row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
9,641
|
const tables = `<root><datagrid id='table1' data='data' border=true font=宋体 fontSize=12 thHeight=18 tdHeight=16>
<column label='序号' prop='sn' width='50' thAlign=center></column>
<column label='样本编号' prop='barCode' width='50'></column>
<column label='样本类型' prop='specimenType' width='50'></column>
<column label='样本量' prop='curCapacity' width='50'></column>
<column label='有效日期' prop='storeEndDate' width='100'></column>
<column label='样本状态' prop='status' width='50'></column>
<column label='样本位置' prop='positionName' width='50'></column>
</datagrid></root>` 转成xml文档
|
21c3627fb20e542d06d510e8a9d60680
|
{
"intermediate": 0.43430766463279724,
"beginner": 0.2709549069404602,
"expert": 0.29473739862442017
}
|
9,642
|
I have a dataset on carbon capture and sequestration technology. I am pasting here that dataset. Can you make a table of it?
Configuration Net plant efficiency, HHV (%) Net electrical output (MW) Makeup Water feeding rate (Tons/hr) Total water withdrawl (Tons/hr) Total capital requirement (TCr) ($/kW-net) Captured CO2 (tons/hr) CO2 released to air (lb-moles/hr) SO2 released to air (lb-moles/hr) Total O&M cost (M$/yr) Total levelized annual cost (M$/yr)(rev req) Capital required (M$) Revenue Required ($/MWh) Cost of CO2 captured ($/ton) Added cost of CCS ($/MWh)
PC0 39.16 617.4 1343 1343 1714 0 24930 258.4 94.96 214.4 1059 52.82 0 0
PC1 38.73 607.5 1667 1667 2570 0 24930 49.81 115.5 291.7 1562 73.04 0 0
PC2 28.59 509 2424 2424 4690 563.3 2844 0 170.8 440.1 2388 131.5 114.4 131.5
PC3 28.05 470.6 2766 2766 5368 531.3 2680 0 168.3 453.3 2527 146.5 125.2 146.5
PC4 32.79 488.7 2074 2074 4905 413.9 4559 0 153.8 424.2 2398 132.1 150.4 132.1
PC5 27.19 405.2 1748 1748 7446 424.9 4515 1.991 160.4 500.8 3018 188 174.6 188
PC6 25.15 496.9 2248 2248 6986 623.4 3149 0 249.6 640.9 3470 196.3 152.1 196.3
PC7 31.91 498.3 1734 1734 4668 513 1375 0 163.4 425.9 2327 130 121.5 130
PC8 31.22 487.5 1814 1814 4827 513 1380 0 160.9 426.4 2354 133 121.6 133
PC9 30.79 480.8 1888 1888 5025 516 1480 0 158 430.6 2417 136.2 122.2 136.2
PC10 40.04 596.7 306.2 0 2398 0 23770 47.48 104.8 266.3 1432 67.88 0 0
PC11 29.47 524.5 409.7 65080 4332 563.1 2843 0 165 421.5 2273 122.2 109.4 122.2
PC12 28.97 486 346.8 89900 4934 531.1 2680 0 161.5 432 2399 135.2 119.1 135.2
PC13 33.83 504.1 364.2 55370 4541 413.9 4559 0 148.8 407.1 2290 122.8 122.8 144.1
PC14 28.22 420.6 307.6 46510 6969 424.9 4515 1.998 156.2 486.8 2932 176.1 169.6 176.1
PC15 25.88 511.9 408.3 59390 0 624.5 3155 0 244.7 624.3 3366 185.5 147.8 185.5
PC16 40.43 602.6 251.3 43600 2317 0 23570 47.43 105.8 263.4 1397 66.48 0 0
|
fc78186280cea3b36e14bdb660c496a2
|
{
"intermediate": 0.3432231843471527,
"beginner": 0.3762318789958954,
"expert": 0.2805449664592743
}
|
9,643
|
#pragma once
class SystemBase;
class ECS
{
private:
typedef std::unordered_map<std::uint8_t, std::vector<SystemBase*>>
SystemsArrayMap;
typedef std::unordered_map<size_t, ComponentBase*>
ComponentTypeIdBaseMap;
struct Record
{
Archetype* archetype;
size_t index;
};
typedef std::unordered_map<size_t, Record> EntityArchetypeMap;
typedef std::vector<Archetype*> ArchetypesArray;
typedef std::unordered_map<size_t, ComponentMask> ComponentMasks;
public:
explicit ECS();
~ECS();
void Update(const std::uint8_t layer, const std::uint32_t delta);
void RegisterEntity(const uint32_t entityId);
void DestroyEntity(const std::uint32_t entityId);
template <class C>
void RegisterComponent();
template<class C, typename... Args>
C* AddComponent(const uint32_t entityId, Args&&... args);
template<class C>
void RemoveComponent(const uint32_t entityId);
template<class C>
C* GetComponent(const uint32_t entityId);
void RegisterSystem(const std::uint8_t& layer, SystemBase* system);
void UnregisterSystem(const std::uint8_t& layer, SystemBase* system);
private:
std::uint32_t entityIdCounter;
SystemsArrayMap systems;
EntityArchetypeMap entityArchetypeMap;
EventBus eventBus_;
ArchetypesArray archetypes;
ComponentMasks componentMasks;
ComponentTypeIdBaseMap componentMap;
};
class SystemBase
{
public:
virtual ~SystemBase() {}
virtual ComponentMask GetComponentMask() const = 0;
virtual void Update(const std::uint32_t elapsedTime, Archetype* archetype) = 0;
};
class ECS;
template <class... Cs>
class System : public SystemBase
{
public:
friend class ECS;
typedef std::function<void(const std::uint32_t, const std::vector<uint32_t>&, Cs*...)> Func;
System(ECS& ecs, const std::uint8_t& layer);
virtual ComponentMask GetComponentMask() const override;
void Action(Func func);
protected:
template<std::size_t Index1, typename T, typename... Ts>
std::enable_if_t<Index1 == sizeof...(Cs)>
Update(const std::uint32_t elapsedMilliseconds,
const ComponentMask& componentMask,
const std::vector<uint32_t>& entityIds,
T& t,
Ts... ts);
template<std::size_t Index1, typename T, typename... Ts>
std::enable_if_t<Index1 != sizeof...(Cs)>
Update(const std::uint32_t elapsedMilliseconds,
const ComponentMask& componentMask,
const std::vector<uint32_t>& entityIds,
T& t,
Ts... ts);
virtual void Update(const std::uint32_t elapsedMilliseconds,
Archetype* archetype) override;
ECS& ecs_;
ComponentMask componentMask_;
Func func_;
bool funcStatus_;
};
Can you create an event bus system that can work with this?
|
da6a34413b53857e795e4ec98a20da8e
|
{
"intermediate": 0.37641915678977966,
"beginner": 0.2932673990726471,
"expert": 0.33031344413757324
}
|
9,644
|
<datagrid id='table1' data='data' border=true font=宋体 fontSize=12 thHeight=18 tdHeight=16>
<column label='序号' prop='sn' width='50' thAlign=center></column>
<column label='样本编号' prop='barCode' width='50'></column>
<column label='样本类型' prop='specimenType' width='50'></column>
<column label='样本量' prop='curCapacity' width='50'></column>
<column label='有效日期' prop='storeEndDate' width='100'></column>
<column label='样本状态' prop='status' width='50'></column>
<column label='样本位置' prop='positionName' width='50'></column>
</datagrid> 用正则给没有引号的属性值加引号 并测试
|
a266090d8697790c74094cac06d21b28
|
{
"intermediate": 0.30615827441215515,
"beginner": 0.3883790373802185,
"expert": 0.30546265840530396
}
|
9,645
|
Here is my C# solution of a temporary storage please check it for any optimization for performance or logic:
Or if there is a built-in type in C# that do the same:
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
namespace Test;
public class Cache<TKey, TValue> where TKey : notnull
{
public TimeSpan DefaultExpireAfter = TimeSpan.FromMinutes(2);
public int ExpiryCheckIntervalMs = 10_000; //10 Seconds
private readonly Dictionary<TKey, CacheItem<TValue>> _cache = new();
private readonly object _lock = new();
private readonly object _expireLock = new();
public void Store(TKey key, TValue? value, TimeSpan expiresAfter)
{
lock (_lock)
_cache[key] = new CacheItem<TValue>(value, expiresAfter);
RemoveExpired();
}
public void Store(TKey key, TValue? value)
{
lock (_lock)
_cache[key] = new CacheItem<TValue>(value, DefaultExpireAfter);
RemoveExpired();
}
public TValue? Get(TKey key, bool returnDefaultIfExpired = true)
{
lock (_lock)
{
if (!_cache.TryGetValue(key, out var item)) return default;
if (!item.IsExpired)
return item.Value;
_cache.Remove(key);
return returnDefaultIfExpired ? default : item.Value;
}
}
public TValue? Remove(TKey key)
{
lock (_lock)
if (_cache.Remove(key, out var item))
return item.Value;
return default;
}
public TValue? this[TKey key, bool returnDefaultIfExpired = true]
{
get => Get(key, returnDefaultIfExpired);
set => Store(key, value);
}
public TValue? this[TKey key, TimeSpan expiresAfter]
{
get => Get(key);
set => Store(key, value, expiresAfter);
}
public void RemoveExpired()
{
//Return if already running
if (!Monitor.TryEnter(_expireLock, 0)) return;
//_expireLock is taken
new Thread(RemoveLooper) { IsBackground = true }.Start();
}
private void RemoveLooper()
{
while (_cache.Count != 0)
{
//Get Expired Keys without locking
var expiredKeys = _cache
.Where(i => i.Value.IsExpired)
.Select(i => i.Key)
.ToArray();
//Continue if none found
if (expiredKeys.Length == 0)
{
Thread.Sleep(ExpiryCheckIntervalMs); //Sleep
continue;
}
try
{
//Lock on _cache's set/get lock
Monitor.Enter(_lock);
foreach (var key in expiredKeys)
{
//Check again if item exists (Maybe deleted before locking)
if (!_cache.TryGetValue(key, out var item)) continue;
//Check if expired again (Maybe updated before locking)
if (item.IsExpired)
_cache.Remove(key); //Expired -> Remove
}
}
finally
{
//Release _lock
Monitor.Exit(_lock);
}
Thread.Sleep(ExpiryCheckIntervalMs); //Sleep
}
//Release _expireLock
Monitor.Exit(_expireLock);
}
private class CacheItem<T>
{
public T? Value { get; }
public bool IsExpired => DateTimeOffset.Now - Created >= ExpiresAfter;
private DateTimeOffset Created { get; }
private TimeSpan ExpiresAfter { get; }
public CacheItem(T? value, TimeSpan expiresAfter)
{
Value = value;
Created = DateTimeOffset.Now;
ExpiresAfter = expiresAfter;
}
}
}
|
3abb2a5ddb68c5976066d0a2ee4bcc34
|
{
"intermediate": 0.35618939995765686,
"beginner": 0.37562692165374756,
"expert": 0.2681836783885956
}
|
9,646
|
Here is my C# solution of a temporary storage please check it for any optimization for performance or logic:
Or if there is a built-in type in C# that do the same:
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
namespace Test;
public class Cache<TKey, TValue> where TKey : notnull
{
public TimeSpan DefaultExpireAfter = TimeSpan.FromMinutes(2);
public int ExpiryCheckIntervalMs = 10_000; //10 Seconds
private readonly Dictionary<TKey, CacheItem<TValue>> _cache = new();
private readonly object _lock = new();
private readonly object _expireLock = new();
public void Store(TKey key, TValue? value, TimeSpan expiresAfter)
{
lock (_lock)
_cache[key] = new CacheItem<TValue>(value, expiresAfter);
RemoveExpired();
}
public void Store(TKey key, TValue? value)
{
lock (_lock)
_cache[key] = new CacheItem<TValue>(value, DefaultExpireAfter);
RemoveExpired();
}
public TValue? Get(TKey key, bool returnDefaultIfExpired = true)
{
lock (_lock)
{
if (!_cache.TryGetValue(key, out var item)) return default;
if (!item.IsExpired)
return item.Value;
_cache.Remove(key);
return returnDefaultIfExpired ? default : item.Value;
}
}
public TValue? Remove(TKey key)
{
lock (_lock)
if (_cache.Remove(key, out var item))
return item.Value;
return default;
}
public TValue? this[TKey key, bool returnDefaultIfExpired = true]
{
get => Get(key, returnDefaultIfExpired);
set => Store(key, value);
}
public TValue? this[TKey key, TimeSpan expiresAfter]
{
get => Get(key);
set => Store(key, value, expiresAfter);
}
public void RemoveExpired()
{
//Return if already running
if (!Monitor.TryEnter(_expireLock, 0)) return;
//_expireLock is taken
new Thread(RemoveLooper) { IsBackground = true }.Start();
}
private void RemoveLooper()
{
while (_cache.Count != 0)
{
//Get Expired Keys without locking
var expiredKeys = _cache
.Where(i => i.Value.IsExpired)
.Select(i => i.Key)
.ToArray();
//Continue if none found
if (expiredKeys.Length == 0)
{
Thread.Sleep(ExpiryCheckIntervalMs); //Sleep
continue;
}
try
{
//Lock on _cache's set/get lock
Monitor.Enter(_lock);
foreach (var key in expiredKeys)
{
//Check again if item exists (Maybe deleted before locking)
if (!_cache.TryGetValue(key, out var item)) continue;
//Check if expired again (Maybe updated before locking)
if (item.IsExpired)
_cache.Remove(key); //Expired -> Remove
}
}
finally
{
//Release _lock
Monitor.Exit(_lock);
}
Thread.Sleep(ExpiryCheckIntervalMs); //Sleep
}
//Release _expireLock
Monitor.Exit(_expireLock);
}
private class CacheItem<T>
{
public T? Value { get; }
public bool IsExpired => DateTimeOffset.Now - Created >= ExpiresAfter;
private DateTimeOffset Created { get; }
private TimeSpan ExpiresAfter { get; }
public CacheItem(T? value, TimeSpan expiresAfter)
{
Value = value;
Created = DateTimeOffset.Now;
ExpiresAfter = expiresAfter;
}
}
}
|
68032c1e4d67e3cd35550353aa5c7631
|
{
"intermediate": 0.35618939995765686,
"beginner": 0.37562692165374756,
"expert": 0.2681836783885956
}
|
9,647
|
make it like this: user can use /encfile command to encrypt files and obtain a key for the decryption of file... user can use /decfile to decrypt the file who sended via the key previously obtained in /encfile step
|
5fe63007c19d112841865a91a696931d
|
{
"intermediate": 0.36664479970932007,
"beginner": 0.17421697080135345,
"expert": 0.45913827419281006
}
|
9,648
|
void signUpWithEmailAndPassword(String email, String password, String firstName, String lastName, String photoUrl, int squat, int bench,int deadlift)async {
try {
// Create user account
UserCredential userCredential = await createUserWithEmailAndPassword(email, password);
// Update user profile
var user = userCredential.user;
await updateUserProfile(user!, firstName, lastName, photoUrl);
// Save user data to Firestore
await saveUserData(user, firstName, lastName, photoUrl, squat, bench,deadlift );
// Navigate to the home screen or next step in the sign-up process
Navigator.pushReplacement( context as BuildContext,
MaterialPageRoute(
builder: (context) => MainPage(),
),
);
} catch (e) {
// Handle errors
// ...
}
} how input that in button ?
|
d8c3925edf7277dbc7e6a748289ba8db
|
{
"intermediate": 0.5471599102020264,
"beginner": 0.24360109865665436,
"expert": 0.2092389166355133
}
|
9,649
|
maya2023 python 报错 No module named 'PIL'
|
81131e346004257f79107762baf5e7b8
|
{
"intermediate": 0.2891501486301422,
"beginner": 0.3389858603477478,
"expert": 0.3718640208244324
}
|
9,650
|
how to use abaqus *imperfection key word
|
b9c0125d3cb4e8beb515282913be3849
|
{
"intermediate": 0.4247134029865265,
"beginner": 0.25487828254699707,
"expert": 0.32040831446647644
}
|
9,651
|
EntityOutOfBoundsEvent event{ entities[i], p[i].x }; Says no instance of constructor matches argument list struct Event
{
virtual ~Event() {}
};struct EntityOutOfBoundsEvent : public Event
{
std::uint32_t entityId;
float xPosition;
};
|
bcb93c1807a9852cbee54d9815e397ee
|
{
"intermediate": 0.4412343502044678,
"beginner": 0.36866089701652527,
"expert": 0.19010470807552338
}
|
9,652
|
Write a code in C language to obtain CPUID
|
f1e159ec634918603ccfa88b548e8f4d
|
{
"intermediate": 0.16320423781871796,
"beginner": 0.33662039041519165,
"expert": 0.5001752972602844
}
|
9,653
|
how to call the System.out.println java function in javascript code using rhino engine?
|
1da36a074e5735f56bfcee07cc3489cb
|
{
"intermediate": 0.39677006006240845,
"beginner": 0.39526185393333435,
"expert": 0.2079681009054184
}
|
9,654
|
import os
import base64
import logging
import telebot
from cryptography.fernet import Fernet
# Set up the Telegram bot
bot = telebot.TeleBot(os.getenv("BOT_TOKEN"))
# Define constants
START_MESSAGE = "I'm PENT. Please select an option:\nType /enctext to encrypt a message.\nType /dectext to decrypt a message.\n Use /encfile to encrypt a file.\n Use /decfile to decrypt a file using your key.\n My Creator: @itsUndead"
ENCRYPT_MESSAGE = "Please enter the message you want to encrypt."
DECRYPT_KEY_MESSAGE = "Please enter the encryption key."
DECRYPT_MESSAGE_MESSAGE = "Please reply to the message you want to decrypt with the encryption key."
ERROR_MESSAGE = "Unable to perform the requested operation. Please try again later."
HELP_MESSAGE = "Use /entext to encrypt a message.\n"\
"Use /dectext to decrypt a message using your key.\n"\
"Use /encfile to encrypt a file.\n"\
"Use /decfile to decrypt a file using your key.\n"\
"My Creator: @itsUndead"
FILE_ENCRYPTED_MESSAGE = "File Encrypted!"
FILE_ENCRYPTION_KEY_MESSAGE = "File Encryption Key (keep it private and secure!)"
FILE_ENCRYPTION_FAILED = "Error File Encryption!"
FILE_GET_MESSAGE = "Send the file to encode or decode, I’ll wait here…"
FILE_DECRYPTION_FAILED = "Error File Decryption!"
# Set up logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
# Define decorators
def command_handler(commands):
def decorator(func):
@bot.message_handler(commands=commands)
def wrapper(message):
try:
func(message)
except Exception as e:
logging.error(f"Error in {func.name}: {e}")
bot.send_message(message.chat.id, ERROR_MESSAGE)
return wrapper
return decorator
###########################
# Define command handlers #
###########################
@command_handler(['start'])
def start(message):
bot.send_message(message.chat.id, START_MESSAGE)
@command_handler(['help'])
def help(message):
bot.send_message(message.chat.id, HELP_MESSAGE)
@command_handler(['enctext'])
def encrypt(message):
bot.send_message(message.chat.id, ENCRYPT_MESSAGE)
bot.register_next_step_handler(message, encrypt_message)
@command_handler(['dectext'])
def decrypt(message):
bot.send_message(message.chat.id, DECRYPT_KEY_MESSAGE)
bot.register_next_step_handler(message, decrypt_message_key)
###############################################
# Define file handlers and encryption methods #
###############################################
def encrypt_file(file_path):
try:
key = Fernet.generate_key()
cipher_suite = Fernet(key)
with open(file_path, 'rb') as file:
contents = file.read()
encrypted_contents = cipher_suite.encrypt(contents)
encrypted_file_path = f"{file_path}.encrypted"
with open(encrypted_file_path, 'wb') as file:
file.write(encrypted_contents)
return key, encrypted_file_path
except Exception as e:
logging.error(f"Error in encrypt_file: {e}")
return None, None
def decrypt_file(file_path, key):
try:
cipher_suite = Fernet(key)
with open(file_path, 'rb') as file:
contents = file.read()
decrypted_contents = cipher_suite.decrypt(contents)
decrypted_file_path = f"{file_path}.decrypted"
with open(decrypted_file_path, 'wb') as file:
file.write(decrypted_contents)
return decrypted_file_path
except Exception as e:
logging.error(f"Error in decrypt_file: {e}")
return None
@bot.message_handler(content_types=[
'document', 'application', 'audio', 'video', 'voice', 'photo'
])
def handle_file(message):
chat_id = message.chat.id
file_info = bot.get_file(message.document.file_id)
if message.text == '/encfile':
downloaded_file = bot.download_file(file_info.file_path)
file_name = message.document.file_name
with open(file_name, 'wb') as file:
file.write(downloaded_file)
key, encrypted_file_path = encrypt_file(
file_name) # Encrypt the file contents
if key is not None:
bot.send_message(chat_id, FILE_ENCRYPTED_MESSAGE)
bot.send_document(chat_id,
open(encrypted_file_path,
'rb')) # Send the encrypted file back to the user
bot.send_message(chat_id, FILE_ENCRYPTION_KEY_MESSAGE)
bot.send_message(chat_id, key) # Send the key to the user
os.remove(file_name) # Remove the original file from the server
os.remove(
encrypted_file_path) # Remove the encrypted file from the server
else:
bot.send_message(chat_id, FILE_ENCRYPTION_FAILED)
elif message.text == '/decfile':
key = message.reply_to_message.text # Get the key from the previous message
downloaded_file = bot.download_file(file_info.file_path)
file_name = message.document.file_name
with open(file_name, 'wb') as file:
file.write(downloaded_file)
decrypted_file_path = decrypt_file(file_name,
key) # Decrypt the file contents
if decrypted_file_path is not None:
bot.send_message(chat_id, "Here is your decrypted file:")
bot.send_document(chat_id,
open(decrypted_file_path,
'rb')) # Send the decrypted file back to the user
os.remove(file_name) # Remove the original file from the server
os.remove(
decrypted_file_path) # Remove the decrypted file from the server
else:
bot.send_message(chat_id, FILE_DECRYPTION_FAILED)
os.remove(file_name) # Remove the original file from the server
else:
bot.send_message(
chat_id,
"Invalid command. Please use /encfile or /decfile to encrypt or decrypt the file."
)
@bot.message_handler(commands=['encfile', 'decfile'])
def handle_command(message):
chat_id = message.chat.id
if message.text == '/encfile':
bot.send_message(chat_id, FILE_GET_MESSAGE)
elif message.text == '/decfile':
bot.send_message(
chat_id,
"Please upload the file you want to decrypt and reply to the message containing the key obtained in the /encfile step."
)
######################################
# Define message encryption handlers #
######################################
def encrypt_message(message):
try:
key = Fernet.generate_key()
cipher_suite = Fernet(key)
key_encoded = base64.urlsafe_b64encode(key)
encrypted_message = cipher_suite.encrypt(message.text.encode())
encoded_message = base64.urlsafe_b64encode(encrypted_message)
response = f"<b>Encrypted message:</b>\n<code>{encoded_message.decode()}</code>\n\n<b>Encryption key:</b>\n<code>{key_encoded.decode()}</code>\n\nPlease keep the encryption key secure as it’s needed to decrypt the message."
bot.send_message(message.chat.id, response, parse_mode="HTML")
except Exception as e:
logging.error(f"Error in encrypt_message: {e}")
bot.send_message(message.chat.id, ERROR_MESSAGE)
def decrypt_message_key(message):
try:
key = base64.urlsafe_b64decode(message.text.encode())
bot.send_message(message.chat.id, DECRYPT_MESSAGE_MESSAGE)
bot.register_next_step_handler(message, decrypt_message, key)
except:
bot.send_message(message.chat.id,
"Invalid encryption key. Please try again.")
def decrypt_message(message, key):
try:
cipher_suite = Fernet(key)
encrypted_message = base64.urlsafe_b64decode(message.text.encode())
decrypted_message = cipher_suite.decrypt(encrypted_message)
response = f"<b>Decrypted message:</b>\n<code>{decrypted_message.decode()}</code>"
bot.send_message(message.chat.id, response, parse_mode="HTML")
except:
bot.send_message(
message.chat.id,
"Unable to decrypt message. Please make sure the message and encryption key are correct."
)
#################
# Start the bot #
#################
bot.polling()
my bot sends me this response but its not correct: Invalid command. Please use /encfile or /decfile to encrypt or decrypt the file.
fix it for me please using @command_handler() method
|
c59fea384596ccb8a03c8cff44e04d4b
|
{
"intermediate": 0.3841049075126648,
"beginner": 0.42029663920402527,
"expert": 0.1955985128879547
}
|
9,655
|
Module "path" has been externalized for browser compatibilit
|
9d14018634cea9eb30184920494f168d
|
{
"intermediate": 0.3464641571044922,
"beginner": 0.3038395941257477,
"expert": 0.34969624876976013
}
|
9,656
|
in unreal engine 4, how to make an actor move with the platform beneath it, while also the actor can move by itself. for example, adding their location to each other.
|
453a7ff37009147e8ead7668a571d7c0
|
{
"intermediate": 0.2478255182504654,
"beginner": 0.1588466316461563,
"expert": 0.5933278203010559
}
|
9,657
|
php how to run a command like you would in cmd
|
edaf937904fdfe89c2b7c92a40a07628
|
{
"intermediate": 0.34740880131721497,
"beginner": 0.44032010436058044,
"expert": 0.2122710645198822
}
|
9,658
|
hi
|
3eb5a85e410041bfffa9f4276a6d4cb0
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
9,659
|
i have an EmptyObject called “Training Area”, in this object i have Player (Agent for ML Agents), Floor, WallTop, WallBottom, WallRight, WallLeft and all spawning foods.
ok, i copied my "Training Area" multiple times to get ML Agents training faster.
but it seems that the learning process is only on one, the very first agent. all the rest synchronously go to the upper right corner of the map with slight deviations.
after about 1000 steps, I have only one agent jerking in random directions, all the other agents just go into the wall, each in his own. it feels like there is not enough batch or buffer.
here's my circletest.yaml:
behaviors:
PlayerLearning:
trainer_type: ppo
hyperparameters:
batch_size: 32
buffer_size: 256
learning_rate: 0.0003
beta: 0.005
epsilon: 0.2
lambd: 0.95
num_epoch: 3
learning_rate_schedule: linear
network_settings:
normalize: false
hidden_units: 20
num_layers: 2
reward_signals:
extrinsic:
gamma: 0.99
strength: 1.0
keep_checkpoints: 5
max_steps: 1000000
time_horizon: 64
summary_freq: 1000
|
1ab63c4966dbf0743a3dcc7de98b9f5d
|
{
"intermediate": 0.29451870918273926,
"beginner": 0.2837986946105957,
"expert": 0.42168259620666504
}
|
9,660
|
Py qt
|
ab449204819fb0ef11367dbcba03a8e2
|
{
"intermediate": 0.24666285514831543,
"beginner": 0.34530216455459595,
"expert": 0.4080349802970886
}
|
9,661
|
The car's initial position is at a negative x value like -1.2 . Based on the following information, implement an end to end PID controller.# Tasks
1. Plot the reference in `RVIZ` as a yellow line.
$$
Reference = y = f(x) =
\begin{cases}
0, & \text{for } 0\leq x\leq 15\\
2, & \text{for } 15\leq x\leq 30\\
5, & \text{for } 30\leq x\leq 45\\
10, & \text{for } 45\leq x\leq 60\\
15, & \text{for } 60\leq x\leq 200\\
STOP, & \text{for } 200\le x\\
\end{cases}
$$
Marker Details:
Scale → `0.1`
Action → `ADD`
Type → `LINE_STRIP`
Frame_id → `odom`
2. Control the steering of the car using a `PID` controller.
Steps
1. Get current `y` of the car.
2. Calculate y `error` to reference, `derivative` of the error and `integral` of the error.
3. Combine the errors calculated with the `PID` methodology to generate steering input with `PID gains` [ You will tune these gains in part d. ].
4. Command the car using calculated `steering` input.
- Car Dynamics [ Please ensure these constraints are followed. ]
- Speed → `2 m/s` [ Use `rosparam` to set this speed in your launch file. We should be able to change the speed to verify the response for slower and faster speeds. Parameter Name → `Vmax` Type → `double` ]
- Steering angle → `[-25 deg, 25 deg]`
3. Car should STOP at the end of the reference.
- This can be done by commanding speed of `0 m/s`
4. Tune PID controller to get a reasonable rise time, overshoot, settling time and steady state.
- In the context of this assignment, reasonable implies that the reference is followed with an error `≤ 0.5m` by the end of current section and steady-state error `≤ 0.1 m` [ i.e at the end of section 2 of the reference → `x = 30`, the y error `≤ 0.5m` and at `x = 200`, the y error `≤ 0.1 m` ].
- You can plot the error using `rqt_plot` to visualize the PID parameters.
- You can also change the speed of the car between `1 m/s` and `3 m/s` to tune your controller for all speeds between `1 m/s` to `3 m/s`. (self-study task)
- You can calculate the performance of you controller using the `MAE` metric. (self-study task) [reasonable → `MAE ≤ 0.6` at the end of all sections. ]
- You can also turn the integral component on after the reference stabilizes for some time. This is how most real world PID controller work. This will improve the performance of your controller. (self-study task)
Deliverable → The car must be able to follow the reference with reasonable PID parameters.**
At `x = 70`, the car is quite far from the provided reference. But as the reference doesn't change till `x = 200`, the error reduces to 0. This is what is referred to as steady-state error.
|
d5f2582458fa37d3a3a5a2fe40c7789e
|
{
"intermediate": 0.30866119265556335,
"beginner": 0.5001901388168335,
"expert": 0.19114868342876434
}
|
9,662
|
i need to add ray perception sensor 2d to 2d agent on unity, here's my PlayerController.cs:
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Sensors.Reflection;
[AddComponentMenu("")]
public class PlayerController : Agent
{
public float speed = 5f;
private Rigidbody2D rb;
private FoodSpawner foodSpawner;
private Vector3 initialPosition;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
initialPosition = transform.position;
}
void Update()
{
ManageEpisode();
}
private void ManageEpisode()
{
SharedAcademy.EpisodeTimeout -= Time.deltaTime;
int remainingFoodCount = foodSpawner.GetComponentsInChildren<Food>().Length;
if (SharedAcademy.EpisodeTimeout <= 0 || remainingFoodCount == 0)
{
ResetPlayerEpisode();
foodSpawner.SpawnFood();
SharedAcademy.EpisodeTimeout = 30f;
}
}
public override void OnEpisodeBegin()
{
rb.velocity = Vector2.zero;
// Get Training Area position
Vector3 trainingAreaPosition = foodSpawner.transform.position;
// Calculate the random position relative to the Training Area
float randomX = UnityEngine.Random.Range(-foodSpawner.spawnRange, foodSpawner.spawnRange) + trainingAreaPosition.x;
float randomY = UnityEngine.Random.Range(-foodSpawner.spawnRange, foodSpawner.spawnRange) + trainingAreaPosition.y;
initialPosition = new Vector3(randomX, randomY, 0);
transform.position = initialPosition;
}
public override void CollectObservations(VectorSensor sensor)
{
// The observations from ray-based sensor will be automatically collected
}
/*public override void CollectObservations(VectorSensor sensor)
{
// Agent’s position
sensor.AddObservation(transform.position);
sensor.AddObservation(rb.velocity);
if (foodSpawner != null)
{
// Distance calculations
float minDistance = float.MaxValue;
Vector2 closestFoodPos = Vector2.zero;
int addedFoodObs = 0;
int maxFoodObserve = 10; // Set a maximum number of food items to track.
foreach (var food in foodSpawner.GetComponentsInChildren<Food>())
{
float distance = Vector2.Distance(transform.position, food.transform.position);
if (addedFoodObs < maxFoodObserve)
{
sensor.AddObservation(food.transform.position); // Add the food position to the observations
addedFoodObs++;
}
if (distance < minDistance)
{
minDistance = distance;
closestFoodPos = food.transform.position;
}
}
// Add closest food position and distance
sensor.AddObservation(closestFoodPos);
sensor.AddObservation(minDistance);
}
}*/
public override void OnActionReceived(ActionBuffers actions)
{
float moveHorizontal = actions.ContinuousActions[0];
float moveVertical = actions.ContinuousActions[1];
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
rb.AddForce(movement * speed);
float minDistance = float.MaxValue;
foreach (var food in foodSpawner.GetComponentsInChildren<Food>())
{
float distance = Vector2.Distance(transform.position, food.transform.position);
if (distance < minDistance)
{
minDistance = distance;
}
}
// Add a penalty proportional to the distance to the nearest food.
SetReward(-minDistance * Time.fixedDeltaTime);
}
public void AddRewardOnEatingFood()
{
AddReward(1f);
}
public override void Heuristic(in ActionBuffers actionsOut)
{
var continuousActionsOut = actionsOut.ContinuousActions;
continuousActionsOut[0] = Input.GetAxis("Horizontal");
continuousActionsOut[1] = Input.GetAxis("Vertical");
}
public void ResetPlayerEpisode()
{
EndEpisode();
transform.position = initialPosition; // Reset player position to the initial position
rb.velocity = Vector2.zero;
}
public void SetFoodSpawner(FoodSpawner spawner)
{
foodSpawner = spawner;
}
}
|
fc503d1c16a6d7caed3871c2376edb8c
|
{
"intermediate": 0.29112234711647034,
"beginner": 0.40331706404685974,
"expert": 0.3055606186389923
}
|
9,663
|
i need to add ray perception sensor 2d to 2d agent on unity, here's my PlayerController.cs:
using UnityEngine;
using Unity.MLAgents;
using Unity.MLAgents.Actuators;
using Unity.MLAgents.Sensors;
using Unity.MLAgents.Sensors.Reflection;
[AddComponentMenu("")]
public class PlayerController : Agent
{
public float speed = 5f;
private Rigidbody2D rb;
private FoodSpawner foodSpawner;
private Vector3 initialPosition;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
initialPosition = transform.position;
}
void Update()
{
ManageEpisode();
}
private void ManageEpisode()
{
SharedAcademy.EpisodeTimeout -= Time.deltaTime;
int remainingFoodCount = foodSpawner.GetComponentsInChildren<Food>().Length;
if (SharedAcademy.EpisodeTimeout <= 0 || remainingFoodCount == 0)
{
ResetPlayerEpisode();
foodSpawner.SpawnFood();
SharedAcademy.EpisodeTimeout = 30f;
}
}
public override void OnEpisodeBegin()
{
rb.velocity = Vector2.zero;
// Get Training Area position
Vector3 trainingAreaPosition = foodSpawner.transform.position;
// Calculate the random position relative to the Training Area
float randomX = UnityEngine.Random.Range(-foodSpawner.spawnRange, foodSpawner.spawnRange) + trainingAreaPosition.x;
float randomY = UnityEngine.Random.Range(-foodSpawner.spawnRange, foodSpawner.spawnRange) + trainingAreaPosition.y;
initialPosition = new Vector3(randomX, randomY, 0);
transform.position = initialPosition;
}
public override void CollectObservations(VectorSensor sensor)
{
// The observations from ray-based sensor will be automatically collected
}
/*public override void CollectObservations(VectorSensor sensor)
{
// Agent’s position
sensor.AddObservation(transform.position);
sensor.AddObservation(rb.velocity);
if (foodSpawner != null)
{
// Distance calculations
float minDistance = float.MaxValue;
Vector2 closestFoodPos = Vector2.zero;
int addedFoodObs = 0;
int maxFoodObserve = 10; // Set a maximum number of food items to track.
foreach (var food in foodSpawner.GetComponentsInChildren<Food>())
{
float distance = Vector2.Distance(transform.position, food.transform.position);
if (addedFoodObs < maxFoodObserve)
{
sensor.AddObservation(food.transform.position); // Add the food position to the observations
addedFoodObs++;
}
if (distance < minDistance)
{
minDistance = distance;
closestFoodPos = food.transform.position;
}
}
// Add closest food position and distance
sensor.AddObservation(closestFoodPos);
sensor.AddObservation(minDistance);
}
}*/
public override void OnActionReceived(ActionBuffers actions)
{
float moveHorizontal = actions.ContinuousActions[0];
float moveVertical = actions.ContinuousActions[1];
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
rb.AddForce(movement * speed);
float minDistance = float.MaxValue;
foreach (var food in foodSpawner.GetComponentsInChildren<Food>())
{
float distance = Vector2.Distance(transform.position, food.transform.position);
if (distance < minDistance)
{
minDistance = distance;
}
}
// Add a penalty proportional to the distance to the nearest food.
SetReward(-minDistance * Time.fixedDeltaTime);
}
public void AddRewardOnEatingFood()
{
AddReward(1f);
}
public override void Heuristic(in ActionBuffers actionsOut)
{
var continuousActionsOut = actionsOut.ContinuousActions;
continuousActionsOut[0] = Input.GetAxis("Horizontal");
continuousActionsOut[1] = Input.GetAxis("Vertical");
}
public void ResetPlayerEpisode()
{
EndEpisode();
transform.position = initialPosition; // Reset player position to the initial position
rb.velocity = Vector2.zero;
}
public void SetFoodSpawner(FoodSpawner spawner)
{
foodSpawner = spawner;
}
}
|
b1489e4a25e0dc1658e79d0289d90779
|
{
"intermediate": 0.29112234711647034,
"beginner": 0.40331706404685974,
"expert": 0.3055606186389923
}
|
9,664
|
Create me a simple Unity game in 2D with a top view. The circle character should WASD in all directions, and food circles will spawn around him. The most important condition is to add ML Agents and then explain to me how to set everything up. If anything, I have Unity and ML Agents installed and imported. I only need the code and instructions on how to make the training of the neural network start, as well as how to switch to keyboard control. The code must be complete and working.
|
f2d5fb53a3e769a28063bdf51823fa8d
|
{
"intermediate": 0.2356054186820984,
"beginner": 0.17129892110824585,
"expert": 0.5930956602096558
}
|
9,665
|
hi
|
5de8bfa53c1269eafec694c8f9653dae
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
9,666
|
i have an EmptyObject called “Training Area”, in this object i have Player (Agent for ML Agents), Floor, WallTop, WallBottom, WallRight, WallLeft and all spawning foods.
ok, i copied my "Training Area" multiple times to get ML Agents training faster.
but it seems that the learning process is only on one, the very first agent. all the rest synchronously go to the upper right corner of the map with slight deviations.
after about 1000 steps, I have only one agent jerking in random directions, all the other agents just go into the wall, each in his own. it feels like there is not enough batch or buffer.
here's my circletest.yaml:
behaviors:
PlayerLearning:
trainer_type: ppo
hyperparameters:
batch_size: 32
buffer_size: 256
learning_rate: 0.0003
beta: 0.005
epsilon: 0.2
lambd: 0.95
num_epoch: 3
learning_rate_schedule: linear
network_settings:
normalize: false
hidden_units: 20
num_layers: 2
reward_signals:
extrinsic:
gamma: 0.99
strength: 1.0
keep_checkpoints: 5
max_steps: 1000000
time_horizon: 64
summary_freq: 1000
|
15d884e69e9548072eb7dab396ccda95
|
{
"intermediate": 0.29451870918273926,
"beginner": 0.2837986946105957,
"expert": 0.42168259620666504
}
|
9,667
|
import {useCallback, useEffect, useState} from "react";
import {ReadyState} from "../enums/readyState";
type CupItem = {
futures_price_micro: number;
quantity: number;
spot_quantity: number;
side: string;
};
export interface BestMicroPrice {
buy: number;
sell: number;
}
export function useRustWsServer() {
const [connection, setConnection] = useState<WebSocket|null>(null);
const [readyState, setReadyState] = useState(0);
const [cup, setCup] = useState<Array<CupItem>>([]);
const [bestMicroPrice, setBestMicroPrice] = useState<BestMicroPrice|null>(null);
const [maxVolume, setMaxVolume] = useState(1);
function splitCupSides(rawData: {[key: number]: CupItem}): Array<CupItem> {
const sellRecords = [];
const buyRecords = [];
let max = 0;
for (const value of Object.values(rawData)) {
if (value.side === "Buy") {
buyRecords.push(value);
} else if (value.side === "Sell") {
sellRecords.push(value);
}
if (value.quantity > max) {
max = value.quantity;
}
}
sellRecords.sort((a, b) => {
return b.futures_price_micro - a.futures_price_micro;
});
buyRecords.sort((a, b) => {
return b.futures_price_micro - a.futures_price_micro;
});
setMaxVolume(max);
return [...sellRecords, ...buyRecords];
}
const cupSubscribe = useCallback((symbol: string, camera: number, zoom: number, rowCount: number) => {
if (null === connection || readyState !== ReadyState.OPEN) return;
connection.send(JSON.stringify({
"commands": [
{
commandType: "SUBSCRIBE_SYMBOL",
symbol,
camera: Math.round(camera / zoom) * zoom,
zoom,
rowCount,
},
],
}));
}, [readyState]);
const cupUnsubscribe = useCallback((symbol: string) => {
if (null === connection || readyState !== ReadyState.OPEN) return;
connection.send(JSON.stringify({
"commands": [
{
commandType: "UNSUBSCRIBE_SYMBOL",
symbol,
},
],
}));
}, [readyState]);
useEffect(() => {
const url = process.env.NEXT_PUBLIC_RUST_WS_SERVER;
if (url) {
const ws = new WebSocket(url);
setConnection(ws);
}
}, []);
useEffect(() => {
if (null !== connection) {
connection.onmessage = (message: MessageEvent) => {
if (!message.data) return;
const data = JSON.parse(message.data);
if (!data?.commands || data.commands.length === 0) return;
const domUpdate = data.commands.find((item: any) => "undefined" !== typeof item.SymbolDomUpdate);
if (!domUpdate) return;
setCup(splitCupSides(domUpdate.SymbolDomUpdate.dom_rows));
setBestMicroPrice({
buy: domUpdate.SymbolDomUpdate.best_prices_futures.best_ask_micro,
sell: domUpdate.SymbolDomUpdate.best_prices_futures.best_bid_micro,
});
};
connection.onopen = () => {
setReadyState(ReadyState.OPEN);
};
connection.onclose = () => {
setReadyState(ReadyState.CLOSED);
};
}
}, [connection]);
return {
readyState,
cupSubscribe,
cupUnsubscribe,
cup,
maxVolume,
bestMicroPrice,
};
}
import {BestMicroPrice, useRustWsServer} from "../../hooks/rustWsServer";
import {createContext, Reducer, useEffect, useReducer, useRef, useState} from "react";
import CupDrawer from "../CupDrawer/CupDrawer";
import {IconButton} from "@mui/material";
import {AddRounded, RemoveRounded} from "@mui/icons-material";
import {ReadyState} from "../../enums/readyState";
import {useSelector} from "react-redux";
import {AppState} from "../../store/store";
interface CupConfigSubscription {
pair: string | null;
zoom: number;
camera: number;
rowCount: number;
}
export const CupControlsContext = createContext<{
cupControlsState: any;
cupControlsDispatcher: any;
}>({
cupControlsState: null,
cupControlsDispatcher: null,
});
const TradingCup = () => {
const symbol = useSelector((state: AppState) => state.screenerSlice.symbol);
const {cup, bestMicroPrice, maxVolume, readyState, cupSubscribe, cupUnsubscribe} = useRustWsServer();
const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbol.toUpperCase()]);
const tickSize = useSelector((state: AppState) => state.binanceTickSize.futures[symbol.toUpperCase()]);
const [cupConfig, setCupConfig] = useState<CupConfigSubscription>({
pair: null,
zoom: 10,
camera: 0,
rowCount: 40,
});
useEffect(() => {
if (symbol) {
setCupConfig({
...cupConfig,
pair: symbol.toUpperCase(),
camera: 0,
});
}
}, [symbol]);
useEffect(() => {
if (readyState === ReadyState.OPEN) {
if (null !== cupConfig.pair) {
cupSubscribe(
cupConfig.pair,
cupConfig.camera,
cupConfig.zoom,
cupConfig.rowCount,
);
}
}
return () => {
if (cupConfig.pair != null) {
cupUnsubscribe(cupConfig.pair);
}
};
}, [
cupConfig.pair,
cupConfig.camera,
cupConfig.zoom,
cupConfig.rowCount,
readyState,
]);
return (
<>
</>
);
};
export default TradingCup;
import {each, get, map, reduce, range, clamp, reverse} from 'lodash'
import {ESide} from "../../interfaces/interfaces";
import {abbreviateNumber, blendColors, blendRGBColors, getRatio, shadeColor} from "../../utils/utils";
import {
bubbleSize, clusterBg,
clusterGreen,
clusterRed,
clustersCountUI,
deepGreen,
deepRed,
lightGreen,
lightRed,
maxClusterWidth,
minuteMs,
rowHeight,
timeFrame,
visibleClustersCount
} from "../../constants/consts";
export default class ClustersClientControllers {
xWidthInMs = timeFrame * clustersCountUI
DOMBorderOffset = 0
abnormalDensities = 200
clusters = []
currentMin = 0
tempCluster = {}
tempCurrentMin
totals = []
tempTotal = {}
root: ClientController
canvasHeight = 0
canvasWidth = 0
tradesArr: any = []
public bestPrices: any = null
clustersCtx
orderFeedCtx
public cameraPrice = null
public zoom = 10
clusterCellWidth
virtualServerTime = null
tradesFilterBySymbol = {}
constructor(root) {
this.root = root
window['clusters'] = this
this.restoreClusterSettings()
}
renderTrades = () => {
this.clearOrderFeed();
reduce(this.tradesArr, (prev, cur, index) => {
this.renderTrade(prev, cur, this.tradesArr.length - (index as any))
prev = cur
console.log(prev);
return prev
})
}
clearOrderFeed = () => {
this.orderFeedCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
}
renderTrade = (prev, item, index) => {
//const anomalyQty = this.root.instruments[this.root.selectedSymbol].anomalies.anomaly_qty;
console.log(item); //
price_float
:
0.4139
price_micro
:
4139000
quantity
:
6
side
:
"Buy"
time
:
1685607036920
//if (size < 1) return;
const ctx = this.orderFeedCtx
let xPos = (this.canvasWidth - (index * (bubbleSize * 1.5))) - bubbleSize;
const offsetFromTop = this.root.tradingDriverController.upperPrice - item.price_micro;
const y = ((offsetFromTop / this.root.tradingDriverController.getZoomedStepMicro()) - 1) * rowHeight
const label = abbreviateNumber(item.quantity * item.price_float)
const {width: textWidth} = ctx.measureText(label);
const itemUsdt = item.quantity * item.price_float;
const tradeFilter = this.getTradeFilterBySymbol(this.getSymbol())
const maxUsdtBubbleAmount = tradeFilter * 30;
const maxPixelBubbleAmount = 35;
const realBubbleSize = (itemUsdt / maxUsdtBubbleAmount) * maxPixelBubbleAmount
const size = clamp(realBubbleSize, (textWidth/2)+3, maxPixelBubbleAmount)
const bubbleX = xPos;
const bubbleY = y + 8;
ctx.beginPath();
let bigRatio = (realBubbleSize / maxPixelBubbleAmount) / 3;
bigRatio = bigRatio > 0.95 ? 0.95 : bigRatio;
ctx.fillStyle = item.side === "Sell" ? deepGreen.lighten(bigRatio).toString() : deepRed.lighten(bigRatio).toString()
ctx.strokeStyle = 'black';
ctx.arc(xPos, bubbleY, size, 0, 2 * Math.PI)
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#FFFFFF"
ctx.fillText(label, bubbleX - (textWidth / 2), (bubbleY + (rowHeight / 2)) - 2)
}
1. В компоненте TradingCup запрашивается cup из useRustWsServer, сделать отрисовку канвас как в методах renderTrade renderTrades .
2. renderTrade renderTrades то другой немного компонент с немного другими данными, нужно использовать его в TradingCup только с нашими данными type CupItem = {
futures_price_micro: number;
quantity: number;
spot_quantity: number;
side: string;
};
3. В методе renderTrade() показатели quantity и price_float перемножаются, чтобы получить объем в $. Нам это не нужно, будем выводить только quantity.
Нужно все отрисовать в канвасе И использовать тоже самое соединение, что установлено в rustWsServer.ts
обязательно везде typescript
|
129b282322b3577b497216d898cbf7ad
|
{
"intermediate": 0.3489033579826355,
"beginner": 0.4464230239391327,
"expert": 0.2046736478805542
}
|
9,668
|
Is the command "set alertemail " run in global or vdom in fortigate
|
b74c19f7b586151a4b26685a863eac65
|
{
"intermediate": 0.4646901488304138,
"beginner": 0.28377699851989746,
"expert": 0.2515328526496887
}
|
9,669
|
This code is for blind protein docking write a code for targeted protein docking which automatically findes the docking site and performs the docking:
import os
import subprocess
from Bio.PDB import PDBParser
class PDBQTParser(PDBParser):
def __init__(self):
super(PDBQTParser, self).__init__()
def _parse_atom_line(self, line):
return super(PDBQTParser, self)._parse_atom_line(line.replace('A ', ' '))
def get_center_and_size(protein_path, ligand_path):
parser = PDBQTParser()
protein_structure = parser.get_structure("protein", protein_path)
ligand_structure = parser.get_structure("ligand", ligand_path)
all_atoms = [atom for atom in protein_structure.get_atoms()] + [atom for atom in ligand_structure.get_atoms()]
all_coords = [atom.coord for atom in all_atoms]
min_coords = [min(coord) for coord in zip(*all_coords)]
max_coords = [max(coord) for coord in zip(*all_coords)]
center = [(max_coords[i] + min_coords[i]) / 2 for i in range(3)]
size = [max_coords[i] - min_coords[i] for i in range(3)]
return center, size
vina_path = "\"C:/Program Files (x86)/The Scripps Research Institute/Vina/vina.exe\""
protein_folder = os.path.join(os.getcwd(), "targetproteinfordocking")
ligand_folder = os.path.join(os.getcwd(), "Ligand")
output_folder = os.path.join(os.getcwd(), "Outputs")
proteins = [os.path.join(protein_folder, f) for f in os.listdir(protein_folder) if f.endswith('.pdbqt')]
ligands = [os.path.join(ligand_folder, f) for f in os.listdir(ligand_folder) if f.endswith('.pdbqt')]
def run_vina(protein_path, ligand_path, output_path):
center, size = get_center_and_size(protein_path, ligand_path)
# Command
command = '{} --receptor "{}" --ligand "{}" --center_x {} --center_y {} --center_z {} --size_x {} --size_y {} --size_z {} --out "{}" --log "{}.log"'.format(
vina_path, protein_path, ligand_path, center[0], center[1], center[2], size[0], size[1], size[2], output_path, output_path)
print("Executing command:", command) # Debugging line
subprocess.call(command, shell=True)
# Iterate through all protein and ligand combinations
for protein_path in proteins:
for ligand_path in ligands:
protein = os.path.basename(protein_path).split('.')[0]
ligand = os.path.basename(ligand_path).split('.')[0]
output_filename = "{}_{}_docked.pdbqt".format(protein, ligand)
output_path = os.path.join(output_folder, output_filename)
# Run Vina
run_vina(protein_path, ligand_path, output_path)
|
fa64968220b0836ef6a36849e39a2109
|
{
"intermediate": 0.25712108612060547,
"beginner": 0.516254723072052,
"expert": 0.22662417590618134
}
|
9,670
|
how to use adb commands and RK DriverInstall.exe to upgrade the firmware of a single board computer running Linux system on a Windows host?
|
af459baf4de2bdcedd100aebefe16660
|
{
"intermediate": 0.47109270095825195,
"beginner": 0.26657453179359436,
"expert": 0.2623327672481537
}
|
9,671
|
File "C:\Users\yuanfx03\AppData\Local\Temp/ipykernel_22464/3736060409.py", line 1, in <module>
pyperclip.copy(1)
AttributeError: module 'pyperclip' has no attribute 'copy'
|
c9a3f270cdbbedc4289f5c4df175709e
|
{
"intermediate": 0.43633636832237244,
"beginner": 0.2737398147583008,
"expert": 0.28992387652397156
}
|
9,672
|
The car's initial position is at a negative x value like -1.2 . Based on the following information, implement an end to end PID controller.# Tasks
1. Plot the reference in `RVIZ` as a yellow line.
$$
Reference = y = f(x) =
\begin{cases}
0, & \text{for } 0\leq x\leq 15\\
2, & \text{for } 15\leq x\leq 30\\
5, & \text{for } 30\leq x\leq 45\\
10, & \text{for } 45\leq x\leq 60\\
15, & \text{for } 60\leq x\leq 200\\
STOP, & \text{for } 200\le x\\
\end{cases}
$$
Marker Details:
Scale → `0.1`
Action → `ADD`
Type → `LINE_STRIP`
Frame_id → `odom`
2. Control the steering of the car using a `PID` controller.
Steps
1. Get current `y` of the car.
2. Calculate y `error` to reference, `derivative` of the error and `integral` of the error.
3. Combine the errors calculated with the `PID` methodology to generate steering input with `PID gains` [ You will tune these gains in part d. ].
4. Command the car using calculated `steering` input.
- Car Dynamics [ Please ensure these constraints are followed. ]
- Speed → `2 m/s` [ Use `rosparam` to set this speed in your launch file. We should be able to change the speed to verify the response for slower and faster speeds. Parameter Name → `Vmax` Type → `double` ]
- Steering angle → `[-25 deg, 25 deg]`
3. Car should STOP at the end of the reference.
- This can be done by commanding speed of `0 m/s`
4. Tune PID controller to get a reasonable rise time, overshoot, settling time and steady state.
- In the context of this assignment, reasonable implies that the reference is followed with an error `≤ 0.5m` by the end of current section and steady-state error `≤ 0.1 m` [ i.e at the end of section 2 of the reference → `x = 30`, the y error `≤ 0.5m` and at `x = 200`, the y error `≤ 0.1 m` ].
- You can plot the error using `rqt_plot` to visualize the PID parameters.
- You can also change the speed of the car between `1 m/s` and `3 m/s` to tune your controller for all speeds between `1 m/s` to `3 m/s`. (self-study task)
- You can calculate the performance of you controller using the `MAE` metric. (self-study task) [reasonable → `MAE ≤ 0.6` at the end of all sections. ]
- You can also turn the integral component on after the reference stabilizes for some time. This is how most real world PID controller work. This will improve the performance of your controller. (self-study task)
Deliverable → The car must be able to follow the reference with reasonable PID parameters.**
At `x = 70`, the car is quite far from the provided reference. But as the reference doesn't change till `x = 200`, the error reduces to 0. This is what is referred to as steady-state error.
|
6e8e53fe086707e1bf419006b88aed73
|
{
"intermediate": 0.30866119265556335,
"beginner": 0.5001901388168335,
"expert": 0.19114868342876434
}
|
9,673
|
Hi
|
fbc9ec55eb5f206eab40dbbca51387a9
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
9,674
|
i need make sql query for get 2 tables
|
9d048389e39483dec927d253f2762030
|
{
"intermediate": 0.45776984095573425,
"beginner": 0.29968079924583435,
"expert": 0.242549329996109
}
|
9,675
|
brew install git
zsh: command not found: brew
|
4241c5085eb618acff020cc9ca446329
|
{
"intermediate": 0.4327731728553772,
"beginner": 0.2823120355606079,
"expert": 0.2849147915840149
}
|
9,676
|
i have two dataframe whichi is a and b, both index is date. make a new dataframe which equal a divide b.
|
0142468d3666078451076c006ac74b2f
|
{
"intermediate": 0.42102667689323425,
"beginner": 0.25996434688568115,
"expert": 0.31900903582572937
}
|
9,677
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
binance_futures = ccxt.binance({ 'option': { 'defaultMarket': 'futures' } })
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '15m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '15m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '15m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR in order execution : The signal time is: 2023-06-02 10:18:35 :buy
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 184, in <module>
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 103, in order_execution
account_balance = binance_futures.fetch_balance()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 2393, in fetch_balance
response = getattr(self, method)(self.extend(request, requestParams))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2861, in fetch2
request = self.sign(path, api, method, params, headers, body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7162, in sign
self.check_required_credentials()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3016, in check_required_credentials
raise AuthenticationError(self.id + ' requires "' + key + '" credential')
ccxt.base.errors.AuthenticationError: binance requires "apiKey" credential
|
5302926cc72af81eda5485ed6b6561cb
|
{
"intermediate": 0.45019787549972534,
"beginner": 0.4073549807071686,
"expert": 0.1424470990896225
}
|
9,678
|
How to check whether a variable is a positive integer in JavaScript?
|
86936ce49d6504da79d8d7b6a590c519
|
{
"intermediate": 0.4157763123512268,
"beginner": 0.42415785789489746,
"expert": 0.16006581485271454
}
|
9,679
|
How to check whether a variable is a positive integer in JavaScript?
|
01a9030820cf066f6dba9a29cc288333
|
{
"intermediate": 0.4157763123512268,
"beginner": 0.42415785789489746,
"expert": 0.16006581485271454
}
|
9,680
|
Sure, here’s how you can solve this problem using Node.js and the xlsx package:
1. Install the xlsx package using npm install xlsx.
2. Load the Excel file into a workbook with const workbook = xlsx.readFile('your_filename.xlsx').
3. Get the data from the first sheet with const worksheet = workbook.Sheets[workbook.SheetNames[0]]; const data = xlsx.utils.sheet_to_json(worksheet, { header: 1 }).
4. Find the merged header row with const mergedIndex = data.findIndex(row => row[0] === undefined).
5. Unmerge the header row with const columnHeaders = data[mergedIndex + 1].map((cellValue, index) => [data[mergedIndex][index] || '', cellValue]); const unmergedData = data.slice(mergedIndex + 2); unmergedData.unshift(columnHeaders.map(header => header[0] || header[1]));.
6. Create a new worksheet with the unmerged data with const newWorksheet = xlsx.utils.aoa_to_sheet(unmergedData).
7. Save the new workbook as a CSV with xlsx.writeFile({ SheetNames: ['Sheet1'], Sheets: { Sheet1: newWorksheet } }, 'your_filename.csv').
|
2bcbc6b537b64c8b02f435f84855e1eb
|
{
"intermediate": 0.7023624777793884,
"beginner": 0.17447501420974731,
"expert": 0.12316250801086426
}
|
9,681
|
How to write an abstract Vue component?
|
49e7c75c59670a6b1b3004f559d88f27
|
{
"intermediate": 0.41192615032196045,
"beginner": 0.19339372217655182,
"expert": 0.39468011260032654
}
|
9,682
|
const fs = require("fs");
const xlsx = require("xlsx");
const workbook = xlsx.readFile("./imports/AFR_Index_0115.xlsx");
let newWorksheet;
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const data = xlsx.utils.sheet_to_json(worksheet, {
header: 1,
});
function isMergedCell(cell, mergedCells) {
for (let i = 0; i < mergedCells.length; i++) {
if (
cell.r >= mergedCells[i].s.r &&
cell.r <= mergedCells[i].e.r &&
cell.c >= mergedCells[i].s.c &&
cell.c <= mergedCells[i].e.c
) {
return true;
}
}
return false;
}
const sheet = workbook.Sheets[workbook.SheetNames[0]];
const mergedCells = sheet["!merges"] ? sheet["!merges"] : [];
const mergedIndexes = {
2: [],
4: [],
};
for (const mergedCell of mergedCells) {
if (mergedCell.s.r === 1 && mergedCell.s.c >= 7 && mergedCell.e.c <= 9) {
// merged cell in second row starting at H column
mergedIndexes[2].push(mergedCell.s.c);
}
if (mergedCell.s.r === 3 && mergedCell.s.c >= 14 && mergedCell.e.c <= 16) {
// merged cell in fourth row starting at O column
mergedIndexes[4].push(mergedCell.s.c);
}
}
const unmergedData = [];
let currentRowIndex = 0;
for (let i = 0; i < data.length; i++) {
if (i === 1 || i === 3) {
// header rows
let currentColumnIndex = 0;
const columnHeaders = [];
for (let j = 0; j < data[i].length; j++) {
if (isMergedCell({ r: i, c: j }, mergedCells)) {
// skip merged cells
continue;
}
if (mergedIndexes[i] && mergedIndexes[i].includes(j)) {
// merged cell, get value from merged header cell
columnHeaders.push([data[i - 1][currentColumnIndex], data[i][j]]);
currentColumnIndex++;
} else {
// regular cell, use value as column header
columnHeaders.push([data[i][j], data[i][j]]);
currentColumnIndex++;
}
}
unmergedData.push(columnHeaders.map((header) => header[0]));
currentRowIndex = i + 1;
} else {
// data rows
unmergedData.push(data[i]);
}
}
// create a worksheet from the unmerged data
newWorksheet = xlsx.utils.aoa_to_sheet(unmergedData);
// Save the new workbook as a CSV
const newWorkbook = {
SheetNames: ["Sheet1"],
Sheets: {
Sheet1: newWorksheet,
},
};
const csvData = xlsx.utils.sheet_to_csv(newWorksheet);
fs.writeFileSync("./imports/AFR_Index_0115.csv", csvData, "utf8");
this code should only check for merged cells in H2:I2 and keep goin to the next cel until it is null then unmerged the cell and copy the values of the merged cell to both h2 and i2.
|
f1e7c909f7934ceb278c3311ccb7af0e
|
{
"intermediate": 0.3339875340461731,
"beginner": 0.38865771889686584,
"expert": 0.27735474705696106
}
|
9,683
|
Python questions and answers
|
15c157e14d5572d5ab1011d21b1bc4a1
|
{
"intermediate": 0.3200910687446594,
"beginner": 0.3207276165485382,
"expert": 0.35918131470680237
}
|
9,684
|
How to write an abstract Vue component?
|
531ccc8b175335207e6c620e9255d6f3
|
{
"intermediate": 0.41192615032196045,
"beginner": 0.19339372217655182,
"expert": 0.39468011260032654
}
|
9,685
|
traverse the dataframe by date, and get the value
|
c10542db7d408239ca1f6865c8e2c6a8
|
{
"intermediate": 0.43458062410354614,
"beginner": 0.22538022696971893,
"expert": 0.34003913402557373
}
|
9,686
|
Give steps to implement the complete project using Docker, Docker Compose (I have no idea how to do it)
Project Details
AI Toolchain (https://github.com/Samagra-Development/ai-tools) is a collection of tools for quickly building and deploying machine learning models for various use cases. Currently, the toolchain includes a text translation model, and more models may be added in the future. It abstracts the dirty details of how a model works similar to Huggingface and gives a clean API that you can orchestrate at aenter code here BFF level.
Features to be implemented
Abstract the layer of deployment for AI Tools. Anyone should be easily add a new model to the stack without thinking about deployments. We should be able to deploy AI Tools in such a way where each model (every model can be packaged as a container) should be independently scalable. As a user, I should be able to access APIs associated with any model.
Current AI Toolchain:
AI Toolchain
AI Toolchain is a collection of tools for quickly building and deploying machine learning models for various use cases. Currently, the toolchain includes a text translation model, and more models may be added in the future.
How to Run
To deploy all models, simply execute the deploy.sh script located in the root folder. This script calls the deployment files of each model. Note that the toolchain may switch to using Docker in the future for deployment.
To create a new model class, use the template_batch_model.py file as a starting point. Your new model class should implement the method mentioned in the template file.
To create a new request class, use the template_model_request.py file as a starting point. This class is used to map the incoming request to the data needed by the model.
To add your new model and request to the API, modify the repository dictionary in api.py.
Repository
The repository is structured as follows
Setup
To set up the AI Toolchain environment, follow these steps:
python3 -m venv venv
source venv/bin/activate
pip install poetry
poetry install
quart --app api --debug run
Poetry Fixes
poetry lock --no-update
Contributing
Contributions to AI Toolchain are welcome! To contribute, please follow these guidelines:
Fork the repository and create a new branch for your feature or bug fix.
Write tests for your changes.
Submit a pull request describing your changes and why they are needed.
Thank you for considering contributing to AI Toolchain!
|
baca2b21795e65c95b3b3492c2f62da6
|
{
"intermediate": 0.5223906636238098,
"beginner": 0.2926150858402252,
"expert": 0.18499425053596497
}
|
9,687
|
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
// 数字键盘连接的行和列
sbit row1 = P3^0;
sbit row2 = P3^1;
sbit row3 = P3^2;
sbit row4 = P3^3;
sbit col1 = P3^4;
sbit col2 = P3^5;
sbit col3 = P3^6;
sbit col4 = P3^7;
uchar code fre[] = {1, 3, 4, 8, 12, 19, 23, 26}; //定义音频
uchar code preMusic1[] = {1, 1, 2, 2, 3, 3, 1}; // 预置乐曲1
uchar code preMusic2[] = {4, 5, 4, 5, 6, 6, 5}; // 预置乐曲2
uchar code preMusic3[] = {7, 7, 8, 8, 7, 7, 6}; // 预置乐曲3
sbit spkr = P2^0; //扬声器连接P2.0口
sbit display = P2^1; //数码管连接P2.1口
//串口初始化
void InitUART(){
SCON = 0x50; //配置串口工作方式
TMOD = 0x20; //配置定时器工作在方式2
TH1 = 0xFD; //波特率设置19200的高位
TL1 = 0xFD; //波特率设置19200的低位
TR1 = 1; //启动定时器1
EA = 1; //开总中断
ES = 1; //开串口中断
}
void DelayUs2X(uchar t){
while (t--);
}
void DelayMs(uchar t){
while(t--){
DelayUs2X(245);
DelayUs2X(245);
}
}
//发音函数
void Sound(uchar num){
uchar i;
for(i=0; i<50; i++){
spkr = ~spkr;
DelayUs2X(fre[num]);
}
}
//发送数据给上位机
void sendData(uchar data){
SBUF = data;
while(!TI);
TI = 0;
}
//键盘扫描
uchar KeyScan(){
uchar keyNum = 0;
col1 = 0; col2 = 1; col3 = 1; col4 = 1;
if(!row1) keyNum = 1;
if(!row2) keyNum = 5;
if(!row3) keyNum = 9;
if(!row4) keyNum = 13;
col1 = 1; col2 = 0; col3 = 1; col4 = 1;
if(!row1) keyNum = 2;
if(!row2) keyNum = 6;
if(!row3) keyNum = 10;
if(!row4) keyNum = 14;
col1 = 1; col2 = 1; col3 = 0; col4 = 1;
if(!row1) keyNum = 3;
if(!row2) keyNum = 7;
if(!row3) keyNum = 11;
if(!row4) keyNum = 15;
col1 = 1; col2 = 1; col3 = 1; col4 = 0;
if(!row1) keyNum = 4;
if(!row2) keyNum = 8;
if(!row3) keyNum = 12;
if(!row4) keyNum = 16;
return keyNum;
}
void main(){
uchar key = 0;
InitUART(); //串口初始化
while(1){
key = KeyScan(); //检测按键
sendData(key); // 发送按键数据给上位机
if(key > 0){
Sound(key - 1); //发音
//数码管显示
//请在这里添加数码管显示代码
}
}
}
说明代码
|
43566bc97b6ed3c3c5302dd926a78eed
|
{
"intermediate": 0.2612164318561554,
"beginner": 0.5839260220527649,
"expert": 0.1548576056957245
}
|
9,688
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
binance_futures = ccxt.binance({ 'option': { 'defaultMarket': 'futures' },
'apiKey': '',
'secret':'' })
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '15m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '15m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '15m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR in order execution: The signal time is: 2023-06-02 10:28:32 :buy
Traceback (most recent call last):
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 559, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: for url: https://api.binance.com/sapi/v1/capital/config/getall?timestamp=1685690912495&recvWindow=10000&signature=cf1ea7fdb3dd3fa2475493d93b78a0c336d5ccefef89e7d067822b7f273ffb90
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 184, in <module>
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 103, in order_execution
account_balance = binance_futures.fetch_balance()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 2354, in fetch_balance
self.load_markets()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 1390, in load_markets
currencies = self.fetch_currencies()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 1705, in fetch_currencies
response = self.sapiGetCapitalConfigGetall(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2862, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 575, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7251, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3172, in throw_exactly_matched_exception
raise exact[string](message)
ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
|
478d3374c039f261bd871318787675fb
|
{
"intermediate": 0.3588620126247406,
"beginner": 0.4652230441570282,
"expert": 0.1759149581193924
}
|
9,689
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR: Traceback (most recent call last):
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 559, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: for url: https://api.binance.com/sapi/v1/capital/config/getall?timestamp=1685696291633&recvWindow=10000&signature=5bcc67e4a10add4beab413a06630e1e29fa2d8c05cbd0c48bd09f9d4b7583f73
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 192, in <module>
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 111, in order_execution
account_balance = binance_futures.fetch_balance()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 2354, in fetch_balance
self.load_markets()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 1390, in load_markets
currencies = self.fetch_currencies()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 1705, in fetch_currencies
response = self.sapiGetCapitalConfigGetall(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2862, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 575, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7251, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3172, in throw_exactly_matched_exception
raise exact[string](message)
ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
|
702ce6f5745460521ba5b8481fba328e
|
{
"intermediate": 0.32704490423202515,
"beginner": 0.5644837617874146,
"expert": 0.1084713339805603
}
|
9,690
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
balance = binance_futures.fetch_balance()
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But fapiPrivatePOSTOrder is undefined
|
45ae88d26149493edea131f3bea632eb
|
{
"intermediate": 0.29726916551589966,
"beginner": 0.5220016241073608,
"expert": 0.1807292401790619
}
|
9,691
|
give me a key code
|
9144f3037b9e43af6a976df42b5d2b67
|
{
"intermediate": 0.35964885354042053,
"beginner": 0.3259560763835907,
"expert": 0.3143950402736664
}
|
9,692
|
can you improve this code useEffect(() => {
const fetchData = async () => {
if (!isPreConfigured) {
const response: any = await httpClient.get("api/1/configure/data");
const configurationData = response.data;
setConfigurationData({
...configurationData,
[baseUrl]: configurationData.baseUrl,
});
setWhatsAppEnabled(configurationData.whatsAppConfig.enabled ?? false);
setwhatsAppInboundEnabled(
configurationData.whatsAppConfig.inboundEnabled ?? false
);
enableSms(configurationData.smsConfig.enabled ?? false);
}
};
fetchData();
}, []);
|
60720748d0db85c07a37b55a2b53d12e
|
{
"intermediate": 0.5921273231506348,
"beginner": 0.24840675294399261,
"expert": 0.1594659984111786
}
|
9,693
|
I have a function in python called foo that takes on argument.
I want to extend the function to handle a list of arguments such that for each of the element of the list it applies foo in the most efficient way
how to do that
|
0061dee46db87d9819a39c60767d4a3f
|
{
"intermediate": 0.3139052987098694,
"beginner": 0.36674219369888306,
"expert": 0.31935253739356995
}
|
9,694
|
В restasshured
Response response = given()
.config(config)
.body(transInfo.getRequestBody())
.header("Content-Type", "application/json")
.header("X-Auth-Token", "621869ab760a483c8557a1a446cca44a")
.header("X-User-Lang", "rus")
.baseUri(url)
.when()
.post(transInfo.getEndpoint());
Я могу получить тело ответа response.getBody().prettyPrint(). Как мне получить тело запроса?
|
f62fa4ffffb75ab3d2c9fdaa9d93174c
|
{
"intermediate": 0.282126247882843,
"beginner": 0.5501410961151123,
"expert": 0.16773267090320587
}
|
9,695
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
balance = binance_futures.fetch_balance()
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR: File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 559, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: for url: https://api.binance.com/sapi/v1/capital/config/getall?timestamp=1685697270728&recvWindow=10000&signature=8f96dc4988ce25b008021954952e11045883a5102398e6ac56923c86640756a2
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 49, in <module>
balance = binance_futures.fetch_balance()
|
42d33eed098d6a4ddf66485c73a518c4
|
{
"intermediate": 0.29726916551589966,
"beginner": 0.5220016241073608,
"expert": 0.1807292401790619
}
|
9,696
|
clean the code: "private void FallBlocks()
{
Debug.Log("falling blocks");
for (var x = 0; x < BoardWidth; x++)
{
for (var y = 0; y < BoardHeight -1; y++)
{
var block = _blocks[x, y];
if (block == null)
{
for (var y2 = y + 1; y2 < BoardHeight; y2++)
{
var block2 = _blocks[x, y2];
if (block2 != null)
{
block = block2;
block.GetComponent<Block>().Y = y2;
block2.transform.position = new Vector3(x * BlockSpacing, y2 * BlockSpacing, 0);
_blocks[x, y] = block;
_blocks[x, y2] = null;
block2 = null;
break;
}
}
}
}
}
}"
|
01ed32aeb43eb9b68973ea21f9d74066
|
{
"intermediate": 0.3115462064743042,
"beginner": 0.5236059427261353,
"expert": 0.16484777629375458
}
|
9,697
|
pod trunk push 出现以下错误如何处理:JSON::ParserError - 767: unexpected token at ''
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/json/common.rb:156:in `parse'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/json/common.rb:156:in `parse'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-trunk-1.6.0/lib/pod/command/trunk.rb:102:in `json'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-trunk-1.6.0/lib/pod/command/trunk/push.rb:92:in `push_to_trunk'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-trunk-1.6.0/lib/pod/command/trunk/push.rb:73:in `run'
/Library/Ruby/Gems/2.6.0/gems/claide-1.0.3/lib/claide/command.rb:334:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.12.1/lib/cocoapods/command.rb:52:in `run'
/Library/Ruby/Gems/2.6.0/gems/cocoapods-1.12.1/bin/pod:55:in `<top (required)>'
/usr/local/bin/pod:25:in `load'
/usr/local/bin/pod:25:in `<main>'
|
ceadb6f3118871de05555315f6abdf1b
|
{
"intermediate": 0.5814270973205566,
"beginner": 0.24961800873279572,
"expert": 0.16895484924316406
}
|
9,698
|
error: Merging is not possible because you have unmerged files.
hint: Fix them up in the work tree, and then use 'git add/rm <file>'
hint: as appropriate to mark resolution and make a commit.
fatal: Exiting because of an unresolved conflict.
|
f103c8c52c396fd52cf3872901b1b569
|
{
"intermediate": 0.39292675256729126,
"beginner": 0.28452610969543457,
"expert": 0.32254716753959656
}
|
9,699
|
give me a simple python code for a 1d minecraft
|
3eaaf027c0e2f56c53fd9f9b882982cf
|
{
"intermediate": 0.35443463921546936,
"beginner": 0.41730833053588867,
"expert": 0.2282569855451584
}
|
9,700
|
can you give me a simple python code for a calculator
|
5e88b45bccfcc419f855c8d356cf086c
|
{
"intermediate": 0.5190001726150513,
"beginner": 0.3226933181285858,
"expert": 0.15830649435520172
}
|
9,701
|
how to create Zuora Report - AR aging report – for collections
|
d9af35925dbfb3e561a0e57978fd77be
|
{
"intermediate": 0.34815874695777893,
"beginner": 0.20863233506679535,
"expert": 0.4432089626789093
}
|
9,702
|
const fs = require("fs");
const xlsx = require("xlsx");
let numChanged = 0;
let numUnchanged = 0;
// Read the old code XLSX file
const Codes = {};
const codesWorkbook = xlsx.readFile("./imports/itemCodes.xlsx");
const codesWorksheet = codesWorkbook.Sheets[codesWorkbook.SheetNames[0]];
const codesData = xlsx.utils.sheet_to_json(codesWorksheet, { header: 1 });
console.log("codesData: ", codesData);
for (let i = 0; i < codesData.length; i++) {
const [oldCode, newCode] = codesData[i];
// console.log("newCode: ", newCode);
Codes[oldCode] = newCode;
}
// Read the price XLSX file
const dataWorkbook = xlsx.readFile("./imports/AFR_Index_0115.xlsx");
const dataWorksheet = dataWorkbook.Sheets[dataWorkbook.SheetNames[0]];
const dataData = xlsx.utils.sheet_to_json(dataWorksheet, { header: 1 });
// console.log("dataData: ", dataData);
// Update the codes in the data XLSX file
const changedRows = [];
const unchangedRows = [];
console.log("Old Code: ", dataData[4][1]);
console.log("New Code: ", Codes[dataData[4][1]]);
for (let row = 4; row < dataData.length; row++) {
const oldCode = dataData[row][1];
const newCode = Codes[oldCode];
if (newCode) {
dataData[row][1] = newCode;
changedRows.push(row);
} else {
unchangedRows.push(row);
}
}
// Write the updated XLSX file
const updatedWorkbook = xlsx.utils.book_new();
const updatedWorksheet = xlsx.utils.aoa_to_sheet(dataData);
xlsx.utils.book_append_sheet(updatedWorkbook, updatedWorksheet);
xlsx.writeFile(updatedWorkbook, "./exports/updated_data.xlsx");
// Output changed rows and values
if (changedRows.length === 0) {
console.log("No codes were updated.");
} else {
console.log(`Updated codes in rows ${changedRows.join(", ")}.`);
console.log("New values:");
changedRows.forEach((row) => {
console.log(dataData[row].join(", "));
});
}
update this code so that it uses the xslx package and accepts xslx file as input. The functionality should be the same. The itemsCodes file has the items with old code and new code and it should use the old code to find entries inside AFR_Index file and when there is a match update the codes on this excel to the new codes
|
e0c7fa9b12dc9867be6c4430733a3dcd
|
{
"intermediate": 0.5258786678314209,
"beginner": 0.2684556245803833,
"expert": 0.205665722489357
}
|
9,703
|
Hi
|
5216de30d5cc9a9a0fdfb81917a43e84
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
9,704
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Get server time and time difference
server_time = binance_futures.fapiPrivatePostPositionRisk()['T']
time_difference = int(time.time() * 1000) - server_time
# Get current time adjusted for time difference
current_time = int(time.time() * 1000) - time_difference
# Use adjusted timestamp in subsequent requests
balances = binance_futures.fetch_balance({'timestamp': current_time})
print(balances)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR: Traceback (most recent call last):
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 559, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://fapi.binance.com/fapi/v1/positionMargin
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 50, in <module>
server_time = binance_futures.fapiPrivatePostPositionMargin()['T']
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2862, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 575, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7251, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3172, in throw_exactly_matched_exception
raise exact[string](message)
ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
|
c3efd732608df2d1c41d376e6831f6e9
|
{
"intermediate": 0.35827741026878357,
"beginner": 0.431441992521286,
"expert": 0.2102806121110916
}
|
9,705
|
Security code review for:
String toString()
A string representation of this object.
Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.
Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.
|
970cf3e23a8bc9135b43d1f043f2c8ff
|
{
"intermediate": 0.27607372403144836,
"beginner": 0.6372674107551575,
"expert": 0.08665887266397476
}
|
9,706
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Get server time and time difference
server_time = binance_futures.fapiPrivateGetPositionRisk({'timestamp':current_time})
time_difference = int(time.time() * 1000) - server_time
# Get current time adjusted for time difference
current_time = int(time.time() * 1000) - time_difference
# Use adjusted timestamp in subsequent requests
balances = binance_futures.fetch_balance({'timestamp': current_time})
print(balances)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(10)
But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 50, in <module>
server_time = binance_futures.fapiPrivateGetPositionRisk({'timestamp':current_time})
^^^^^^^^^^^^
NameError: name 'current_time' is not defined
|
d52522d12524b67908709b62e3862b35
|
{
"intermediate": 0.42830783128738403,
"beginner": 0.40644317865371704,
"expert": 0.16524899005889893
}
|
9,707
|
I want to implement the tendermint consensus algorithm in python. It will consist of 2 files, one named node.py contatining the code which will be run on every node, only constituted of three functions which are: whenStarting, whenReceiving and whenTimeout. The other file is simulator.py and will enable us to run the tendermint consensus algorithm from the nodes. Write the codes for both of these files.
|
ad1a3d13ddbe580e6eb2df5f166945d9
|
{
"intermediate": 0.17536023259162903,
"beginner": 0.13559271395206451,
"expert": 0.6890470385551453
}
|
9,708
|
please re-write this and make it better with typescript let testSenders;
if (
!availableSenders[0].options.length &&
!availableSenders[1].options.length
) {
testSenders = groupedOptions;
} else {
testSenders = availableSenders;
}
|
c02fbbc65585674a1b893e1fab711768
|
{
"intermediate": 0.25246888399124146,
"beginner": 0.6017888188362122,
"expert": 0.1457422822713852
}
|
9,709
|
why use docker?
|
ae8567f1770dc50fb050e837f91f8b4a
|
{
"intermediate": 0.4791063368320465,
"beginner": 0.19351793825626373,
"expert": 0.32737571001052856
}
|
9,710
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
Get server time and time difference
server_time = binance_futures.fapiPrivateGetPositionRisk()
time_difference = int(time.time() * 1000) - server_time - 500
Get current time adjusted for time difference
current_time = int(time.time() * 1000) - time_difference
Use adjusted timestamp in subsequent requests
balances = binance_futures.fetch_balance({'timestamp': current_time})
print(balances)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
perl
Copy code
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
python
Copy code
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(0.1)
But I getting ERROR: Traceback (most recent call last):
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 559, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://fapi.binance.com/fapi/v1/positionRisk?timestamp=1685706950143&recvWindow=10000&signature=e0578adf87ff44f10ec5669ad669b3445e9f8a5587cfeff4bdb0ed2698c3ac25
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 51, in
server_time = binance_futures.fapiPrivateGetPositionRisk()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2862, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 575, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7251, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3172, in throw_exactly_matched_exception
raise exactstring
ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
Please if it possible give me full right code
|
0e9063828eb0aa7365575d28c362dd11
|
{
"intermediate": 0.3392953872680664,
"beginner": 0.4359035789966583,
"expert": 0.22480103373527527
}
|
9,711
|
how run bat file without popup window
|
a9088625a66f50863b17248f3790e74a
|
{
"intermediate": 0.49055033922195435,
"beginner": 0.19067050516605377,
"expert": 0.3187791705131531
}
|
9,712
|
add disabled property to this button component export interface ButtonProps {
text: string;
onClick: () => void;
bgClassName?: string;
borderClassName?: string;
textColorClassName?: string;
}
export default function Button({
text,
onClick,
bgClassName = "bg-white",
borderClassName = "border-lochmara border border-solid",
textColorClassName = "text-lochmara",
}: ButtonProps) {
return (
<div
onClick={onClick}
className={`${bgClassName} ${textColorClassName} ${borderClassName} w-max cursor-pointer rounded-sm px-3 py-2.5 text-xs font-semibold uppercase`}
>
{text}
</div>
);
}
|
fe1400e930da916f6163e134164c501a
|
{
"intermediate": 0.3640463352203369,
"beginner": 0.3783315420150757,
"expert": 0.257622092962265
}
|
9,713
|
I have the following code:
import simpy
import random
import matplotlib.pyplot as plt
import numpy as np
# Parameters
num_edge_nodes = 2
num_cloud_nodes = 2
edge_buffer_size = 10
cloud_buffer_size = 15
# service times
cloud_server_time = 10
A_edge_service_time = 4
A_cloud_service_time = 2
B_edge_sevice_time = 2
B_cloud_service_partialprocess = 4
B_cloud_service_fullprocess = 5
propagation_delay = 1
arrival_rate = 0.8
edge_costs = [1, 2, 3]
cloud_costs = [2, 4, 6]
# Measurements
class Measure:
def __init__(self, N_arr_a, N_arr_b, drop, total_queuing_delay, edge_cost, cloud_cost):
self.N_arr_A = N_arr_a
self.N_arr_B = N_arr_b
self.drop = drop
self.total_queuing_delay = total_queuing_delay
self.edge_cost = edge_cost
self.cloud_cost = cloud_cost
measurements = Measure(0, 0, 0, 0, 0, 0)
def packet_arrivals(env, micro_data_center, cloud_data_center, data, edge_buffer, cloud_buffer, f_value):
packet_type_options = ['A', 'B']
packet_id = 1
while True:
packet_type = random.choices(packet_type_options, weights=(1 - f_value, f_value))[0]
if packet_type == 'A':
data.N_arr_A += 1
else:
data.N_arr_B += 1
arrival_time = env.now # Adding current time stamp for calculating delay
if len(micro_data_center.items) < edge_buffer:
if packet_type == 'A':
micro_data_center.put((packet_id, packet_type, A_edge_service_time, arrival_time))
elif packet_type == 'B':
micro_data_center.put((packet_id, packet_type, B_edge_sevice_time, arrival_time))
else:
if len(cloud_data_center.items) < cloud_buffer:
if packet_type == 'A':
cloud_data_center.put((packet_id, packet_type, A_cloud_service_time + propagation_delay))
elif packet_type == 'B':
cloud_data_center.put((packet_id, packet_type, B_cloud_service_fullprocess + propagation_delay))
else:
data.drop += 1
yield env.timeout(random.expovariate(arrival_rate))
packet_id += 1
def edge_node(env, micro_data_center, cloud_data_center, node_id, data, edge_cost):
while True:
packet_id, packet_type, packet_processing_time, arrival_time = yield micro_data_center.get()
queuing_delay = env.now - arrival_time
data.total_queuing_delay += queuing_delay
data.edge_cost += edge_cost * packet_processing_time
print(f"Edge Node {node_id} processed packet {packet_id} of type {packet_type} at time {env.now}")
yield env.timeout(packet_processing_time)
if packet_type == 'B':
yield cloud_data_center.put((packet_id, packet_type, B_cloud_service_partialprocess + propagation_delay))
def cloud_node(env, cloud_data_center, node_id, data, cloud_cost):
while True:
packet_id, packet_type, packet_processing_time = yield cloud_data_center.get()
yield env.timeout(packet_processing_time)
data.cloud_cost += cloud_cost * packet_processing_time
print(f"Cloud Node {node_id} processed {packet_type} packet {packet_id} (including propagation delay) at time {env.now}")
# Simulation setup
simtime = 100000
packet_loss_rates = []
f_list = np.linspace(0, 1, 20)
# Run the simulation
for f in f_list:
env = simpy.Environment()
micro_data_center = simpy.Store(env)
cloud_data_center = simpy.Store(env)
measurements = Measure(0, 0, 0, 0, 0, 0)
env.process(packet_arrivals(env, micro_data_center, cloud_data_center, measurements, edge_buffer_size, cloud_buffer_size, f))
for node_id in range(num_edge_nodes):
env.process(edge_node(env, micro_data_center, cloud_data_center, node_id + 1, measurements, edge_costs[node_id % len(edge_costs)]))
for node_id in range(num_cloud_nodes):
env.process(cloud_node(env, cloud_data_center, node_id + 1, measurements, cloud_costs[node_id % len(cloud_costs)]))
env.run(until=simtime)
packet_loss_rate = measurements.drop / (measurements.N_arr_A + measurements.N_arr_B)
packet_loss_rates.append(packet_loss_rate)
# Plot packet loss rate over time
plt.plot(f_list, packet_loss_rates)
plt.xlabel('Different f')
plt.ylabel('Packet Loss Rate')
plt.title('Packet Loss Rate over Different f')
plt.show()
tell me how to perform the following task using the above code:
Assume at least 4 Cloud servers. Furthermore, consider at least three different
types of Cloud servers, each featuring a different service speed and a specific
operational cost (that may depend, for example, on the service speed). Test
various combinations of server types and investigate the trade off between the
overall cost, the queuing delays and the packet drop probability
|
16f4a74b4c1a9a5c59a2d6a3cf47fe96
|
{
"intermediate": 0.2953169345855713,
"beginner": 0.48198243975639343,
"expert": 0.22270067036151886
}
|
9,714
|
Write a program code that, when entering the address of a token contract, will determine whether this token is hosted on https://pancakeswap.finance/ or not
|
df4c2051a72ff228c1979f13c5f361b8
|
{
"intermediate": 0.4752008020877838,
"beginner": 0.13555936515331268,
"expert": 0.3892398178577423
}
|
9,715
|
I need to use the "Consolas" font when using my code in powershell. Change my code to use the right font:
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $Outlook.GetNamespace("MAPI")
$PstPath = [System.IO.Path]::Combine([System.Environment]::GetFolderPath("MyDocuments"), "Файлы Outlook\unit_60@niiagp.org.pst")
# Find the specific account based on the email address
$Account = $Namespace.Accounts | Where-Object { $_.SmtpAddress -eq "unit_60@niiagp.org" }
if ($Account -ne $null) {
Write-Host "Importing contacts for account $($Account.DisplayName)"
# Open the PST file
$Folder = $Namespace.AddStoreEx($PstPath, 1)
if ($Folder -ne $null) {
# Get the Contacts folder for the account
$ContactsFolder = $Folder.GetDefaultFolder(10)
# Import contacts from the PST file and replace duplicates
$Folder.Items | ForEach-Object {
$Contact = $_
$ContactsFolder.Items.Add($Contact)
}
# Remove the temporary PST file from the Outlook profile
$Namespace.RemoveStore($Folder)
Write-Host "Contacts imported and temporary PST file removed for account $($Account.DisplayName)"
}
} else {
Write-Host "Account 'unit_60@niiagp.org' not found."
}
# Close Outlook
$Outlook.Quit()
|
3658b109469232cec386edac5aba1452
|
{
"intermediate": 0.41188502311706543,
"beginner": 0.37243539094924927,
"expert": 0.21567964553833008
}
|
9,716
|
const fs = require("fs");
const xlsx = require("xlsx");
let numChanged = 0;
let numUnchanged = 0;
// Read the old code XLSX file
const Codes = {};
const codesWorkbook = xlsx.readFile("./imports/itemCodes.xlsx");
const codesWorksheet = codesWorkbook.Sheets[codesWorkbook.SheetNames[2]];
const codesData = xlsx.utils.sheet_to_json(codesWorksheet, { header: 1 });
for (let i = 0; i < codesData.length; i++) {
const [oldCode, newCode] = codesData[i];
Codes[oldCode] = newCode;
}
// Read the price XLSX file
const dataWorkbook = xlsx.readFile("./imports/AFR_Index_0115.xlsx");
const dataWorksheet = dataWorkbook.Sheets[dataWorkbook.SheetNames[0]];
const dataData = xlsx.utils.sheet_to_json(dataWorksheet, { header: 1 });
// Update the codes in the data XLSX file
const changedRows = [];
const unchangedRows = [];
for (let row = 0; row < dataData.length; row++) {
const oldCode = dataData[row][1];
const newCode = Codes[oldCode];
if (newCode) {
dataData[row][1] = newCode;
changedRows.push(row);
} else {
unchangedRows.push(row);
}
}
// Write the updated XLSX file
const updatedWorkbook = xlsx.utils.book_new();
const updatedWorksheet = xlsx.utils.aoa_to_sheet(dataData);
xlsx.utils.book_append_sheet(updatedWorkbook, updatedWorksheet);
xlsx.writeFile(updatedWorkbook, "./exports/updated_data.xlsx");
// Output changed rows and values
if (changedRows.length === 0) {
console.log("No codes were updated.");
} else {
console.log(`Updated codes in rows ${changedRows.join(", ")}.`);
console.log("New values:");
changedRows.forEach((row) => {
console.log(dataData[row].join(", "));
});
}
how can i enforce datas that are on the updatedworkbook be the same as that of the original data. Like rounding of numbers on other columns should not be changed when updating codes. only update codes while leaving the rest of the data the same
|
36bdd7e991a55026664f3ade14ec3d14
|
{
"intermediate": 0.6716973781585693,
"beginner": 0.22379070520401,
"expert": 0.10451187938451767
}
|
9,717
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Get server time and time difference
server_time = binance_futures.public_get_time()
timestamp = int(time.time() * 1000) - (server_time - result['serverTime'])
print(result)
time_difference = int(time.time() * 1000) - server_time - 500
# Get current time adjusted for time difference
current_time = int(time.time() * 1000) - time_difference
# Use adjusted timestamp in subsequent requests
balances = binance_futures.fetch_balance({'timestamp': current_time})
print(balances)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(0.1)
But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 53, in <module>
timestamp = int(time.time() * 1000) - (server_time - result['serverTime'])
~~~~~~^^^^^^^^^^^^^^
KeyError: 'serverTime'
Give me right code please
|
1b8c83ad1f7f9a101c5e6a4ece5bfc24
|
{
"intermediate": 0.5269791483879089,
"beginner": 0.3119443953037262,
"expert": 0.16107645630836487
}
|
9,718
|
const { ethers } = require('ethers');
// Ethereum network configuration
const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/2d5bc62bb8d748cebfc64763e719cb4f');
const privateKey = 'ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
// Uniswap V3 contract configuration
const uniswapV3ContractAddress = '0x1F98431c8aD98523631AE4a59f267346ea31F984';
const { abi: uniswapV3ContractABI } = require('@uniswap/v3-core/build/UniswapV3.json');
// Token configuration
const tokenToSwapAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const tokenToReceiveAddress = '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984';
const tokenToSwapAmount = ethers.utils.parseUnits('<TOKEN_TO_SWAP_AMOUNT>', '<TOKEN_DECIMALS>');
// Connect to wallet
const wallet = new ethers.Wallet(privateKey, provider);
// Load the Uniswap V3 contract
const uniswapV3Contract = new ethers.Contract(uniswapV3ContractAddress, uniswapV3ContractABI, wallet);
async function executeTrade() {
// Approve Uniswap V3 to spend tokenToSwap
const tokenToSwapContract = new ethers.Contract(tokenToSwapAddress, tokenABI, wallet);
const approvalTx = await tokenToSwapContract.approve(uniswapV3ContractAddress, tokenToSwapAmount);
await approvalTx.wait();
// Prepare swap transaction
const swapTx = await uniswapV3Contract.swap(
tokenToSwapAddress,
tokenToReceiveAddress,
tokenToSwapAmount,
0, // slippage tolerance (0 means no tolerance)
ethers.constants.MaxUint256, // deadline (set to maximum value)
wallet.address, // recipient address
ethers.constants.AddressZero // fee recipient (use zero address for default)
);
console.log('Swap transaction hash:', swapTx.hash);
// Wait for transaction confirmation
await swapTx.wait();
console.log('Swap transaction confirmed!');
}
executeTrade().catch((error) => {
console.error('Error executing trade:', error);
});
Node.js v18.16.0
PS C:\Users\lidor\Desktop\Trade Bot> node index.js
C:\Users\lidor\Desktop\Trade Bot\index.js:4
const provider = new ethers.providers.JsonRpcProvider('https://mainnet.infura.io/v3/2d5bc62bb8d748cebfc64763e719cb4f');
^
TypeError: Cannot read properties of undefined (reading 'JsonRpcProvider')
at Object.<anonymous> (C:\Users\lidor\Desktop\Trade Bot\index.js:4:39)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.16.0
PS C:\Users\lidor\Desktop\Trade Bot>
|
79c75722da5b7a536e98eeddd2e569a1
|
{
"intermediate": 0.32878145575523376,
"beginner": 0.40562301874160767,
"expert": 0.26559561491012573
}
|
9,719
|
I have the following code:
import simpy
import random
import matplotlib.pyplot as plt
import numpy as np
# Parameters
num_edge_nodes = 2
num_cloud_nodes = 4
edge_buffer_size = 10
cloud_buffer_size = 15
# service times
cloud_server_time = 10
A_edge_service_time = 4
A_cloud_service_time = 2
B_edge_sevice_time = 2
B_cloud_service_partialprocess = 4
B_cloud_service_fullprocess = 5
propagation_delay = 1
cloud_server_times = [8, 10, 12] # Add a list of service times for each cloud server type
edge_server_times = [A_edge_service_time, B_edge_sevice_time] # Add edge service times for easy indexing
arrival_rate = 0.8
edge_costs = [1, 2, 3]
cloud_costs = [2, 4, 6]
# Modify cloud_costs and edge_costs to support more configurations
cloud_costs = [cloud_cost * server_time for cloud_cost, server_time in zip(cloud_costs, cloud_server_times)]
edge_costs = [edge_cost * server_time for edge_cost, server_time in zip(edge_costs, edge_server_times)]
# Measurements
class Measure:
def __init__(self, N_arr_a, N_arr_b, drop, total_queuing_delay, edge_cost, cloud_cost):
self.N_arr_A = N_arr_a
self.N_arr_B = N_arr_b
self.drop = drop
self.total_queuing_delay = total_queuing_delay
self.edge_cost = edge_cost
self.cloud_cost = cloud_cost
measurements = Measure(0, 0, 0, 0, 0, 0)
def packet_arrivals(env, micro_data_center, cloud_data_center, data, edge_buffer, cloud_buffer, f_value):
packet_type_options = ['A', 'B']
packet_id = 1
while True:
packet_type = random.choices(packet_type_options, weights=(1 - f_value, f_value))[0]
if packet_type == 'A':
data.N_arr_A += 1
else:
data.N_arr_B += 1
arrival_time = env.now # Adding current time stamp for calculating delay
if len(micro_data_center.items) < edge_buffer:
if packet_type == 'A':
micro_data_center.put((packet_id, packet_type, A_edge_service_time, arrival_time))
elif packet_type == 'B':
micro_data_center.put((packet_id, packet_type, B_edge_sevice_time, arrival_time))
else:
if len(cloud_data_center.items) < cloud_buffer:
if packet_type == 'A':
cloud_data_center.put((packet_id, packet_type, A_cloud_service_time + propagation_delay))
elif packet_type == 'B':
cloud_data_center.put((packet_id, packet_type, B_cloud_service_fullprocess + propagation_delay))
else:
data.drop += 1
yield env.timeout(random.expovariate(arrival_rate))
packet_id += 1
def edge_node(env, micro_data_center, cloud_data_center, node_id, data, edge_cost, service_time):
while True:
packet_id, packet_type, packet_processing_time, arrival_time = yield micro_data_center.get()
queuing_delay = env.now - arrival_time
data.total_queuing_delay += queuing_delay
data.edge_cost += edge_cost * packet_processing_time
print(f"Edge Node {node_id} processed packet {packet_id} of type {packet_type} at time {env.now}")
yield env.timeout(service_time) # Use parametrized service time for delay
if packet_type == 'B':
yield cloud_data_center.put((packet_id, packet_type, B_cloud_service_partialprocess + propagation_delay))
def cloud_node(env, cloud_data_center, node_id, data, cloud_cost, service_time):
while True:
packet_id, packet_type, packet_processing_time = yield cloud_data_center.get()
yield env.timeout(service_time) # Use parametrized service time for delay
data.cloud_cost += cloud_cost * packet_processing_time
print(f"Cloud Node {node_id} processed {packet_type} packet {packet_id} (including propagation delay) at time {env.now}")
# Simulation setup
simtime = 10000
packet_loss_rates = []
f_list = np.linspace(0, 1, 5)
# In the simulation loop, run the simulation by varying the server types
combinations = []
for f in f_list:
for i in range(len(edge_costs)):
for j in range(len(cloud_costs)):
# Create a new environment for each combination
env = simpy.Environment()
# Initialize queue and measurements
micro_data_center = simpy.Store(env)
cloud_data_center = simpy.Store(env)
measurements = Measure(0, 0, 0, 0, 0, 0)
# Configure the packet arrival function
env.process(packet_arrivals(
env, micro_data_center, cloud_data_center, measurements, edge_buffer_size, cloud_buffer_size, f))
# Configure edge nodes with specific server types
for node_id in range(num_edge_nodes):
env.process(edge_node(env, micro_data_center, cloud_data_center, node_id + 1,
measurements, edge_costs[i], edge_server_times[node_id % len(edge_server_times)]))
# Configure cloud nodes with specific server types
for node_id in range(num_cloud_nodes):
env.process(cloud_node(env, cloud_data_center, node_id + 1,
measurements, cloud_costs[j], cloud_server_times[node_id % len(cloud_server_times)]))
# Run the simulation and gather results
env.run(until=simtime)
packet_loss_rate = measurements.drop / (measurements.N_arr_A + measurements.N_arr_B)
# Append the current combination’s cost and packet loss rate to the results
combinations.append({
"edge_cost": edge_costs[i],
"cloud_cost": cloud_costs[j],
"f": f,
"total_cost": measurements.edge_cost + measurements.cloud_cost,
"queuing_delay": measurements.total_queuing_delay,
"packet_loss_rate": packet_loss_rate
})
print(combinations) # Print the list of combinations and their corresponding costs, queuing delays, and packet drop rates
Tell me how I use these info generated by the code to investigate the trade off between the overall cost, the queuing delays and the packet drop probability. Provide me the code for some plottings and ... to visualize this tradeoff
|
9afa6bca6f0455286f3fcd0ef5376c10
|
{
"intermediate": 0.36929160356521606,
"beginner": 0.4051605463027954,
"expert": 0.2255478948354721
}
|
9,720
|
Change that R code:
Data<-read.csv("C:/Users/Użytkownik/Desktop/player22.csv")
RW_idx <- which(grepl("RW", Data$Positions))
ST_idx <- which(grepl("ST", Data$Positions))
GK_idx <- which(grepl("GK", Data$Positions))
CM_idx <- which(grepl("CM", Data$Positions))
LW_idx <- which(grepl("LW", Data$Positions))
CDM_idx <- which(grepl("CDM", Data$Positions))
LM_idx <- which(grepl("LM", Data$Positions))
CF_idx <- which(grepl("CF", Data$Positions))
CB_idx <- which(grepl("CB", Data$Positions))
CAM_idx <- which(grepl("CAM", Data$Positions))
LB_idx <- which(grepl("LB", Data$Positions))
RB_idx <- which(grepl("RB", Data$Positions))
RM_idx <- which(grepl("RM", Data$Positions))
LWB_idx <- which(grepl("LWB", Data$Positions))
RWB_idx <- which(grepl("RWB", Data$Positions))
#############
pop_init <- list()
# Create a list of vectors to loop through
position_vectors <- list(RW_idx, ST_idx, GK_idx, CM_idx, LW_idx,
CDM_idx, LM_idx, CF_idx, CB_idx, CAM_idx,
LB_idx, RB_idx, RM_idx, LWB_idx, RWB_idx)
position_vectors_list<-position_vectors
tournament_selection <- function(parents, t_size) {
# Select t_size random parents
random_parents_idx <- sample(nrow(parents), t_size, replace = FALSE)
random_parents <- parents[random_parents_idx, ]
# Evaluate the target function for each selected parent
random_parents_fitness <- apply(random_parents, 1, target)
# Select the best parent based on the target function value
best_parent_idx <- which.max(random_parents_fitness)
return(random_parents[best_parent_idx, ])
}
# Crossover function
crossover <- function(parent1, parent2) {
# Choose a random crossover point
crossover_point <- sample(2:(ncol(parent1) - 1), 1)
# Swap the position vectors after the crossover point
offspring1 <- c(parent1[1:crossover_point], parent2[(crossover_point + 1):ncol(parent1)])
offspring2 <- c(parent2[1:crossover_point], parent1[(crossover_point + 1):ncol(parent2)])
return(rbind(offspring1, offspring2))
}
mutate <- function(individual, position_vectors_list, probability = 0.09) {
for (pos_idx in 1:length(position_vectors_list)) {
if (runif(1) <= probability) {
repeat {
random_idx <- sample(position_vectors_list[[pos_idx]], 1)
if (!random_idx %in% individual) {
individual[pos_idx] <- random_idx
break
}
}
}
}
return(individual)
}
preserve_elites <- function(population, num_elites) {
population_fitness <- apply(population, 1, target)
elite_indices <- order(-population_fitness)[1:num_elites]
elites <- population[elite_indices, ]
return(as.matrix(elites))
}
initialize_individual <- function(position_vectors_list) {
individual <- sapply(position_vectors_list, function(pos) sample(pos, 1))
return(individual)
}
# Create initial population
n_rows <- 100
initial_population <- matrix(NA, n_rows, length(position_vectors))
for (i in 1:n_rows) {
individual <- initialize_individual(position_vectors)
initial_population[i, ] <- individual
}
# Define the target function
target <- function(parent_indices) {
position_ratings <- c("RWRating", "STRating", "GKRating", "CMRating",
"LWRating", "CDMRating", "LMRating", "CFRating",
"CBRating", "CAMRating", "LBRating", "RBRating",
"RMRating", "LWBRating", "RWBRating")
parent_data <- Data[parent_indices, ]
ratings <- parent_data[position_ratings]
ratings_log <- log(ratings)
potential_minus_age <- parent_data$Potential - parent_data$Age
log_value_eur_minus_wage_eur <- log(parent_data$ValueEUR) - log(parent_data$WageEUR)
int_reputation <- parent_data$IntReputation
# Apply constraints
constraint_penalty <- 0
if (sum(parent_data$ValueEUR) > 250000000) {
constraint_penalty <- constraint_penalty + 200
}
if (sum(parent_data$WageEUR) > 250000) {
constraint_penalty <- constraint_penalty + 200
}
if (any(ratings_log < 1.2)) {
constraint_penalty <- constraint_penalty + 200
}
target_value <- -(rowSums(ratings_log) + potential_minus_age - log_value_eur_minus_wage_eur + int_reputation) + constraint_penalty
return(target_value)
}
# Create a matrix to store the population
population <- as.matrix(population)
# Genetic algorithm parameters
population_size <- 100
num_generations <- 1000
tournament_size <- 5
num_elites <- 2
for (gen in 1:num_generations) {
# Preserve elites
elites <- preserve_elites(population, num_elites)
# Create an empty matrix to store offspring
offspring_population <- matrix(NA, population_size - num_elites, ncol(population))
# Perform crossover and mutation to generate offspring
for (i in seq(1, population_size - num_elites, 2)) {
# Select two parents using tournament selection
parent1 <- tournament_selection(population, tournament_size)
parent2 <- tournament_selection(population, tournament_size)
# Perform crossover to generate offspring
offspring <- crossover(parent1, parent2)
# Mutate offspring
offspring[1, ] <- mutate(offspring[1, ], position_vectors_list)
offspring[2, ] <- mutate(offspring[2, ], position_vectors_list)
# Add the generated offspring to the offspring population matrix
offspring_population[i, ] <- as.numeric(offspring[1, ])
offspring_population[(i + 1), ] <- as.numeric(offspring[2, ])
}
# Replace the old population with the offspring and elites
population <- rbind(elites, offspring_population)
# Calculate the fitness for the current population
population_fitness <- apply(population, 1, target)
# Get the best solution in the current population
best_solution <- population[which.max(population_fitness), ]
best_fitness <- max(population_fitness)
}
# Remove temporary variables
rm(offspring_population, population_fitness)
To Julia.
|
af609141cb3f3b86f1400c66d10d5acb
|
{
"intermediate": 0.294542133808136,
"beginner": 0.4073975682258606,
"expert": 0.2980602979660034
}
|
9,721
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Get server time and time difference
server_time = binance_futures.public_get_time()
print(f'Timestamp:{server_time}')
try:
timestamp = int(time.time() * 1000) - (server_time - result['serverTime'])
print(f'Timestamp: {timestamp}')
except KeyError:
print(f"Error accessing 'serverTime' in API response. Response: {result}")
timestamp = int(time.time() * 1000)
time_difference = int(time.time() * 1000) - server_time - 500
# Get current time adjusted for time difference
current_time = int(time.time() * 1000) - time_difference
# Use adjusted timestamp in subsequent requests
balances = binance_futures.fetch_balance({'timestamp': current_time})
print(balances)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(0.1)
But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 62, in <module>
time_difference = int(time.time() * 1000) - server_time - 500
~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
TypeError: unsupported operand type(s) for -: 'int' and 'dict'
|
5076d59e89e18590f153373124add76e
|
{
"intermediate": 0.5377260446548462,
"beginner": 0.32153159379959106,
"expert": 0.14074234664440155
}
|
9,722
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Get server time and time difference
server_time = binance_futures.public_get_time()
server_timestamp = server_time['serverTime']
print(f'Timestamp:{server_time}')
server_time = binance_futures.public_get_time()
server_timestamp = int(server_time['serverTime'] - 1000)
print(f'Timestamp:{server_timestamp}')
try:
timestamp = int(time.time() * 1000) - (server_timestamp * 1000 - result['serverTime'])
print(f'Timestamp: {timestamp}')
except KeyError:
print(f"Error accessing 'serverTime' in API response. Response: {result}")
timestamp = int(time.time() * 1000)
time_difference = int(time.time() * 1000) - server_timestamp * 1000 - 500
# Get current time adjusted for time difference
current_time = int(time.time() * 1000) - time_difference
# Use adjusted timestamp in subsequent requests
balances = binance_futures.fetch_balance({'timestamp': current_time})
print(balances)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(0.1)
But I getting ERROR: 06/02/2023 16:29:44
Timestamp:{'serverTime': '1685712581314'}
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 57, in <module>
server_timestamp = int(server_time['serverTime'] - 1000)
~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~
TypeError: unsupported operand type(s) for -: 'str' and 'int'
|
229fa5e3e2173771bc4ad52848043c44
|
{
"intermediate": 0.5324435830116272,
"beginner": 0.2085716724395752,
"expert": 0.25898483395576477
}
|
9,723
|
const dataData = xlsx.utils.sheet_to_json(dataWorksheet, { header: 1 });
how can inforce the decimals being read by this code are rounded to two decimal places, whole numbers should not be changed
|
8b79ddee5caf4f1874a8ef435689b4bd
|
{
"intermediate": 0.5548017024993896,
"beginner": 0.22364971041679382,
"expert": 0.22154851257801056
}
|
9,724
|
const dataWorkbook = xlsx.readFile("./imports/AFR_Index_0115.xlsx");
const dataWorksheet = dataWorkbook.Sheets[dataWorkbook.SheetNames[0]];
const dataData = xlsx.utils.sheet_to_json(dataWorksheet, { header: 1 });
how can i enforce the dataData rounds columns with decimal value to be rounded to two place
|
e49e4929adc7b98294b8628077f808cb
|
{
"intermediate": 0.7673749923706055,
"beginner": 0.11420702189207077,
"expert": 0.11841799318790436
}
|
9,725
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
t = int(time.time()*1000 - 1000)
url = f"https://api.binance.com/api/v1/time?timestamp={t}"
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({
'apiKey': '',
'secret': '',
'enableRateLimit': True, # enable rate limitation
'options': {
'defaultType': 'future',
'adjustForTimeDifference': True
}
})
# Get server time and time difference
server_time = binance_futures.public_get_time()
server_timestamp = server_time['serverTime']
print(f'Timestamp:{server_time}')
server_time = binance_futures.public_get_time()
server_timestamp = int(server_time['serverTime']) - 1000
print(f'Timestamp:{server_timestamp}')
try:
timestamp = int(time.time() * 1000) - (server_timestamp * 1000 - result['serverTime']) - 500
print(f'Timestamp: {timestamp}')
except KeyError:
print(f"Error accessing 'serverTime' in API response. Response: {result}")
timestamp = int(time.time() * 1000)
time_difference = int(time.time() * 1000) - server_timestamp * 1000 - 500
# Get current time adjusted for time difference
current_time = int(time.time() * 1000) - time_difference
# Use adjusted timestamp in subsequent requests
balances = binance_futures.fetch_balance({'timestamp': timestamp})
print(balances)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
# Get current positions
positions = binance_futures.fapiPrivateGetPositionRisk()
for p in positions:
if p['symbol'] == symbol and p['positionSide'] == 'LONG':
long_position = p
elif p['symbol'] == symbol and p['positionSide'] == 'SHORT':
short_position = p
# Close positions
if long_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True)
time.sleep(1)
if short_position is not None:
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True)
time.sleep(1)
print("Both positions closed.")
# Place new order
quantity = max_trade_quantity
if signal == 'buy':
position_side = 'BOTH'
opposite_position = short_position
elif signal == 'sell':
position_side = 'BOTH'
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
if opposite_position is not None:
quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
price = None
if signal == 'buy':
order_type = 'TAKE_PROFIT_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
elif signal == 'sell':
order_type = 'STOP_MARKET'
price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price']
stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
order = binance_futures.fapiPrivatePostOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage))
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
if signal == 'buy':
take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100)
elif signal == 'sell':
take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100)
# Set stop loss and take profit orders
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
time.sleep(1)
binance_futures.fapiPrivatePostOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(0.1)
But I getting ERROR: Timestamp:{'serverTime': '1685712948002'}
Timestamp:1685712947278
Error accessing 'serverTime' in API response. Response: {'code': -1101, 'msg': "Too many parameters; expected '0' and received '1'."}
Traceback (most recent call last):
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 559, in fetch
response.raise_for_status()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: for url: https://api.binance.com/sapi/v1/capital/config/getall?timestamp=1685712951693&recvWindow=10000&signature=cebb17e42b7ea26c8951841b1e7bafaf13674902915df3d57c2c3844f757fd34
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 72, in <module>
balances = binance_futures.fetch_balance({'timestamp': timestamp})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 2354, in fetch_balance
self.load_markets()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 1390, in load_markets
currencies = self.fetch_currencies()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 1705, in fetch_currencies
response = self.sapiGetCapitalConfigGetall(params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2862, in fetch2
return self.fetch(request['url'], request['method'], request['headers'], request['body'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 575, in fetch
skip_further_error_handling = self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7251, in handle_errors
self.throw_exactly_matched_exception(self.exceptions['exact'], error, feedback)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3172, in throw_exactly_matched_exception
raise exact[string](message)
ccxt.base.errors.InvalidNonce: binance {"code":-1021,"msg":"Timestamp for this request was 1000ms ahead of the server's time."}
|
97f14aade55663c7dbcdf7dd928c65d5
|
{
"intermediate": 0.5617773532867432,
"beginner": 0.18927448987960815,
"expert": 0.2489481121301651
}
|
9,726
|
write a python program to check whether a number prime or not.
|
1da6bbf9183e1697b0daf3e2953a3ac9
|
{
"intermediate": 0.41214457154273987,
"beginner": 0.18160131573677063,
"expert": 0.4062541425228119
}
|
9,727
|
Wenn ich mit dem Code_Scan Package in Flutter einen QR_Code scanne, dann wird in Flutter in der camera_controller.dart eine Exception geworfen.
code: "Disposed CameraController"
"stopImageStream() was called on a disposed CameraController."
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'$functionName() was called on a disposed CameraController.',
);
}
import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/patient_app_localizations.dart';
import 'package:patient_app/models/scan_result.dart';
import 'package:patient_app/theme/patient_app_colors.dart';
import 'package:patient_app/theme/patient_app_theme.dart' as theme;
import 'package:patient_app/widgets/patient_app_back_button.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
typedef QrScanResultCallback = Future<bool> Function(ScanResult);
// see https://pub.dev/packages/qr_code_scanner/example
class QrScanner extends StatefulWidget {
const QrScanner(
{Key? key, required this.callback, required this.backButtonCallback})
: super(key: key);
final QrScanResultCallback callback;
final BackButtonCallback backButtonCallback;
@override
State<QrScanner> createState() => _QrScannerState();
}
class _QrScannerState extends State<QrScanner> {
QRViewController? controller;
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
late AppLocalizations _l10n;
@override
void didChangeDependencies() {
_l10n = AppLocalizations.of(context)!;
super.didChangeDependencies();
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
// In order to get hot reload to work we need to pause the camera if the platform
// is android, or resume the camera if the platform is iOS.
@override
void reassemble() {
super.reassemble();
if (defaultTargetPlatform == TargetPlatform.android) {
controller!.pauseCamera();
}
controller!.resumeCamera();
}
@override
Widget build(BuildContext context) {
double cutOutSize = _calculateCutOutSize(context);
return Container(
color: AppColors.opascaBlue,
child: Stack(
children: [
_buildQrView(cutOutSize),
_flashlightButton(cutOutSize),
],
),
);
}
double _calculateCutOutSize(BuildContext context) {
var minimumAvailableSpace = min(
MediaQuery.of(context).size.width, MediaQuery.of(context).size.height);
return minimumAvailableSpace - (2 * theme.mediumPadding);
}
Widget _flashlightButton(double cutOutSize) {
return Positioned.fill(
top: (MediaQuery.of(context).size.height * 0.5) + (cutOutSize * 0.5),
child: Align(
alignment: Alignment.topCenter,
child: FloatingActionButton(
onPressed: () async {
try {
await controller?.toggleFlash();
} catch (e) {
_showSnackBar(const ValueKey('flashlight'),
'Flashlight toggle not possible');
}
setState(() {});
},
elevation: 0.0,
backgroundColor: AppColors.transparent,
child: FutureBuilder(
future: controller?.getFlashStatus(),
builder: (context, snapshot) {
if (snapshot.data == true) {
return const Icon(Icons.flash_off);
}
return const Icon(Icons.flash_on);
},
),
),
),
);
}
Widget _buildQrView(double cutOutSize) {
// For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
var cutOutBottomOffset = theme.mediumSpacing;
return QRView(
key: qrKey,
onQRViewCreated: _onQRViewCreated,
overlay: QrScannerOverlayShape(
borderRadius: theme.radiusValue,
borderLength: theme.scannerOverlayBorderLength,
borderWidth: theme.scannerOverlayBorderWidth,
cutOutSize: cutOutSize,
cutOutBottomOffset: cutOutBottomOffset,
overlayColor: AppColors.blackOpacity60,
),
onPermissionSet: (_, permissionGranted) =>
_onPermissionSet(permissionGranted),
);
}
void _onQRViewCreated(QRViewController controller) {
this.controller?.dispose();
setState(() {
this.controller = controller;
});
controller.scannedDataStream.listen((scanData) async {
if (scanData.code != null) {
this.controller?.pauseCamera();
bool resultHandled = await widget.callback(ScanResult(scanData.code!));
if (!resultHandled) {
await _showQrCodeReadErrorDialog();
this.controller?.resumeCamera();
}
}
});
if (Platform.isAndroid) {
// https://github.com/juliuscanute/qr_code_scanner/issues/560
// fix for android camera, black screen
controller.pauseCamera();
controller.resumeCamera();
}
}
Future<dynamic> _showQrCodeReadErrorDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(_l10n.accountLinking_QrCodeScannerDialogTitle),
content: Text(_l10n.accountLinking_QrCodeScannerDialogDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
void _onPermissionSet(bool permissionGranted) async {
if (!permissionGranted) {
await _showPermissionNotGrantedDialog();
controller?.pauseCamera();
widget.backButtonCallback();
}
}
Future<dynamic> _showPermissionNotGrantedDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(
_l10n.accountLinking_QrCodeScannerMissingCameraPermissionTitle),
content: Text(_l10n
.accountLinking_QrCodeScannerMissingCameraPermissionDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
void _showSnackBar(Key key, String text) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
key: key,
content: Text(text),
),
);
}
}
import 'dart:async';
import 'package:code_scan/code_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/patient_app_localizations.dart';
import 'package:patient_app/models/scan_result.dart';
import 'package:patient_app/theme/patient_app_colors.dart';
import 'package:patient_app/widgets/patient_app_back_button.dart';
typedef QrScanResultCallback = Future<bool> Function(ScanResult);
// see https://pub.dev/packages/code_scan/example
class QrScanner extends StatefulWidget {
const QrScanner(
{Key? key, required this.callback, required this.backButtonCallback})
: super(key: key);
final QrScanResultCallback callback;
final BackButtonCallback backButtonCallback;
@override
State<QrScanner> createState() => _QrScannerState();
}
class _QrScannerState extends State<QrScanner> with WidgetsBindingObserver {
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
late AppLocalizations _l10n;
// prevent over processing
bool processingInProgress = false;
@override
void didChangeDependencies() {
_l10n = AppLocalizations.of(context)!;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Container(
color: AppColors.opascaBlue,
child: _buildQrView(),
);
}
Widget _buildQrView() {
return CodeScanner(
key: qrKey,
formats: const [BarcodeFormat.qrCode],
scanInterval: const Duration(milliseconds: 500),
onScan: (code, _, listener) {
if (code != null) {
if (processingInProgress == false) {
processingInProgress = true;
widget.callback(ScanResult(code)).then((isValidCode) {
if (mounted && !isValidCode) {
processingInProgress = false;
}
});
}
}
},
onAccessDenied: (_, controller) {
_showPermissionNotGrantedDialog()
.then((_) => widget.backButtonCallback());
return false;
},
onError: (_, __) {
_showQrCodeReadErrorDialog();
},
overlay: Container(),
);
}
Future<dynamic> _showQrCodeReadErrorDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(_l10n.accountLinking_QrCodeScannerDialogTitle),
content: Text(_l10n.accountLinking_QrCodeScannerDialogDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
Future<dynamic> _showPermissionNotGrantedDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(
_l10n.accountLinking_QrCodeScannerMissingCameraPermissionTitle),
content: Text(_l10n
.accountLinking_QrCodeScannerMissingCameraPermissionDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
}
|
73c1ac29809adbd3cf30392d5d567538
|
{
"intermediate": 0.30643296241760254,
"beginner": 0.5088894963264465,
"expert": 0.18467757105827332
}
|
9,728
|
in my kotlin app, i want to add a listener to a button which allows the user to open the image library on the device and pick a photo. the photo’s location in the internal storage is then returned, and the app can save it in some location. i dont want to use deprecated functions
|
c4994abf4eb2bfa42c82466b8936b1e1
|
{
"intermediate": 0.5866461396217346,
"beginner": 0.18355333805084229,
"expert": 0.22980044782161713
}
|
9,729
|
const ethers = require('ethers');
// Ethereum network configuration
// const provider = new ethers.getDefaultProvider('https://mainnet.infura.io/v3/2d5bc62bb8d748cebfc64763e719cb4f');
const provider = new ethers.JsonRpcProvider('http://127.0.0.1:8545/');
const privateKey = 'ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
// Uniswap V3 contract configuration
const uniswapV3ContractAddress = '0x1F98431c8aD98523631AE4a59f267346ea31F984';
const uniswapV3ContractABI = require('./abi.json');
// Token configuration
const tokenToSwapAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const tokenToReceiveAddress = '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984';
const tokenToSwapAmount = ethers.parseUnits('0.001', 'ether');
// Connect to wallet
const wallet = new ethers.Wallet(privateKey, provider);
// Load the Uniswap V3 contract
const uniswapV3Contract = new ethers.Contract(uniswapV3ContractAddress, uniswapV3ContractABI, wallet);
async function executeTrade() {
// Approve Uniswap V3 to spend tokenToSwap
const tokenToSwapContract = new ethers.Contract(tokenToSwapAddress, uniswapV3ContractABI, wallet);
const approvalTx = await tokenToSwapContract.approve(uniswapV3ContractAddress, tokenToSwapAmount);
await approvalTx.wait();
// Prepare swap transaction
const swapTx = await uniswapV3Contract.swap(
tokenToSwapAddress,
tokenToReceiveAddress,
tokenToSwapAmount,
0, // slippage tolerance (0 means no tolerance)
ethers.MaxUint256, // deadline (set to maximum value)
wallet.address, // recipient address
0 // fee recipient (use zero address for default)
);
console.log('Swap transaction hash:', swapTx.hash);
// Wait for transaction confirmation
await swapTx.wait();
console.log('Swap transaction confirmed!');
}
executeTrade().catch((error) => {
console.error('Error executing trade:', error);
});
PS C:\Users\lidor\Desktop\Trade Bot> node index.js
Error executing trade: Error: insufficient funds for intrinsic transaction cost (transaction="0x02f8b2018201d8843b9aca00850f200002a882b3e494c02aaa39b223fe8d0a0e5c4f27ead9083c756cc280b844095ea7b30000000000000000000000001f98431c8ad98523631ae4a59f267346ea31f98400000000000000000000000000000000000000000000000000038d7ea4c68000c001a0e12053e6d48e6d2b6f58db2a8b35bb3dc609ca0f4dfff74a4b41c8f53690d5dca07df5f64242fdf382aa0aa13e2571a10a13a519bf51e358903352cd6706157486", info={ "error": { "code": -32000, "message": "insufficient funds for gas * price + value" } }, code=INSUFFICIENT_FUNDS, version=6.4.1)
at makeError (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\utils\errors.js:125:21)
at JsonRpcProvider.getRpcError (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\providers\provider-jsonrpc.js:616:49)
at C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\providers\provider-jsonrpc.js:257:52
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'INSUFFICIENT_FUNDS',
98431c8ad98523631ae4a59f267346ea31f98400000000000000000000000000000000000000000000000000038d7ea4c68000c001a0e12053e6d48e6d2b6f58db2a8b35bb3dc609ca0f4dfff74a4b41c8f53690d5dca07df5f64242fdf382aa0aa13e2571a10a13a519bf51e358903352cd6706157486',
info: {
error: {
code: -32000,
message: 'insufficient funds for gas * price + value'
}
}
}
PS C:\Users\lidor\Desktop\Trade Bot> node index.js
Error executing trade: TypeError: no matching function (argument="key", value="swap", code=INVALID_ARGUMENT, version=6.4.1)
at makeError (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\utils\errors.js:118:21)
at assert (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\utils\errors.js:142:15)
at assertArgument (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\utils\errors.js:154:5)
at Interface.getFunctionName (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\abi\interface.js:433:39)
at buildWrappedMethod (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\contract\contract.js:240:34)
at Contract.getFunction (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\contract\contract.js:688:22)
at Object.get (C:\Users\lidor\Desktop\Trade Bot\node_modules\ethers\lib.commonjs\contract\contract.js:598:39)
at executeTrade (C:\Users\lidor\Desktop\Trade Bot\index.js:31:42)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'INVALID_ARGUMENT',
argument: 'key',
value: 'swap'
}
|
7314be861e55334aa2ed2688f849d762
|
{
"intermediate": 0.3852372467517853,
"beginner": 0.35139647126197815,
"expert": 0.2633662521839142
}
|
9,730
|
Change that R code:
Data<-read.csv("C:/Users/Użytkownik/Desktop/player22.csv")
RW_idx <- which(grepl("RW", Data$Positions))
ST_idx <- which(grepl("ST", Data$Positions))
GK_idx <- which(grepl("GK", Data$Positions))
CM_idx <- which(grepl("CM", Data$Positions))
LW_idx <- which(grepl("LW", Data$Positions))
CDM_idx <- which(grepl("CDM", Data$Positions))
LM_idx <- which(grepl("LM", Data$Positions))
CF_idx <- which(grepl("CF", Data$Positions))
CB_idx <- which(grepl("CB", Data$Positions))
CAM_idx <- which(grepl("CAM", Data$Positions))
LB_idx <- which(grepl("LB", Data$Positions))
RB_idx <- which(grepl("RB", Data$Positions))
RM_idx <- which(grepl("RM", Data$Positions))
LWB_idx <- which(grepl("LWB", Data$Positions))
RWB_idx <- which(grepl("RWB", Data$Positions))
#############
pop_init <- list()
# Create a list of vectors to loop through
position_vectors <- list(RW_idx, ST_idx, GK_idx, CM_idx, LW_idx,
CDM_idx, LM_idx, CF_idx, CB_idx, CAM_idx,
LB_idx, RB_idx, RM_idx, LWB_idx, RWB_idx)
position_vectors_list<-position_vectors
tournament_selection <- function(parents, t_size) {
# Select t_size random parents
random_parents_idx <- sample(nrow(parents), t_size, replace = FALSE)
random_parents <- parents[random_parents_idx, ]
# Evaluate the target function for each selected parent
random_parents_fitness <- apply(random_parents, 1, target)
# Select the best parent based on the target function value
best_parent_idx <- which.max(random_parents_fitness)
return(random_parents[best_parent_idx, ])
}
# Crossover function
crossover <- function(parent1, parent2) {
# Choose a random crossover point
crossover_point <- sample(2:(ncol(parent1) - 1), 1)
# Swap the position vectors after the crossover point
offspring1 <- c(parent1[1:crossover_point], parent2[(crossover_point + 1):ncol(parent1)])
offspring2 <- c(parent2[1:crossover_point], parent1[(crossover_point + 1):ncol(parent2)])
return(rbind(offspring1, offspring2))
}
mutate <- function(individual, position_vectors_list, probability = 0.09) {
for (pos_idx in 1:length(position_vectors_list)) {
if (runif(1) <= probability) {
repeat {
random_idx <- sample(position_vectors_list[[pos_idx]], 1)
if (!random_idx %in% individual) {
individual[pos_idx] <- random_idx
break
}
}
}
}
return(individual)
}
preserve_elites <- function(population, num_elites) {
population_fitness <- apply(population, 1, target)
elite_indices <- order(-population_fitness)[1:num_elites]
elites <- population[elite_indices, ]
return(as.matrix(elites))
}
initialize_individual <- function(position_vectors_list) {
individual <- sapply(position_vectors_list, function(pos) sample(pos, 1))
return(individual)
}
# Create initial population
n_rows <- 100
initial_population <- matrix(NA, n_rows, length(position_vectors))
for (i in 1:n_rows) {
individual <- initialize_individual(position_vectors)
initial_population[i, ] <- individual
}
# Define the target function
target <- function(parent_indices) {
position_ratings <- c("RWRating", "STRating", "GKRating", "CMRating",
"LWRating", "CDMRating", "LMRating", "CFRating",
"CBRating", "CAMRating", "LBRating", "RBRating",
"RMRating", "LWBRating", "RWBRating")
parent_data <- Data[parent_indices, ]
ratings <- parent_data[position_ratings]
ratings_log <- log(ratings)
potential_minus_age <- parent_data$Potential - parent_data$Age
log_value_eur_minus_wage_eur <- log(parent_data$ValueEUR) - log(parent_data$WageEUR)
int_reputation <- parent_data$IntReputation
# Apply constraints
constraint_penalty <- 0
if (sum(parent_data$ValueEUR) > 250000000) {
constraint_penalty <- constraint_penalty + 200
}
if (sum(parent_data$WageEUR) > 250000) {
constraint_penalty <- constraint_penalty + 200
}
if (any(ratings_log < 1.2)) {
constraint_penalty <- constraint_penalty + 200
}
target_value <- -(rowSums(ratings_log) + potential_minus_age - log_value_eur_minus_wage_eur + int_reputation) + constraint_penalty
return(target_value)
}
# Create a matrix to store the population
population <- as.matrix(population)
# Genetic algorithm parameters
population_size <- 100
num_generations <- 1000
tournament_size <- 5
num_elites <- 2
for (gen in 1:num_generations) {
# Preserve elites
elites <- preserve_elites(population, num_elites)
# Create an empty matrix to store offspring
offspring_population <- matrix(NA, population_size - num_elites, ncol(population))
# Perform crossover and mutation to generate offspring
for (i in seq(1, population_size - num_elites, 2)) {
# Select two parents using tournament selection
parent1 <- tournament_selection(population, tournament_size)
parent2 <- tournament_selection(population, tournament_size)
# Perform crossover to generate offspring
offspring <- crossover(parent1, parent2)
# Mutate offspring
offspring[1, ] <- mutate(offspring[1, ], position_vectors_list)
offspring[2, ] <- mutate(offspring[2, ], position_vectors_list)
# Add the generated offspring to the offspring population matrix
offspring_population[i, ] <- as.numeric(offspring[1, ])
offspring_population[(i + 1), ] <- as.numeric(offspring[2, ])
}
# Replace the old population with the offspring and elites
population <- rbind(elites, offspring_population)
# Calculate the fitness for the current population
population_fitness <- apply(population, 1, target)
# Get the best solution in the current population
best_solution <- population[which.max(population_fitness), ]
best_fitness <- max(population_fitness)
}
# Remove temporary variables
rm(offspring_population, population_fitness)
To Julia
|
cc4e446f892dba9e26bde3a9598c8d07
|
{
"intermediate": 0.294542133808136,
"beginner": 0.4073975682258606,
"expert": 0.2980602979660034
}
|
9,731
|
Fivem Scripting Server Side how to have argumnets
|
69edc2d9efcad16cc6f28c1b48938a75
|
{
"intermediate": 0.1535683423280716,
"beginner": 0.5112853050231934,
"expert": 0.33514630794525146
}
|
9,732
|
Fivem Scripting Server Side how to have arguments lua register command
|
fc2357fc52e418acf18687c9fae6e4cc
|
{
"intermediate": 0.2349349409341812,
"beginner": 0.510837197303772,
"expert": 0.2542278468608856
}
|
9,733
|
Give me example of POST method using RestTemplate with application/x-www-form-urlencoded Content-Type
|
bee05b900fb157a7aa42ff41ab136efc
|
{
"intermediate": 0.5792035460472107,
"beginner": 0.21002809703350067,
"expert": 0.21076832711696625
}
|
9,734
|
registercommand server side fivem lua
clients can trigger it. how do i stop them from doing so?
|
1fcf6ee5131112ba7e2554946b32893e
|
{
"intermediate": 0.4211145043373108,
"beginner": 0.31078633666038513,
"expert": 0.2680990993976593
}
|
9,735
|
Write a program in Wolfram Mathematica that solves a differential equation using four different methods
1. By the ritz method
2. The method of concatenated elements
3. The method of conjugate distinctions.
4. With the help of standard libraries of Wolphram mathematica.
For this, come up with a differential equation and boundary conditions for it. At the end of the program you should display the results of each method and a graph showing the difference in their answers
|
4b3c6389dfac219401f52765521d7dff
|
{
"intermediate": 0.5718359351158142,
"beginner": 0.13663241267204285,
"expert": 0.29153162240982056
}
|
9,736
|
registercommand server side fivem lua
clients can trigger it. how do i stop them from doing so?
|
bc0836de8623f7b2fd0b5dd30f7e1618
|
{
"intermediate": 0.4211145043373108,
"beginner": 0.31078633666038513,
"expert": 0.2680990993976593
}
|
9,737
|
write a simple python code which will fetch weather data from openweathermap json api
|
3f56f9636c6d265312a0d5111c7e3406
|
{
"intermediate": 0.7110273838043213,
"beginner": 0.135612353682518,
"expert": 0.1533602774143219
}
|
9,738
|
write a simple python code which will fetch weather data from openweathermap json api
|
0cb78168c15480ef5bafb4e92e3f603d
|
{
"intermediate": 0.7110273838043213,
"beginner": 0.135612353682518,
"expert": 0.1533602774143219
}
|
9,739
|
(SELECT Zuora__TotalAmount__c FROM Zuora__ZInvoice__r)
^
ERROR at Row:1:Column:65
Didn't understand relationship 'Zuora__ZInvoice__r' in FROM part of query call. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.
|
803e52f502a5a3d025f5a66567708fc0
|
{
"intermediate": 0.5263398289680481,
"beginner": 0.23396551609039307,
"expert": 0.23969469964504242
}
|
9,740
|
Wie bekomme ich die _isDisposed aus der _QRScannerState
und habe in der _QRScannerState keine Disposed funktion:
import 'dart:async';
import 'package:code_scan/code_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/patient_app_localizations.dart';
import 'package:patient_app/models/scan_result.dart';
import 'package:patient_app/theme/patient_app_colors.dart';
import 'package:patient_app/widgets/patient_app_back_button.dart';
typedef QrScanResultCallback = Future<bool> Function(ScanResult);
// see https://pub.dev/packages/code_scan/example
class QrScanner extends StatefulWidget {
const QrScanner(
{Key? key, required this.callback, required this.backButtonCallback})
: super(key: key);
final QrScanResultCallback callback;
final BackButtonCallback backButtonCallback;
@override
State<QrScanner> createState() => _QrScannerState();
}
class _QrScannerState extends State<QrScanner> with WidgetsBindingObserver {
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
late AppLocalizations _l10n;
bool _isDisposed = false;
// prevent over processing
bool processingInProgress = false;
@override
void didChangeDependencies() {
_l10n = AppLocalizations.of(context)!;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Container(
color: AppColors.opascaBlue,
child: _buildQrView(),
);
}
Widget _buildQrView() {
return CodeScanner(
key: qrKey,
formats: const [BarcodeFormat.qrCode],
scanInterval: const Duration(milliseconds: 500),
onScan: (code, _, listener) {
if (code != null) {
if (processingInProgress == false) {
processingInProgress = true;
widget.callback(ScanResult(code)).then((isValidCode) {
if (mounted && !isValidCode) {
processingInProgress = false;
}
});
}
}
},
onAccessDenied: (_, controller) {
_showPermissionNotGrantedDialog()
.then((_) => widget.backButtonCallback());
return false;
},
onError: (_, __) {
_showQrCodeReadErrorDialog();
},
overlay: Container(),
);
}
Future<dynamic> _showQrCodeReadErrorDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(_l10n.accountLinking_QrCodeScannerDialogTitle),
content: Text(_l10n.accountLinking_QrCodeScannerDialogDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
Future<dynamic> _showPermissionNotGrantedDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(
_l10n.accountLinking_QrCodeScannerMissingCameraPermissionTitle),
content: Text(_l10n
.accountLinking_QrCodeScannerMissingCameraPermissionDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
}
|
5f8b1cc2a4300cddd6af4bc1290c0190
|
{
"intermediate": 0.3835899233818054,
"beginner": 0.3209696412086487,
"expert": 0.2954404354095459
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.