row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
8,633
|
build some vanilla JavaScript component
|
c44867512735755d1918caa1be5423e0
|
{
"intermediate": 0.2621201276779175,
"beginner": 0.5387150645256042,
"expert": 0.1991647481918335
}
|
8,634
|
how can i use this string format: "/add 'this is some text' groupid times seconds" in C# while storing "'this is some text'", "groupid", "times", "seconds" in different variables?
|
420d817c18d7b64d1d3484866db66dd6
|
{
"intermediate": 0.5097465515136719,
"beginner": 0.3020997941493988,
"expert": 0.18815363943576813
}
|
8,635
|
EffectiveCapabilities=cap_chown cap_dac_override cap_dac_read_search
cap_fowner cap_fsetid cap_kill cap_setgid
cap_setuid cap_setpcap cap_linux_immutable cap_net_bind_service
cap_net_broadcast cap_net_admin cap_net_raw cap_ipc_lock
cap_ipc_owner cap_sys_module cap_sys_rawio cap_sys_chroot
cap_sys_ptrace cap_sys_pacct cap_sys_admin cap_sys_boot
cap_sys_nice cap_sys_resource cap_sys_time cap_sys_tty_config
cap_mknod cap_lease cap_audit_write cap_audit_control
cap_setfcap cap_mac_override cap_mac_admin cap_syslog
cap_wake_alarm cap_block_suspend cap_audit_read cap_perfmon
cap_bpf cap_checkpoint_restore как получить эти данные используя GIO и язык С? и что это вообще?
|
defebda9a50553e826d2686dba1e74df
|
{
"intermediate": 0.47681447863578796,
"beginner": 0.3758511245250702,
"expert": 0.14733441174030304
}
|
8,636
|
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
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 = 0.27
order_type = ‘MARKET’
leverage = 125
max_trade_quantity_percentage = 10
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+‘min ago UTC’))
frame = frame.iloc[:60,:6]
frame.columns = [‘Time’,‘Open’,‘High’,‘Low’,‘Close’,‘Volume’]
frame = frame.set_index(‘Time’)
today = dt.date.today()
frame.index = pd.to_datetime(frame.index, unit=‘ms’).tz_localize(‘UTC’).tz_convert(‘Etc/GMT+3’).strftime(f"{today} %H:%M:%S")
frame = frame.astype(float)
return frame
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 = getminutedata(‘BTCUSDT’, ‘5m’, ‘44640’)
signal = [“” for i in range(len(df))] # initialize signal as a list of empty strings
for i in range(1, len(df)):
df_temp = df[i-1:i+1]
signal[i] = signal_generator(df_temp)
df[“signal”] = signal
def order_execution(symbol, signal, max_trade_quantity_percentage):
max_trade_quantity_percentage = 10
buy = signal == “buy”
sell = signal == “sell”
signal = buy or sell
symbol = ‘BTCUSDT’
account_balance = client.futures_account_balance()
usdt_balance = float([x[‘balance’] for x in account_balance if x[‘asset’] == ‘USDT’][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
POSITION_SIDE_SHORT = SIDE_SELL
POSITION_SIDE_LONG = SIDE_BUY
long_position = POSITION_SIDE_LONG
short_position = POSITION_SIDE_SHORT
symbol = ‘BTCUSDT’
max_trade_quantity = 100
positions = client.futures_position_information(symbol=symbol)
long_position = next((p for p in positions if p[‘symbol’] == symbol and p[‘positionSide’] == ‘LONG’), None)
if long_position:
# Close long position if signal is opposite
if signal == “sell”:
order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position[‘positionAmt’],
reduceOnly=True
)
print(f"Closed long position with order ID {order[‘orderId’]}“)
time.sleep(1)
else:
if long_position is not None:
order_quantity = min(max_trade_quantity, float(long_position[‘positionAmt’]))
else:
print(“No long position found”)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_SHORT,
leverage=leverage
)
print(f"Placed short order with order ID {order[‘orderId’]} and quantity {order_quantity})”)
time.sleep(1)
# Set stop loss and take profit orders
stop_loss_price = order[‘avgPrice’] * (1 + STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order[‘avgPrice’] * (1 + TAKE_PROFIT_PERCENTAGE / 100)
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_SHORT
)
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_SHORT
)
print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}“)
time.sleep(1)
short_position = next((p for p in positions if p[‘symbol’] == symbol and p[‘positionSide’] == ‘SHORT’), None)
if short_position:
# Close short position if signal is opposite
if signal == “buy”:
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position[‘positionAmt’],
reduceOnly=True
)
print(f"Closed short position with order ID {order[‘orderId’]}”)
time.sleep(1)
else:
order_quantity = min(max_trade_quantity, float(short_position[‘maxNotionalValue’]) / leverage)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_LONG,
leverage=leverage
)
print(f"Placed long order with order ID {order[‘orderId’]} and quantity {order_quantity}“)
time.sleep(1)
# Set stop loss and take profit orders
stop_loss_price = order[‘avgPrice’] * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order[‘avgPrice’] * (1 - TAKE_PROFIT_PERCENTAGE / 100)
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_LONG
)
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_LONG
)
print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}”)
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime(“%Y-%m-%d %H:%M:%S”)
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution(symbol, current_signal,max_trade_quantity_percentage)
time.sleep(1) # Add a delay of 1 second But I getting ERROR: The signal time is: 2023-05-27 15:46:52 :sell
No long position found
Traceback (most recent call last):
File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 214, in <module>
order_execution(symbol, current_signal,max_trade_quantity_percentage)
File “c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py”, line 123, in order_execution
quantity=order_quantity,
^^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable ‘order_quantity’ where it is not associated with a value
|
c9f825b3dc319e8e77c6f8f3340730f0
|
{
"intermediate": 0.296960711479187,
"beginner": 0.4816133975982666,
"expert": 0.22142592072486877
}
|
8,637
|
In unreal engine 4 I want to create an scope, but due to the camera Field of view when you look through the scope the viewing area is very narrow. Can you write a custom HLSL shader code in the scope material to clip only the narrow area through the scope? for example when the player looking through the scope, the front end is as wide as the rear of the scope which we are looking through.
|
3c5dfe92ef627c3091006f8ea5514d84
|
{
"intermediate": 0.4640779495239258,
"beginner": 0.24091872572898865,
"expert": 0.29500335454940796
}
|
8,638
|
"clc
clear all
close all
% load Data
TimeLabel = importTime('july3.xlsx');
Data = importData('july3.xlsx');
nDays = 110;
TimeLabel = TimeLabel(2:nDays);
Data = Data(2:nDays);
TimeLabel = datetime(TimeLabel,"InputFormat","yyyyMMdd");
TimeLabel = string(TimeLabel);
ts = timeseries(Data,TimeLabel);
ts.Name = 'Close';
ts.TimeInfo.Format = 'mmm dd, yyyy';
figure
plot(ts,'LineWidth',2)"
expand this code to The data from 71 onwards in this time series ts should be drawn in orange color and dotted.
|
1f44cd455a4bb4dbfae823548e64cd46
|
{
"intermediate": 0.4086975157260895,
"beginner": 0.300933837890625,
"expert": 0.2903686463832855
}
|
8,639
|
I have a telegram bot made using C#. I have a for loop somewhere and i need a way to break the loop using a telegram prefix that is placed far from the for loop. how can we achieve this?
|
5a8d9dc94b1b00a7316489a9d5bba882
|
{
"intermediate": 0.2910226583480835,
"beginner": 0.5846990942955017,
"expert": 0.1242782324552536
}
|
8,640
|
kmeans = KMeans(n_clusters=num_clusters, random_state=0).fit(features)
in this line an error appears that says
ValueError: Expected 2D array, got scalar array instead:
array=10.0.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
what should I do ?
|
995d5c9f58f038cbbeb98ab30625bf01
|
{
"intermediate": 0.49553993344306946,
"beginner": 0.12907801568508148,
"expert": 0.3753820061683655
}
|
8,641
|
I have a telegram bot in C#, I have a for loop in one prefix and another /stop prefix. how can i makethe /stop prefix always running in the background so whenever it is triggered the for loop breaks?
|
dc6909ebd84c623236a52a146d415ecf
|
{
"intermediate": 0.4133123457431793,
"beginner": 0.44498005509376526,
"expert": 0.1417076289653778
}
|
8,642
|
Solve, using scilab, the Ordinary Differential Equation by the Adams-Bashforth method of order 6y''(t)+23.8y''(t)+1.3y'(t)+0.5y(t)=8;
y(0)=y'(0)=y'(0)=0;
t on the interval [0, 400];
|
03d04c159fb46eb942c85c03db99c933
|
{
"intermediate": 0.2723923325538635,
"beginner": 0.23027077317237854,
"expert": 0.4973369240760803
}
|
8,643
|
Python open serial port 4, baudrate 115200
|
633bd1f0c162f8eb5d18171ea158104d
|
{
"intermediate": 0.3600423336029053,
"beginner": 0.25636690855026245,
"expert": 0.38359078764915466
}
|
8,644
|
This is part of my telegram bot code in C#: "async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
// Echo received message text
for (int i = 0; i < Convert.ToInt32(Times); i++)
{
if (dd.IsStopped)
{
dd.IsStopped = false;
Message sendy = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "تم إيقاف الرسائل.",
cancellationToken: cancellationToken);
break;
}
await client.GroupMessage(GroupID, text);
int waiting = Convert.ToInt32(seconds) * 1000;
Message se = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "أرسل " + item.Email + " الرسالة بنجاح.",
cancellationToken: cancellationToken);
Thread.Sleep(waiting);
}
}
}" I need to make this for loop check every time if there's a new message has been sent to the bot, if the message is: "stop" we break the for loop.
|
657d5c8eadc8b13342becbc7b0f079f1
|
{
"intermediate": 0.4799121916294098,
"beginner": 0.33905521035194397,
"expert": 0.18103255331516266
}
|
8,645
|
write a simple Queue structure in C, with addQ and removeQ functions
|
9ceb7a6a2e5dfce761dc843f93368ee9
|
{
"intermediate": 0.27955394983291626,
"beginner": 0.3906062841415405,
"expert": 0.3298397660255432
}
|
8,646
|
Redis. how to create integer key with ttl 1 second, after which value is reset to 0 instead of deleting?
|
6c305fed9dda1b788a57685010a80c7d
|
{
"intermediate": 0.5623827576637268,
"beginner": 0.1247725710272789,
"expert": 0.3128446936607361
}
|
8,647
|
Make additions to the code below so that in the response it also returns name(), symbol(), decimals() the age of the creation of the contract Use the ABI application binary interface
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
if check_method_id(tx['input']):
contract_address = await get_contract_address(tx['hash'])
if contract_address:
print(f'New contract creation: Contract Address: {contract_address}')
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28466587 # Replace with your desired starting block number
block_end = 28466640 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
|
a30703350d934c75519644c1b88c8565
|
{
"intermediate": 0.38978201150894165,
"beginner": 0.4858655631542206,
"expert": 0.12435252964496613
}
|
8,648
|
this is a telegram bot made using telegram.bot in C#: "using Telegram.Bot.Exceptions;
using Telegram.Bot.Polling;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types;
using Telegram.Bot;
using WolfLive.Api;
using WolfLive.Api.Commands;
using Newtonsoft.Json;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics.SymbolStore;
namespace WolfyMessagesBot
{
internal class Program
{
public async static Task Main(string[] args)
{
var botClient = new TelegramBotClient("5860497272:AAGP5OqCiUFA-lIXVBwbkymtF60H9utp-Xw");
using CancellationTokenSource cts = new();
// StartReceiving does not block the caller thread. Receiving is done on the ThreadPool.
ReceiverOptions receiverOptions = new()
{
AllowedUpdates = Array.Empty<UpdateType>() // receive all update types except ChatMember related updates
};
botClient.StartReceiving(
updateHandler: HandleUpdateAsync,
pollingErrorHandler: HandlePollingErrorAsync,
receiverOptions: receiverOptions,
cancellationToken: cts.Token
);
var me = await botClient.GetMeAsync();
Console.WriteLine($"Start listening for @{me.Username}");
Console.ReadLine();
// Send cancellation request to stop bot
cts.Cancel();
async Task HandleUpdateAsync(ITelegramBotClient botClient, Update update, CancellationToken cancellationToken)
{
var dd = new Program();
// Only process Message updates: https://core.telegram.org/bots/api#message
if (update.Message is not { } message)
return;
// Only process text messages
if (message.Text is not { } messageText)
return;
var chatId = message.Chat.Id;
Console.WriteLine($"Received a '{messageText}' message in chat {chatId}.");
// Echo received message text
if (messageText.StartsWith("/اضف"))
{
string[] parts = messageText.Split();
// The first line contains the command (“/add”)
string command = parts[0];
// The second line contains the email address
string email = parts[1];
// The third line contains the password
string password = parts[2];
if (email != null || password != null)
{
var data = new AccountsList();
data.Email = email;
data.Password = password;
string jsonFromFile = System.IO.File.ReadAllText("accounts.json");
List<AccountsList>? accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile);
var search = accountsFromFile.Where(x => x.Email == email).FirstOrDefault();
if (search == null)
{
if (accountsFromFile == null)
{
var set = new List<AccountsList>();
set.Add(data);
string jsonString = JsonConvert.SerializeObject(set);
System.IO.File.WriteAllText("accounts.json", jsonString);
var jsonlist = "";
foreach (var item in set)
{
jsonlist = jsonlist + " \n" + item.Email;
}
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "تم اضافة الحساب " + email + "\n هذه هي القائمة الحالية بالحسابات الخاصة بك:" + jsonlist,
cancellationToken: cancellationToken);
}
else
{
// Add new accounts to the list
accountsFromFile.Add(data);
string jsonString = JsonConvert.SerializeObject(accountsFromFile);
System.IO.File.WriteAllText("accounts.json", jsonString);
var jsonlist = "";
foreach (var item in accountsFromFile)
{
jsonlist = jsonlist + " \n" + item.Email;
}
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "تم اضافة الحساب " + email + "\n هذه هي القائمة الحالية بالحسابات الخاصة بك:" + jsonlist,
cancellationToken: cancellationToken);
}
}
else
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "هذا الحساب موجود مُسبقًا.",
cancellationToken: cancellationToken);
}
}
else
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "يوجد خطأ في الإيعاز.",
cancellationToken: cancellationToken);
}
}
else if (messageText == "/تشغيل")
{
string jsonFromFile = System.IO.File.ReadAllText("accounts.json");
List<AccountsList> accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile);
Parallel.ForEach(accountsFromFile, async item =>
{
var client = new WolfClient();
var loggedIn = await client.Login(item.Email, item.Password);
if (!loggedIn)
{
Message senddMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "فشل تسجيل الدخول على حساب: " + item.Email,
cancellationToken: cancellationToken);
return;
}
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "تم بنجاح تسجيل الدخول على حساب: : " + item.Email,
cancellationToken: cancellationToken);
await Task.Delay(-1);
});
}
else if (messageText.StartsWith("/ارسل"))
{
var parts = Regex.Matches(messageText, @"[\""].+?[\""]|[^ ]+")
.Cast<Match>()
.Select(m => m.Value)
.ToList();
string text = parts[1].Replace("\"","");
string GroupID = parts[2];
string Times = parts[3];
string seconds = parts[4];
if (text != null || GroupID != null)
{
string jsonFromFile = System.IO.File.ReadAllText("accounts.json");
List<AccountsList> accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile);
Parallel.ForEach(accountsFromFile, async item =>
{
var client = new WolfClient();
var loggedIn = await client.Login(item.Email, item.Password);
if (!loggedIn)
{
Message senddMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "فشل تسجيل الدخول على حساب: " + item.Email,
cancellationToken: cancellationToken);
return;
}
if (Convert.ToInt32(Times) == 0 || Convert.ToInt32(seconds) == 0)
{
await client.GroupMessage(GroupID, text);
}
else
{
for (int i = 0; i < Convert.ToInt32(Times); i++)
{
await client.GroupMessage(GroupID, text);
int waiting = Convert.ToInt32(seconds) * 1000;
Message se = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "أرسل " + item.Email + " الرسالة بنجاح.",
cancellationToken: cancellationToken);
Thread.Sleep(waiting);
var messages = await botClient.GetUpdatesAsync(offset: update.Id, cancellationToken: cancellationToken);
var newMessage = messages.FirstOrDefault()?.Message;
}
}
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "أرسل " + item.Email + " الرسالة بنجاح.",
cancellationToken: cancellationToken);
await Task.Delay(-1);
});
}
else
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "يوجد خطأ في الإيعاز.",
cancellationToken: cancellationToken);
}
}
else if (messageText.StartsWith("/انضم"))
{
string[] parts = messageText.Split();
// The first line contains the command (“/add”)
string command = parts[0];
string GroupID = parts[1];
string Password = "";
if (parts.Length > 2)
{
Password = parts[2];
}
if (GroupID != null)
{
string jsonFromFile = System.IO.File.ReadAllText("accounts.json");
List<AccountsList> accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile);
Parallel.ForEach(accountsFromFile, async item =>
{
var client = new WolfClient();
var loggedIn = await client.Login(item.Email, item.Password);
if (!loggedIn)
{
Message senddMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "فشل تسجيل الدخول على حساب: " + item.Email,
cancellationToken: cancellationToken);
return;
}
if (Password == null)
{
await client.JoinGroup(GroupID);
}
else
{
await client.JoinGroup(GroupID, Password);
}
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "إنضم " + item.Email + "للروم بنجاح.",
cancellationToken: cancellationToken);
await Task.Delay(-1);
});
}
else
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "يوجد خطأ في الإيعاز.",
cancellationToken: cancellationToken);
}
}
else if (messageText == "/قائمة")
{
string jsonFromFile = System.IO.File.ReadAllText("accounts.json");
List<AccountsList>? accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile);
if (accountsFromFile == null)
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "لا يوجد أى حسابات في القائمة.",
cancellationToken: cancellationToken);
}
else
{
var show = "";
foreach (var item in accountsFromFile)
{
show = show + " \n" + item.Email;
}
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "الحسابات المُستخدمة: \n" + show,
cancellationToken: cancellationToken);
}
}
else if (messageText.StartsWith("/حذف"))
{
string jsonFromFile = System.IO.File.ReadAllText("accounts.json");
List<AccountsList>? accountsFromFile = JsonConvert.DeserializeObject<List<AccountsList>>(jsonFromFile);
if (accountsFromFile == null)
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "لا يوجد أى حسابات في القائمة.",
cancellationToken: cancellationToken);
}
else
{
string[] parts = messageText.Split();
string command = parts[0];
string emails = parts[1];
var data = accountsFromFile.Where(x => x.Email == emails).FirstOrDefault();
accountsFromFile.Remove(data);
string jsonString = JsonConvert.SerializeObject(accountsFromFile);
System.IO.File.WriteAllText("accounts.json", jsonString);
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "تم حذف " + emails + " من القائمة.",
cancellationToken: cancellationToken);
}
}
else if (messageText == "/وقف")
{
Message sentMessage = await botClient.SendTextMessageAsync(
chatId: chatId,
text: "تم إيقاف العملية.",
cancellationToken: cancellationToken);
}
}
Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
{
var ErrorMessage = exception switch
{
ApiRequestException apiRequestException
=> $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
_ => exception.ToString()
};
Console.WriteLine(ErrorMessage);
return Task.CompletedTask;
}
}
}
class AccountsList
{
public string Email { get; set; }
public string Password { get; set; }
}
}", there's a for loop at line 202 that i need to break if the user at any given point typed the prefix "/stop", how can i achieve that?
|
b1ba0fc4f94b45eb1f49a3061fbc16dc
|
{
"intermediate": 0.3697561025619507,
"beginner": 0.4609270393848419,
"expert": 0.16931691765785217
}
|
8,649
|
can you give me an example of use The Nelder-Mead algorithm optimize Keras model Weights? please use the iris dataset,thanks
|
9581158d1bf173d2cfa9f382c21ec8fa
|
{
"intermediate": 0.14044071733951569,
"beginner": 0.031587865203619,
"expert": 0.8279713988304138
}
|
8,650
|
Can you fix the problem
AttributeError: module ‘cv2’ has no attribute ‘TrackerKCF_create’
|
4d306fce854306551a2e65cda9d00f1f
|
{
"intermediate": 0.541706383228302,
"beginner": 0.20992901921272278,
"expert": 0.2483646422624588
}
|
8,651
|
how to make C# app always listening to a function i have in program.cs
|
24469c5b50645ed0635e1b6779838a15
|
{
"intermediate": 0.36420851945877075,
"beginner": 0.4425695836544037,
"expert": 0.19322189688682556
}
|
8,652
|
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int yylex();
void yyerror(const char* s);
%}
%union {
int num;
char* str;
}
%token <num> NUMBER
%token <str> IDENTIFIER STRING_LITERAL
%token IF ELSE FOR ADD SUB MUL DIV MOD ASSIGN EQ LT GT LE GE NEQ AND OR NOT SEMICOLON LPAREN RPAREN LBRACE RBRACE PKG MAIN IMPORT FUNC VAR PRINTLN PRINT INT_TYPE
%type <num> expression term factor
%type <str> program package_declaration import_declaration func_declaration statements statement var_declaration print_statement assignment_statement if_statement for_loop for_initializer for_update data_type
%left ADD SUB
%left MUL DIV
%left MOD
%nonassoc EQ LT GT LE GE NEQ
%left AND
%left OR
%nonassoc NOT
%start program
%%
program:
package_declaration import_declaration func_declaration
;
package_declaration:
PKG MAIN SEMICOLON{}
;
import_declaration:
IMPORT STRING_LITERAL SEMICOLON{}
;
func_declaration:
FUNC MAIN LPAREN RPAREN LBRACE statements RBRACE{}
;
statements:
statement
| statements statement
;
statement:
var_declaration SEMICOLON {
printf("variable declaration and assignment\n");
}
| print_statement SEMICOLON
| assignment_statement SEMICOLON
| if_statement
| for_loop
;
if_statement:
IF LPAREN expression RPAREN LBRACE statements RBRACE {
printf("if statement\n");
}
| IF LPAREN expression RPAREN LBRACE statements RBRACE ELSE LBRACE statements RBRACE {
printf("if-else statement\n");
}
;
for_loop:
FOR LPAREN for_initializer SEMICOLON expression SEMICOLON for_update RPAREN LBRACE statements RBRACE{}
;
for_initializer:
IDENTIFIER ASSIGN expression
;
for_update:
IDENTIFIER ASSIGN expression
;
var_declaration:
VAR IDENTIFIER data_type ASSIGN expression {
printf("var declaration: %s\n", $2);
}
;
print_statement:
PRINTLN LPAREN expression RPAREN {
printf("println statement\n");
}
| PRINT LPAREN expression RPAREN {
printf("print statement\n");
}
;
assignment_statement:
IDENTIFIER ASSIGN expression {
printf("%s = %d\n", $1, $3);
}
;
data_type:
INT_TYPE{}
;
expression:
expression ADD term {
$$ = $1 + $3;
}
| expression SUB term {
$$ = $1 - $3;
}
| term {
$$ = $1;
}
;
term:
term MUL factor {
$$ = $1 * $3;
}
| term DIV factor {
$$ = $1 / $3;
}
| factor {
$$ = $1;
}
;
factor:
NUMBER {
$$ = $1;
}
| IDENTIFIER {
printf("identifier: %s\n", $1);
}
| LPAREN expression RPAREN {
$$ = $2;
}
| SUB factor {
$$ = -$2;
}
| ADD factor {
$$ = $2;
}
| NOT factor {
$$ = !$2;
}
| factor MOD factor {
$$ = $1 % $3;
}
| expression EQ expression {
$$ = $1 == $3;
}
| expression LT expression {
$$ = $1 < $3;
}
| expression GT expression {
$$ = $1 > $3;
}
| expression LE expression {
$$ = $1 <= $3;
}
| expression GE expression {
$$ = $1 >= $3;
}
| expression NEQ expression {
$$ = $1 != $3;
}
| expression AND expression {
$$ = $1 && $3;
}
| expression OR expression {
$$ = $1 || $3;
}
| IDENTIFIER LPAREN RPAREN {
printf("function call: %s\n", $1);
}
| IDENTIFIER LPAREN expression RPAREN {
printf("function call with argument: %s\n", $1);
}
| IDENTIFIER LPAREN expression ',' expression RPAREN {
printf("function call with multiple arguments: %s\n", $1);
}
;
%%
void yyerror(const char* s) {
fprintf(stderr, "%s\n", s);
}
int main() {
yyparse();
return 0;
}
gptparser.y: warning: shift/reduce conflict on token MUL [-Wcounterexamples]
Example: expression EQ term • MUL factor
Shift derivation
term
↳ 27: factor
↳ 35: expression EQ expression
↳ 24: term
↳ 25: term • MUL factor
Reduce derivation
term
↳ 25: term MUL factor
↳ 27: factor
↳ 35: expression EQ expression
↳ 24: term •
|
1c15786610d48a27df07c24f66434bc8
|
{
"intermediate": 0.25593963265419006,
"beginner": 0.6523360013961792,
"expert": 0.09172441065311432
}
|
8,653
|
Modify the code below to get the following data about the token:
name, symbol, price, creation date. Use ABI Application Binary Interface for this
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
if check_method_id(tx['input']):
contract_address = await get_contract_address(tx['hash'])
if contract_address:
print(f'New contract creation: Contract Address: {contract_address}')
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28466587 # Replace with your desired starting block number
block_end = 28466640 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
|
7c3753610aa1e30dc90417b3a9100dc6
|
{
"intermediate": 0.4334021508693695,
"beginner": 0.4307703971862793,
"expert": 0.13582740724086761
}
|
8,654
|
у меня есть такие классы:
public abstract class MultipleReward extends Reward {
public MultipleReward(int duration) {
super(duration);
}
protected abstract void newSchedule(TownObject townObject);
public abstract void cancelScheduleOnNoPlayers(TownObject townObject);
public abstract void startIfNoTask(TownObject townObject);
}
public class CoinsReward extends MultipleReward {
Integer taskID;
int coins;
long millisTimeToNextReward;
long leftTime;
public CoinsReward(int minutesPeriod, int coins) {
super(minutesPeriod);
this.coins = coins;
this.taskID = null;
}
@Override
public Component[] loreReward() {
List<Component> components = new ArrayList<>();
components.add(Component.text(ChatColor.GRAY + "Награды:"));
if (coins != 0) {
components.add(Component.text(ChatColor.GREEN + "+" + ChatColor.GOLD + coins + "⛀" + ChatColor.GRAY + " монет" +
ChatColor.GRAY + " раз в " + ChatColor.AQUA + minutesPeriod + ChatColor.GRAY + " минут"));
}
return components.toArray(new Component[0]);
}
@Override
public void grantReward(TownObject townObject) {
newSchedule(townObject);
}
@Override
protected void newSchedule(TownObject townObject) {
if (leftTime == 0) this.millisTimeToNextReward = System.currentTimeMillis() + (minutesPeriod * 60000L);
else this.millisTimeToNextReward = System.currentTimeMillis() + leftTime;
taskID = TownyExtension.getInstance().getServer().getScheduler().runTaskLater(TownyExtension.getInstance(),
() -> getCoinsReward(townObject),
Utils.convertMillisecondsToTicks(millisTimeToNextReward)).getTaskId();
}
private void getCoinsReward(TownObject townObject) {
townObject.addCoins(coins);
grantReward(townObject);
}
@Override
public void cancelScheduleOnNoPlayers(TownObject townObject) {
if (taskID != null) {
leftTime = millisTimeToNextReward - System.currentTimeMillis();
TownyExtension.getInstance().getServer().getScheduler().cancelTask(taskID);
}
}
@Override
public void startIfNoTask(TownObject townObject) {
if (taskID == null) grantReward(townObject);
}
}
мне нужно как-то вынести cancelScheduleOnNoPlayers() и startIfNoTask() в MultipleReward, потому что они должны быть общими для всех наследников, функционал одинаковый
|
7ff1e197a3ac101820756d59f7936e52
|
{
"intermediate": 0.23500843346118927,
"beginner": 0.48908093571662903,
"expert": 0.2759106755256653
}
|
8,655
|
This is my ide program for a highsum gui game.
"import GUIExample.GameTableFrame;
import Model.*;
import GUIExample.LoginDialog;
public class GUIExample {
private Dealer dealer;
private Player player;
private GameTableFrame app;
public GUIExample() {
}
public void run() {
dealer.shuffleCards();
app = new GameTableFrame(dealer, player);
app.setVisible(true); // Replace app.run(); with this line
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
GUIExample example = new GUIExample();
example.dealer = new Dealer();
example.player = new Player(login, password, 10000);
example.run();
}
}
}
package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import java.awt.EventQueue;
import javax.swing.*;
public class HighSumGUI {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum() {
// Override the ‘run’ method to display and update the GameTableFrame
@Override
public void run() {
Dealer dealer = getDealer();
Player player = getPlayer();
GameTableFrame gameTableFrame = new GameTableFrame(dealer, player);
gameTableFrame.setVisible(true);
// Use a loop to continuously update and start new games as desired by the user
boolean carryOn = true;
while (carryOn) {
runOneRound();
gameTableFrame.updateScreen();
int response = JOptionPane.showConfirmDialog(
gameTableFrame,
"Do you want to play another game?",
"New Game",
JOptionPane.YES_NO_OPTION
);
carryOn = response == JOptionPane.YES_OPTION;
}
gameTableFrame.dispose();
}
};
highSum.init(login, password);
highSum.run();
}
}
});
}
}
package Controller;
import Model.Dealer;
import Model.Player;
import View.ViewController;
public class GameController {
private Dealer dealer;
private Player player;
private ViewController view;
private int chipsOnTable;
private boolean playerQuit;
public GameController(Dealer dealer,Player player,ViewController view) {
this.dealer = dealer;
this.player = player;
this.view = view;
this.chipsOnTable = 0;
}
public boolean getPlayerQuitStatus() {
return playerQuit;
}
public void run() {
boolean carryOn= true;
while(carryOn) {
runOneRound();
char r = this.view.getPlayerNextGame();
if(r=='n') {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for(int round = 1;round<=4;round++) {
this.view.displaySingleLine();
this.view.displayDealerDealCardsAndGameRound(round);
this.view.displaySingleLine();
if (round == 1) { //round 1 deal extra card
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
} else {
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
}
this.view.displayPlayerCardsOnHand(this.dealer);
this.view.displayBlankLine();
this.view.displayPlayerCardsOnHand(player);
this.view.displayPlayerTotalCardValue(player);
int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard());
if(whoCanCall==1) {//dealer call
int chipsToBet = this.view. getDealerCallBetChips();
//ask player want to follow?
char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet);
if(r=='y') {
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}else {//player call
if(round==1) {//round 1 player cannot quit
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayBetOntable(this.chipsOnTable);
}else {
char r = this.view.getPlayerCallOrQuit();
if(r=='c') {
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}
}
}
//check who win
if(playerQuit) {
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) {
this.view.displayPlayerWin(this.player);
this.player.addChips(chipsOnTable);
this.chipsOnTable=0;
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) {
this.view.displayDealerWin();
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else {
this.view.displayTie();
this.player.addChips(chipsOnTable/2);
this.view.displayPlayerNameAndLeftOverChips(this.player);
}
//put all the cards back to the deck
dealer.addCardsBackToDeck(dealer.getCardsOnHand());
dealer.addCardsBackToDeck(player.getCardsOnHand());
dealer.clearCardsOnHand();
player.clearCardsOnHand();
}
}
package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GameTableFrame extends JFrame {
private GameTablePanel gameTablePanel;
private Dealer dealer;
private Player player;
private JLabel shufflingLabel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
gameTablePanel = new GameTablePanel(dealer, player);
shufflingLabel = new JLabel("Shuffling");
shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER);
playButton = new JButton("Play");
quitButton = new JButton("Quit");
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
shufflingLabel.setVisible(true);
HighSum highSum = new HighSum();
highSum.init(player.getLoginName(), "some_default_password");
highSum.run();
updateScreen();
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// Create the main panel that contains both the game board and the buttons
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(playButton);
buttonsPanel.add(quitButton);
mainPanel.add(gameTablePanel, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
mainPanel.add(shufflingLabel, BorderLayout.NORTH);
shufflingLabel.setVisible(false);
add(mainPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// This method updates the screen after each game
public void updateScreen() {
gameTablePanel.updateTable(dealer, player);
}
}
package GUIExample;
import java.awt.*;
import javax.swing.*;
import Model.*;
public class GameTablePanel extends JPanel {
private Player player;
private Dealer dealer;
public GameTablePanel(Dealer dealer, Player player) {
setLayout(new BorderLayout());
setBackground(Color.GREEN);
setPreferredSize(new Dimension(1024, 768));
this.dealer = dealer;
this.player = player;
}
public void updateTable(Dealer dealer, Player player) {
this.dealer = dealer;
this.player = player;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw dealer’s cards
int dealerX = 50;
int dealerY = 100;
g.drawString("Dealer", dealerX, dealerY - 20);
dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true);
// Draw player’s cards
int playerX = 50;
int playerY = getHeight() - 200;
g.drawString("Player", playerX, playerY - 20);
playerX = drawPlayerHand(g, player, playerX, playerY, false);
// Draw chips on the table
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 18));
g.drawString("Chips on the table: ", playerX + 50, playerY);
}
private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) {
int i = 0;
for (Card c : p.getCardsOnHand()) {
if (isDealer && i == 0) {
new ImageIcon("images/back.png").paintIcon(this, g, x, y);
} else {
c.paintIcon(this, g, x, y);
}
x += 100;
i++;
}
return x;
}
}
package GUIExample;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog {
private JTextField loginField;
private JPasswordField passwordField;
private JButton loginButton;
private boolean loggedIn = false;
public LoginDialog(JFrame parent) {
super(parent, "Login", true);
loginField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loggedIn = true;
dispose();
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("Login:"));
panel.add(loginField);
panel.add(new JLabel("Password:"));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
pack();
setLocationRelativeTo(parent);
}
public String getLogin() {
return loginField.getText();
}
public String getPassword() {
return new String(passwordField.getPassword());
}
public boolean isLoggedIn() {
return loggedIn;
}
}
package Helper;
public class Keyboard {
public static String readString(String prompt) {
System.out.print(prompt);
return new java.util.Scanner(System.in).nextLine();
}
public static int readInt(String prompt) {
int input = 0;
boolean valid = false;
while (!valid) {
try {
input = Integer.parseInt(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter an integer ***");
}
}
return input;
}
public static double readDouble(String prompt) {
double input = 0;
boolean valid = false;
while (!valid) {
try {
input = Double.parseDouble(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a double ***");
}
}
return input;
}
public static float readFloat(String prompt) {
float input = 0;
boolean valid = false;
while (!valid) {
try {
input = Float.parseFloat(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a float ***");
}
}
return input;
}
public static long readLong(String prompt) {
long input = 0;
boolean valid = false;
while (!valid) {
try {
input = Long.parseLong(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("*** Please enter a long ***");
}
}
return input;
}
public static char readChar(String prompt,char[] choices) {
boolean validChoice = false;
char r = ' ';
while(!validChoice) {
r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":");
if(!validateChoice(choices,r)) {
System.out.println("Invalid input");
}else {
validChoice = true;
}
}
return r;
}
private static String charArrayToString(char[] charArray) {
String s = "[";
for(int i=0;i<charArray.length;i++) {
s+=charArray[i];
if(i!=charArray.length-1) {
s+=",";
}
}
s += "]";
return s;
}
private static boolean validateChoice(char[] choices, char choice) {
boolean validChoice = false;
for(int i=0;i<choices.length;i++) {
if(choices[i]==choice) {
validChoice = true;
break;
}
}
return validChoice;
}
public static char readChar(String prompt) {
char input = 0;
boolean valid = false;
while (!valid) {
String temp = readString(prompt);
if (temp.length() != 1) {
System.out.println("*** Please enter a character ***");
} else {
input = temp.charAt(0);
valid = true;
}
}
return input;
}
public static boolean readBoolean(String prompt) {
boolean valid = false;
while (!valid) {
String input = readString(prompt);
if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true")
|| input.equalsIgnoreCase("t")) {
return true;
} else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false")
|| input.equalsIgnoreCase("f")) {
return false;
} else {
System.out.println("*** Please enter Yes/No or True/False ***");
}
}
return false;
}
public static java.util.Date readDate(String prompt) {
java.util.Date date = null;
boolean valid = false;
while (!valid) {
try {
String input = readString(prompt).trim();
if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) {
int day = Integer.parseInt(input.substring(0, 2));
int month = Integer.parseInt(input.substring(3, 5));
int year = Integer.parseInt(input.substring(6, 10));
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, day, 0, 0, 0);
date = cal.getTime();
valid = true;
} else {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
} catch (IllegalArgumentException e) {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
}
return date;
}
private static String quit = "0";
public static int getUserOption(String title, String[] menu) {
displayMenu(title, menu);
int choice = Keyboard.readInt("Enter Choice --> ");
while (choice > menu.length || choice < 0) {
choice = Keyboard.readInt("Invalid Choice, Re-enter --> ");
}
return choice;
}
private static void displayMenu(String title, String[] menu) {
line(80, "=");
System.out.println(title.toUpperCase());
line(80, "-");
for (int i = 0; i < menu.length; i++) {
System.out.println("[" + (i + 1) + "] " + menu[i]);
}
System.out.println("[" + quit + "] Quit");
line(80, "-");
}
public static void line(int len, String c) {
System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c));
}
}
package Helper;
import java.security.MessageDigest;
public class Utility {
public static String getHash(String base)
{
String message="";
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
message = hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
return message;
}
public static void printLine(int num)
{
printLine(num,'-');
}
public static void printDoubleLine(int num)
{
printLine(num,'=');
}
public static void printLine(int num,char pattern)
{
for(int i =0;i<num;i++)
{
System.out.print(pattern);
}
System.out.println("");
}
}
package Model;
import javax.swing.*;
public class Card extends ImageIcon {
private String suit;
private String name;
private int value;
private int rank;
private boolean faceDown;
public Card(String suit, String name, int value, int rank) {
super("images/" + suit + name + ".png");
this.suit = suit;
this.name = name;
this.value = value;
this.rank = rank;
this.faceDown = false;
}
public boolean isFaceDown() {
return this.faceDown;
}
public void setFaceDown(boolean faceDown) {
this.faceDown = faceDown;
}
public String getSuit() {
return this.suit;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public int getRank() {
return this.rank;
}
public String toString() {
if (this.faceDown) {
return "<HIDDEN CARD>";
} else {
return "<" + this.suit + " " + this.name + ">";
}
}
public String display() {
return "<"+this.suit+" "+this.name+" "+this.rank+">";
}
}
//card rank
// D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.*;
public class Dealer extends Player {
private Deck deck;
public Dealer() {
super("Dealer", "", 0);
deck = new Deck();
}
public void shuffleCards() {
System.out.println("Dealer shuffle deck");
deck.shuffle();
}
public void dealCardTo(Player player) {
Card card = deck.dealCard(); // take a card out from the deck
player.addCard(card); // pass the card into the player
}
public void addCardsBackToDeck(ArrayList<Card> cards) {
deck.appendCard(cards);
}
//return 1 if card1 rank higher, else return 2
public int determineWhichCardRankHigher(Card card1, Card card2) {
if(card1.getRank()>card2.getRank()) {
return 1;
}else {
return 2;
}
}
}
package Model;
import java.util.*;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = { "Diamond", "Club","Heart","Spade", };
for (int i = 0; i < suits.length; i++) {
String suit = suits[i];
Card card = new Card(suit, "Ace", 1,1+i);
cards.add(card);
int c = 5;
for (int n = 2; n <= 10; n++) {
Card oCard = new Card(suit, "" + n, n,c+i);
cards.add(oCard);
c+=4;
}
Card jackCard = new Card(suit, "Jack", 10,41+i);
cards.add(jackCard);
Card queenCard = new Card(suit, "Queen", 10,45+i);
cards.add(queenCard);
Card kingCard = new Card(suit, "King", 10,49+i);
cards.add(kingCard);
}
}
public Card dealCard() {
return cards.remove(0);
}
//add back one card
public void appendCard(Card card) {
cards.add(card);
}
//add back arraylist of cards
public void appendCard(ArrayList<Card> cards) {
for(Card card: cards) {
this.cards.add(card);
}
}
public void shuffle() {
Random random = new Random();
for(int i=0;i<10000;i++) {
int indexA = random.nextInt(cards.size());
int indexB = random.nextInt(cards.size());
Card cardA = cards.get(indexA);
Card cardB = cards.get(indexB);
cards.set(indexA, cardB);
cards.set(indexB, cardA);
}
}
//for internal use only
private void showCards() {
for (Card card : cards) {
System.out.println(card);
}
}
//for internal use only
private void displayCards() {
for (Card card : cards) {
System.out.println(card.display());
}
}
public static void main(String[] args) {
Deck deck = new Deck();
//deck.shuffle();
/*Card card1 = deck.dealCard();
Card card2 = deck.dealCard();
Card card3 = deck.dealCard();
deck.showCards();
ArrayList<Card> cards = new ArrayList<Card>();
cards.add(card1);
cards.add(card2);
cards.add(card3);
deck.appendCard(cards);
System.out.println();*/
deck.displayCards();
}
}
//card rank
//D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import Controller.*;
import View.*;
import GUIExample.LoginDialog;
import GUIExample.GameTableFrame;
import javax.swing.JOptionPane;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class HighSum {
private Dealer dealer;
private Player player;
private ViewController view;
private GameController gc;
private int chipsOnTable;
public HighSum() {
}
public void init(String login, String password) {
// Create all the required objects
this.dealer = new Dealer();
this.player = new Player(login, password, 50);
this.view = new ViewController();
// Bring them together
this.gc = new GameController(this.dealer, this.player, this.view);
}
private Player checkWinner() {
if(player.getTotalCardsValue() > dealer.getTotalCardsValue())
return player;
else if(player.getTotalCardsValue() < dealer.getTotalCardsValue())
return dealer;
else
return null;
}
public Dealer getDealer() {
return dealer;
}
public Player getPlayer() {
return player;
}
public void run() {
// Setup the game table
GameTableFrame gameTableFrame = new GameTableFrame(dealer, player);
// Starts the game!
boolean carryOn = true;
while (carryOn) {
runOneRound();
gameTableFrame.updateScreen();
if (!gc.getPlayerQuitStatus()) {
int response = JOptionPane.showConfirmDialog(
gameTableFrame,
"Do you want to play another game?",
"New Game",
JOptionPane.YES_NO_OPTION
);
carryOn = response == JOptionPane.YES_OPTION;
} else {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
gameTableFrame.dispose();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for (int round = 1; round <= 4; round++) {
// Code remains same until here
// Check if the player wants to follow or quit
char r;
int chipsToBet;
if (round == 1) {
chipsToBet = this.view.getPlayerCallBetChip(this.player);
} else {
chipsToBet = this.view.getDealerCallBetChips();
}
}
Player winner = checkWinner();
if(playerQuit){
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
}
/* public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum();
highSum.init(login, password);
highSum.run();
}
}*/
}
package Model;
import java.util.*;
public class Player extends User{
private int chips;
protected ArrayList<Card> cardsOnHand;
public Player(String loginName, String password, int chips) {
super(loginName, password);
this.chips = chips;
this.cardsOnHand = new ArrayList<Card>();
}
public int getChips() {
return this.chips;
}
public void addChips(int amount) {
this.chips+=amount;//no error check
}
public void deductChips(int amount) {
this.chips-=amount;//no error check
}
public void addCard(Card card) {
this.cardsOnHand.add(card);
}
public ArrayList<Card> getCardsOnHand() {
return this.cardsOnHand;
}
public int getTotalCardsValue() {
int total = 0;
for(Card card: this.cardsOnHand) {
total+=card.getValue();
}
return total;
}
public Card getLastCard() {
return this.cardsOnHand.get(this.cardsOnHand.size()-1);
}
public void clearCardsOnHand() {
this.cardsOnHand.clear();
}
//Think of the action that a player can take
//implement more related methods here
public static void main(String[] args) {
// TODO Auto-generated method stub
Player player = new Player("IcePeak","A",100);
System.out.println(player.getChips());
player.deductChips(10);
System.out.println(player.getChips());
player.addChips(20);
System.out.println(player.getChips());
}
}
package Model;
import Helper.*;
abstract public class User {
private String loginName;
private String hashPassword;
public User(String loginName, String password) {
this.loginName = loginName;
this.hashPassword = Utility.getHash(password);
}
public String getLoginName() {
return this.loginName;
}
public boolean checkPassword(String password) {
return this.hashPassword.equals(Utility.getHash(password));
}
}
package View;
import Helper.*;
import Model.*;
//all input and output should be done view ViewController
//so that it is easier to implement GUI later
public class ViewController {
public void displayExitGame() {
System.out.println("Thank you for playing HighSum game");
}
public void displayBetOntable(int bet) {
System.out.println("Bet on table : "+bet);
}
public void displayPlayerWin(Player player) {
System.out.println(player.getLoginName()+" Wins!");
}
public void displayDealerWin() {
System.out.println("Dealer Wins!");
}
public void displayTie() {
System.out.println("It is a tie!.");
}
public void displayPlayerQuit() {
System.out.println("You have quit the current game.");
}
public void displayPlayerCardsOnHand(Player player) {
System.out.println(player.getLoginName());
if(player instanceof Dealer) {
for (int i = 0; i < player.getCardsOnHand().size(); i++) {
if (i == 0) {
System.out.print("<HIDDEN CARD> ");
} else {
System.out.print(player.getCardsOnHand().get(i).toString() + " ");
}
}
} else {
for (Card card : player.getCardsOnHand()) {
System.out.print(card + " ");
}
}
System.out.println();
}
public void displayBlankLine() {
System.out.println();
}
public void displayPlayerTotalCardValue(Player player) {
System.out.println("Value:"+player.getTotalCardsValue());
}
public void displayDealerDealCardsAndGameRound(int round) {
System.out.println("Dealer dealing cards - ROUND "+round);
}
public void displayGameStart() {
System.out.println("Game starts - Dealer shuffle deck");
}
public void displayPlayerNameAndChips(Player player) {
System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips");
}
public void displayPlayerNameAndLeftOverChips(Player player) {
System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips");
}
public void displayGameTitle() {
System.out.println("HighSum GAME");
}
public void displaySingleLine() {
for(int i=0;i<30;i++) {
System.out.print("-");
}
System.out.println();
}
public void displayDoubleLine() {
for(int i=0;i<30;i++) {
System.out.print("=");
}
System.out.println();
}
public char getPlayerCallOrQuit() {
char[] choices = {'c','q'};
char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices);
return r;
}
public char getPlayerFollowOrNot(Player player, int dealerBet) {
boolean validChoice = false;
char[] choices = {'y','n'};
char r = 'n';
while(!validChoice) {
r = Keyboard.readChar("Do you want to follow?",choices);
//check if player has enff chips to follow
if(r=='y' && player.getChips()<dealerBet) {
System.out.println("You do not have enough chips to follow");
displayPlayerNameAndChips(player);
}else {
validChoice = true;
}
}
return r;
}
public char getPlayerNextGame() {
char[] choices = {'y','n'};
char r = Keyboard.readChar("Next game?",choices);
return r;
}
public int getPlayerCallBetChip(Player player) {
boolean validBetAmount = false;
int chipsToBet = 0;
while(!validBetAmount) {
chipsToBet = Keyboard.readInt("Player call, state bet:");
if(chipsToBet<0) {
System.out.println("Chips cannot be negative");
}else if(chipsToBet>player.getChips()) {
System.out.println("You do not have enough chips");
}else {
validBetAmount = true;
}
}
return chipsToBet;
}
public int getDealerCallBetChips() {
System.out.println("Dealer call, state bet: 10");
return 10;
}
}
"
These are the requirements:
"On completion of this assignment a student should be able to write a Java application
that:
• Makes use of Java API "Swing" and "AWT" packages
• Handles generated events
• Makes use of layout manager to organize the GUI components
• Know how to apply and design a program using object-oriented concepts
2. Task
Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI).
2.1 Login
The game starts by the player logging into the game.
2.2 Play Game
The game starts after the player click on “Login”.
First, the dealer will shuffles the deck.
(You may include animation in this frame to simulate “shuffle” effect as enhancement.)
Then the dealer deals two cards from the top of the deck to the player and itself.
Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game.
Assume the player states 10 as the bet chips.
The player’s chip will be deducted by 10.
The chips on table will be updated to 20 and the dealer deals cards for next round.
Assume the dealer’s last card is higher than the player’s last card.
The dealer Call the game and the player gets to choose to Follow or Quit the game.
If the player follows the game, 10 chips will be deducted from the player’s balance chips.
(Asumme the dealer place 10 chips.)
The games carry on for maximum of four rounds.
In the last round, the player with the highest total sum wins the game.
And the game continues until the player exits the game.
Error Handling
Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips.
You should look out for other possible exceptions and handle them too."
Edit the code so that when highsum gui is run,
The gui uses these file names as images for the cards
"back.png
Club10.png
Club2.png
Club3.png
Club4.png
Club5.png
Club6.png
Club7.png
Club8.png
Club9.png
ClubAce.png
ClubJack.png
ClubKing.png
ClubQueen.png
Diamond10.png
Diamond2.png
Diamond3.png
Diamond4.png
Diamond5.png
Diamond6.png
Diamond7.png
Diamond8.png
Diamond9.png
DiamondAce.png
DiamondJack.png
DiamondKing.png
DiamondQueen.png
Heart10.png
Heart2.png
Heart3.png
Heart4.png
Heart5.png
Heart6.png
Heart7.png
Heart8.png
Heart9.png
HeartAce.png
HeartJack.png
HeartKing.png
HeartQueen.png
Spade10.png
Spade2.png
Spade3.png
Spade4.png
Spade5.png
Spade6.png
Spade7.png
Spade8.png
Spade9.png
SpadeAce.png
SpadeJack.png
SpadeKing.png
SpadeQueen.png"
|
9770d2c98f44f80e32b29ce38b9c9285
|
{
"intermediate": 0.2889218032360077,
"beginner": 0.6018312573432922,
"expert": 0.10924690216779709
}
|
8,656
|
Video editor application banane ke liye kaun sa programming language ka use hota Hai
|
3a4ec20ac915ed38d595efa06a8068a1
|
{
"intermediate": 0.20909805595874786,
"beginner": 0.5702588558197021,
"expert": 0.22064319252967834
}
|
8,657
|
Complete the code below so that it also displays the age of the token address in the response
import asyncio
import aiohttp
import json
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Define ABI request URLs
abi_url = f'https://api.bscscan.com/api?module=contract&action=getabi&apikey={bscscan_api_key}'
# Define the contract method signatures
name_signature = '0x06fdde03'
symbol_signature = '0x95d89b41'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
async def get_contract_info(contract_address, method_signature):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_call&to={contract_address}&data={method_signature}&tag=latest&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
result = data.get('result')
if result is None or not isinstance(result, str):
return None
# Decode the returned data
result = bytes.fromhex(result[2:]).decode()
return result.strip("\x00")
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
if check_method_id(tx['input']):
contract_address = await get_contract_address(tx['hash'])
token_name = await get_contract_info(contract_address, name_signature)
token_symbol = await get_contract_info(contract_address, symbol_signature)
print(f'New contract creation: Contract Address: {contract_address}')
print(f'Token Name: {token_name}, Token Symbol: {token_symbol} ')
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28466587 # Replace with your desired starting block number
block_end = 28466640 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
|
3da913893b172fe420276b682b326fd7
|
{
"intermediate": 0.3743782639503479,
"beginner": 0.5121715068817139,
"expert": 0.1134503036737442
}
|
8,658
|
гдк ошибка в @Override?
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
System.out.println("Введите сторону a");
int a = scn.nextInt();
System.out.println("Введите сторону b");
int b = scn.nextInt();
Rectangle r1 = new Rectangle();
Square s1 = new Square();
r1.getArea(a,b);
s1.getArea(a);
System.out.println("Прямоугольник: "+r1.getArea(a,b));
System.out.println("Квадрат: "+s1.getArea(a));
System.out.println(a);
}
}
class Rectangle{
public int getArea(int a,int b){
return a*b;
}
}
class Square extends Rectangle{
@Override
public int getArea(int a){
return a*a;
}
}
|
8b2201ba8fde8635a9c7d95cf7f16f87
|
{
"intermediate": 0.33452746272087097,
"beginner": 0.502278745174408,
"expert": 0.1631937474012375
}
|
8,659
|
使用Nessus扫描,提示Unable to resolve DNS 'r.nessus.org' to check Log4j Vulnerability.
|
57ed9d48dfd00fe1600a9b9befe92339
|
{
"intermediate": 0.32801470160484314,
"beginner": 0.35770243406295776,
"expert": 0.3142828345298767
}
|
8,660
|
i have a kotlin app. in it i have a function, lets call it f1. i want to display a progress bar (indefinite progress bar) for as long as f1 is running
|
ed4e0f9567a05084487c5084f02c3b61
|
{
"intermediate": 0.4134749472141266,
"beginner": 0.2518063485622406,
"expert": 0.3347187340259552
}
|
8,661
|
Change the code below so that the date format in the response is displayed as y m d h m s. If the value in front is zero, then they should not be displayed
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном интревале блоков (Обрабатывет множество блоков)
import asyncio
import aiohttp
from datetime import datetime
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Define ABI request URLs
abi_url = f'https://api.bscscan.com/api?module=contract&action=getabi&apikey={bscscan_api_key}'
# Define the contract method signatures
name_signature = '0x06fdde03'
symbol_signature = '0x95d89b41'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
async def get_block_timestamp(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return None
return data['result'].get('timestamp')
async def get_contract_info(contract_address, method_signature):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_call&to={contract_address}&data={method_signature}&tag=latest&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
result = data.get('result')
if result is None or not isinstance(result, str):
return None
# Decode the returned data
result = bytes.fromhex(result[2:]).decode()
return result.strip("\x00")
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
if check_method_id(tx['input']):
contract_address = await get_contract_address(tx['hash'])
timestamp = await get_block_timestamp(block_number)
age_seconds = int(datetime.now().timestamp()) - int(timestamp, 16)
token_name = await get_contract_info(contract_address, name_signature)
token_symbol = await get_contract_info(contract_address, symbol_signature)
print(f'New contract creation: Contract Address: {contract_address}')
print(f'Token Name: {token_name}, Token Symbol: {token_symbol}')
print(f'Age of the token address: {age_seconds} seconds')
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28466587 # Replace with your desired starting block number
block_end = 28467640 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
|
6740234acbc889e02414ea89ec8574b7
|
{
"intermediate": 0.38839268684387207,
"beginner": 0.4254501760005951,
"expert": 0.18615710735321045
}
|
8,662
|
у меня есть такой класс export class ConfirmOrderComponent implements OnInit {
хочу использовать его в export class PageMarketGiftComponent {
|
23b42deec8d11752dfab5e295a3e7401
|
{
"intermediate": 0.34823140501976013,
"beginner": 0.46048662066459656,
"expert": 0.1912819892168045
}
|
8,663
|
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 127, in <module>
asyncio.run(main())
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 125, in main
await display_transactions(block_start, block_end)
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 119, in display_transactions
await asyncio.gather(*tasks)
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 111, in process_block
token_name = await get_contract_info(contract_address, name_signature)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 89, in get_contract_info
result = bytes.fromhex(result[2:]).decode()
^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: non-hexadecimal number found in fromhex() arg at position 0
Process finished with exit code 1
The code that resulted in the error is shown below.
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 127, in <module>
asyncio.run(main())
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 125, in main
await display_transactions(block_start, block_end)
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 119, in display_transactions
await asyncio.gather(*tasks)
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 111, in process_block
token_name = await get_contract_info(contract_address, name_signature)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 89, in get_contract_info
result = bytes.fromhex(result[2:]).decode()
^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: non-hexadecimal number found in fromhex() arg at position 0
Process finished with exit code 1
|
ebc7e65bcbb76d86671b701f69902d5f
|
{
"intermediate": 0.3375992476940155,
"beginner": 0.4223949611186981,
"expert": 0.24000579118728638
}
|
8,664
|
hi, please write a python script to build an empty streamlit app
|
9fc0423966eecccb92be64161f12c879
|
{
"intermediate": 0.47727522253990173,
"beginner": 0.17550243437290192,
"expert": 0.34722235798835754
}
|
8,665
|
write me a docker compose that spins up fastapi+celery+flower+redis and write me a python module that uses it to do onnx-model predictions
|
6e13c4ef7c5d60004f7f92eb49a96a6f
|
{
"intermediate": 0.7709735035896301,
"beginner": 0.05389485880732536,
"expert": 0.17513158917427063
}
|
8,666
|
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 137, in <module>
asyncio.run(main())
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 135, in main
await display_transactions(block_start, block_end)
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 129, in display_transactions
await asyncio.gather(*tasks)
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 120, in process_block
age = format_age(timestamp)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\pythonProject4\main.py", line 101, in format_age
age = int(datetime.now().timestamp()) - int(timestamp, 16)
^^^^^^^^^^^^^^^^^^
TypeError: int() can't convert non-string with explicit base
Process finished with exit code 1
The code that resulted in the error is shown below.
# Оптимизированный!!! Возвращает адреса созданных токенов в указанном интревале блоков (Обрабатывет множество блоков)
import asyncio
import aiohttp
from datetime import datetime
import re
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Define ABI request URLs
abi_url = f'https://api.bscscan.com/api?module=contract&action=getabi&apikey={bscscan_api_key}'
# Define the contract method signatures
name_signature = '0x06fdde03'
symbol_signature = '0x95d89b41'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
async def get_block_timestamp(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return None
return data['result'].get('timestamp')
def is_hex(string):
return re.fullmatch(r"^(0x)?[0-9a-fA-F]*$", string) is not None
async def get_contract_info(contract_address, method_signature):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_call&to={contract_address}&data={method_signature}&tag=latest&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
result = data.get('result')
if is_hex(result):
# Normal execution
result = bytes.fromhex(result[2:]).decode()
else:
result = "Error: Invalid hex string"
return result
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
def format_age(timestamp):
age = int(datetime.now().timestamp()) - int(timestamp, 16)
d, rem = divmod(age, 86400)
h, rem = divmod(rem, 3600)
m, s = divmod(rem, 60)
return f"{d}d {h}h {m}m {s}s" if d else f"{h}h {m}m {s}s" if h else f"{m}m {s}s" if m else f"{s}s"
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
if check_method_id(tx['input']):
contract_address = await get_contract_address(tx['hash'])
timestamp = await get_block_timestamp(block_number)
age = format_age(timestamp)
token_name = await get_contract_info(contract_address, name_signature)
token_symbol = await get_contract_info(contract_address, symbol_signature)
print(f'New contract creation: Contract Address: {contract_address}')
print(f'Token Name: {token_name}, Token Symbol: {token_symbol}')
print(f'Age of the token address: {age}')
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28466587 # Replace with your desired starting block number
block_end = 28466640 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
Fix it
|
7ef9980660150817a1f25cfdf02aa206
|
{
"intermediate": 0.30789852142333984,
"beginner": 0.3956702649593353,
"expert": 0.2964312434196472
}
|
8,667
|
Use vanilla JavaScript and ES6 Class dynamic build multi-layers sidebar navigation, eg. three-layers,four-layers etc.
|
95f40a22a992f1ebf1cfff09e9e6d1a0
|
{
"intermediate": 0.328571617603302,
"beginner": 0.3875296115875244,
"expert": 0.28389880061149597
}
|
8,668
|
I have c# wpf project with this code:
// MyProject/Utils/Constants/ToolTips.cs
namespace MyProject.Constants
{
public static class ToolTips
{
public const string ToolTip1 = "ToolTip1";
// Add more tooltip constants here if needed
}
}
// MyProject/Views/Window.xaml
xmlns:c="clr-namespace:MyProject.Constants"
ToolTip="{x:Static c:ToolTips.ToolTip1}" // error!
But it gives me error when accessing ToolTip1, how can I do that correctly
|
ab005a5f030ccb22e4eeb13b44eb8667
|
{
"intermediate": 0.6284009218215942,
"beginner": 0.20962375402450562,
"expert": 0.16197529435157776
}
|
8,669
|
Write a code for ESP8266 that will open a webserver on the access point that will allow me to control LED connected to pin 4 using AJAX.
|
eb2e9714dcf70f3d98b21572d9cc7810
|
{
"intermediate": 0.6140366792678833,
"beginner": 0.09514311701059341,
"expert": 0.2908201813697815
}
|
8,670
|
write a C# code to break every process,loop,task running and start one task
|
4e550a9517e4a9f73448f284ef7587b8
|
{
"intermediate": 0.42851418256759644,
"beginner": 0.3879739046096802,
"expert": 0.1835118979215622
}
|
8,671
|
Implement a tracking algorithm (motpy tracking algorithms) to track
multiple objects in a video.
|
acd02ea9ec30c9ce683bfe05b72ae759
|
{
"intermediate": 0.10138039290904999,
"beginner": 0.057538751512765884,
"expert": 0.8410808444023132
}
|
8,672
|
i have a kotlin app, and a function which counts games in a database. however, when i put the value in an acitivity, it returns 0. fun countGames(): Int {
var gamesCount = 0
val COUNT_GAMES = (“SELECT COUNT(*) FROM " + TABLE_GAMES + " WHERE " + COLUMN_TYPE + " = 0”)
val DB = this.readableDatabase
val QUERY = DB.rawQuery(COUNT_GAMES, null)
while (QUERY.moveToNext()) {
gamesCount = Integer.parseInt(QUERY.getString(0))
}
QUERY.close()
DB.close()
return gamesCount
}
|
9c5a7de7e5eed6ef567de7e07b71dcd2
|
{
"intermediate": 0.4624195396900177,
"beginner": 0.35572341084480286,
"expert": 0.18185701966285706
}
|
8,673
|
Исправь ошибки в коде:
error C2065: вирусом: необъявленный идентификатор
error C2065: является: необъявленный идентификатор
error C2065: “Файл: необъявленный идентификатор
error C3873: "0x201c": этот символ недопустим как первый символ идентификатора
error C3873: "0x201d": этот символ недопустим как первый символ идентификатора
error C2065: my: необъявленный идентификатор
error C2065: to: необъявленный идентификатор
error C2568: <<: не удается разрешить перегрузку функции
#include
#include <fstream>
#include <dirent.h>
#include <string>
#include <vector>
#include <cstdio>
#include <iostream>
using namespace std;
bool isVirus(string fileName, string databaseFilePath) {
// Открываем файл и считываем его содержимое в буфер
ifstream file(fileName);
string buffer((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
// Получаем список вирусов из базы данных
ifstream databaseFile(databaseFilePath);
vector<string> virusList;
string line;
while (getline(databaseFile, line)) {
virusList.push_back(line);
}
// Сравниваем содержимое файла с базой данных вирусов
for (string virus : virusList) {
if (buffer == virus) {
return true;
}
}
return false;
}
bool deleteFile(string fileName) {
if (remove(fileName.c_str()) != 0) {
return false;
}
return true;
}
vector<string> getFilesInDirectory(string path) {
vector<string> files;
DIR* dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_REG) { // Только обычные файлы
files.push_back(ent->d_name);
}
}
closedir(dir);
}
return files;
}
void scanDirectory(string path, string databaseFilePath) {
vector<string> files = getFilesInDirectory(path);
for (string fileName : files) {
string fullFilePath = path + “ / ” + fileName;
if (isVirus(fullFilePath, databaseFilePath)) {
cout << “Файл " << fullFilePath << " является вирусом!” << endl;
// Предлагаем удалить файл
deleteFile(fullFilePath);
}
}
// Рекурсивный вызов для всех поддиректорий
DIR* dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_DIR && strcmp(ent->d_name, “.”) != 0 && strcmp(ent->d_name, “…”) != 0) { // Только директории, кроме . и …
string subDirPath = path + “ / ” + ent->d_name;
scanDirectory(subDirPath, databaseFilePath);
}
}
closedir(dir);
}
}
int main() {
// Путь к директории, которую нужно просканировать
string path = “ / path / to / my / directory”;
// Путь к файлу базы данных вирусов
string databaseFilePath = “ / path / to / my / database.txt”;
// Сканируем директорию на наличие вирусов
scanDirectory(path, databaseFilePath);
return 0;
}
|
649876cadc3528bd59672060f9bca26a
|
{
"intermediate": 0.34124991297721863,
"beginner": 0.5078699588775635,
"expert": 0.1508801132440567
}
|
8,674
|
Улучши код и функции.
алгоритм сканирования должны быть максимально эффективными и актуальными
#include <iostream>
#include <fstream>
#include <dirent.h>
#include <string>
#include <vector>
#include <cstdio>
using namespace std;
bool isVirus(string fileName, string databaseFilePath) {
// Открываем файл и считываем его содержимое в буфер
ifstream file(fileName);
string buffer((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
// Получаем список вирусов из базы данных
ifstream databaseFile(databaseFilePath);
vector<string> virusList;
string line;
while (getline(databaseFile, line)) {
virusList.push_back(line);
}
// Сравниваем содержимое файла с базой данных вирусов
for (string virus : virusList) {
if (buffer == virus) {
return true;
}
}
return false;
}
bool deleteFile(string fileName) {
if (remove(fileName.c_str()) != 0) {
return false;
}
return true;
}
vector<string> getFilesInDirectory(string path) {
vector<string> files;
DIR* dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_REG) { // Только обычные файлы
files.push_back(ent->d_name);
}
}
closedir(dir);
}
return files;
}
void scanDirectory(string path, string databaseFilePath) {
vector<string> files = getFilesInDirectory(path);
for (string fileName : files) {
string fullFilePath = path + " / " + fileName;
if (isVirus(fullFilePath, databaseFilePath)) {
cout << "Файл " << fullFilePath << " является вирусом!" << endl;
// Предлагаем удалить файл
deleteFile(fullFilePath);
}
}
// Рекурсивный вызов для всех поддиректорий
DIR* dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "…") != 0) { // Только директории, кроме . и …
string subDirPath = path + " / " + ent->d_name;
scanDirectory(subDirPath, databaseFilePath);
}
}
closedir(dir);
}
}
int main() {
// Путь к директории, которую нужно просканировать
string path = " / path / to / my / directory";
// Путь к файлу базы данных вирусов
string databaseFilePath = " / path / to / my / database.txt";
// Сканируем директорию на наличие вирусов
scanDirectory(path, databaseFilePath);
return 0;
}
|
b9a92608f473b82fca7e4ec366c8ac8c
|
{
"intermediate": 0.33819130063056946,
"beginner": 0.5609928965568542,
"expert": 0.10081584006547928
}
|
8,675
|
Улучши алгоритм сканирования должны быть максимально эффективными и актуальными.
#include <iostream>
#include <fstream>
#include <dirent.h>
#include <string>
#include <vector>
#include <cstdio>
using namespace std;
bool isVirus(string fileName, string databaseFilePath) {
// Открываем файл и считываем его содержимое в буфер
ifstream file(fileName);
string buffer((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
// Получаем список вирусов из базы данных
ifstream databaseFile(databaseFilePath);
vector<string> virusList;
string line;
while (getline(databaseFile, line)) {
virusList.push_back(line);
}
// Сравниваем содержимое файла с базой данных вирусов
for (string virus : virusList) {
if (buffer == virus) {
return true;
}
}
return false;
}
bool deleteFile(string fileName) {
if (remove(fileName.c_str()) != 0) {
return false;
}
return true;
}
vector<string> getFilesInDirectory(string path) {
vector<string> files;
DIR* dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_REG) { // Только обычные файлы
files.push_back(ent->d_name);
}
}
closedir(dir);
}
return files;
}
void scanDirectory(string path, string databaseFilePath) {
vector<string> files = getFilesInDirectory(path);
for (string fileName : files) {
string fullFilePath = path + " / " + fileName;
if (isVirus(fullFilePath, databaseFilePath)) {
cout << "Файл " << fullFilePath << " является вирусом!" << endl;
// Предлагаем удалить файл
deleteFile(fullFilePath);
}
}
// Рекурсивный вызов для всех поддиректорий
DIR* dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "…") != 0) { // Только директории, кроме . и …
string subDirPath = path + " / " + ent->d_name;
scanDirectory(subDirPath, databaseFilePath);
}
}
closedir(dir);
}
}
int main() {
// Путь к директории, которую нужно просканировать
string path = " / path / to / my / directory";
// Путь к файлу базы данных вирусов
string databaseFilePath = " / path / to / my / database.txt";
// Сканируем директорию на наличие вирусов
scanDirectory(path, databaseFilePath);
return 0;
}
|
577c2373430143ab302f774200081edc
|
{
"intermediate": 0.3298338055610657,
"beginner": 0.39979538321495056,
"expert": 0.27037087082862854
}
|
8,676
|
Traceback (most recent call last):
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\pythonProject1\main.py", line 83, in main
await display_transactions(block_start, block_end)
File "C:\Users\AshotxXx\PycharmProjects\pythonProject1\main.py", line 76, in display_transactions
await asyncio.gather(*tasks)
File "C:\Users\AshotxXx\PycharmProjects\pythonProject1\main.py", line 61, in process_block
transactions = await get_external_transactions(block_number)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\pythonProject1\main.py", line 20, in get_external_transactions
async with semaphore:
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\locks.py", line 15, in __aenter__
await self.acquire()
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\locks.py", line 387, in acquire
await fut
asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\pythonProject1\main.py", line 90, in <module>
asyncio.run(main())
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 123, in run
raise KeyboardInterrupt()
KeyboardInterrupt
Process finished with exit code -1073741510 (0xC000013A: interrupted by Ctrl+C)
Fix it all
|
d79f646dd94146a78b48583fd8be3f49
|
{
"intermediate": 0.35282760858535767,
"beginner": 0.3421136438846588,
"expert": 0.3050587475299835
}
|
8,677
|
Проверь код на ошибки dir.
Так же измени что бы база данных вируса считывалась не txt а cav.
#include <iostream>
#include <fstream>
#include <dirent.h>
#include <string>
#include <vector>
#include <cstdio>
#include <thread>
#include <chrono>
#include <openssl/md5.h>
#include <map>
using namespace std;
bool isVirus(string fileName, map<string, string>& virusDatabase) {
// Открываем файл и считываем его содержимое в буфер
ifstream file(fileName, ios::binary);
string buffer((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
// Вычисляем хеш-сумму файла
unsigned char digest[MD5_DIGEST_LENGTH];
MD5((unsigned char*)buffer.c_str(), buffer.size(), digest);
char md5sum[33];
for (int i = 0; i < 16; i++)
sprintf(&md5sum[i2], " % 02x", (unsigned int)digest[i]);
// Сравниваем хеш-сумму с базой данных вирусов
if (virusDatabase.count(md5sum) == 1) {
return true;
}
return false;
}
bool deleteFile(string fileName) {
if (remove(fileName.c_str()) != 0) {
return false;
}
return true;
}
vector<string> getFilesInDirectory(string path) {
vector<string> files;
DIR dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_REG) { // Только обычные файлы
files.push_back(ent->d_name);
}
}
closedir(dir);
}
return files;
}
void scanDirectory(string path, map<string, string>& virusDatabase, bool deleteVirus) {
vector<string> files = getFilesInDirectory(path);
for (string fileName : files) {
string fullFilePath = path + " / " + fileName;
if (isVirus(fullFilePath, virusDatabase)) {
cout << "Файл " << fullFilePath << " является вирусом!" << endl;
// Предлагаем удалить файл
if (deleteVirus)
deleteFile(fullFilePath);
}
}
// Рекурсивный вызов для всех поддиректорий
DIR* dir;
struct dirent* ent;
if ((dir = opendir(path.c_str())) != NULL) {
while ((ent = readdir(dir)) != NULL) {
if (ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "…") != 0) { // Только директории, кроме . и …
string subDirPath = path + " / " + ent->d_name;
scanDirectory(subDirPath, virusDatabase, deleteVirus);
}
}
closedir(dir);
}
}
void scanDirectoryThread(string path, map<string, string>& virusDatabase, bool deleteVirus) {
cout << "Начало сканирования директории: " << path << endl;
auto start = chrono::high_resolution_clock::now();
scanDirectory(path, virusDatabase, deleteVirus);
auto end = chrono::high_resolution_clock::now();
double elapsedTimeInSeconds = chrono::duration<double>(end - start).count();
cout << "Окончание сканирования директории: " << path << endl;
cout << "Время выполнения : " << elapsedTimeInSeconds << " секунд" << endl;
}
void loadVirusDatabase(string databaseFilePath, map<string, string>& virusDatabase) {
// Получаем список вирусов из базы данных
ifstream databaseFile(databaseFilePath);
string line;
while (getline(databaseFile, line)) {
// Вычисляем хеш-сумму вируса
unsigned char digest[MD5_DIGEST_LENGTH];
MD5((unsigned char*)line.c_str(), line.length(), digest);
char md5sum[33];
for (int i = 0; i < 16; i++)
sprintf(&md5sum[i * 2], " % 02x", (unsigned int)digest[i]);
virusDatabase.insert(pair<string, string>(md5sum, line));
}
}
int main() {
// Путь к директории, которую нужно просканировать
string path = " / path / to / my / directory";
// Путь к файлу базы данных вирусов
string databaseFilePath = " / path / to / my / database.txt";
// Загружаем базу данных вирусов
map<string, string> virusDatabase;
loadVirusDatabase(databaseFilePath, virusDatabase);
// По умолчанию антивирус включен
bool antivirusEnabled = true;
// Меню программы
while (true) {
cout << "1.Сканирование директории" << endl;
cout << "2.Включение / выключение антивируса" << endl;
cout << "3.Выход" << endl;
int choice;
cin >> choice;
switch (choice) {
case 1:
if (antivirusEnabled) {
// Сканируем директорию на наличие вирусов с помощью нескольких потоков
const int numThreads = 4;
bool deleteVirus = true;
thread threads[numThreads];
for (int i = 0; i < numThreads; i++) {
threads[i] = thread(scanDirectoryThread, path, virusDatabase, deleteVirus);
}
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
}
else {
cout << "Антивирус выключен!Включите антивирус, чтобы выполнить сканирование директории." << endl;
}
break;
case 2:
antivirusEnabled = !antivirusEnabled;
if (antivirusEnabled) {
cout << "Антивирус включен!" << endl;
}
else {
cout << "Антивирус выключен!" << endl;
}
break;
case 3:
return 0;
default:
cout << "Неправильный ввод!" << endl;
}
}
return 0;
}
|
3004e56e846870828f79ae425acaca52
|
{
"intermediate": 0.41277870535850525,
"beginner": 0.45700299739837646,
"expert": 0.13021831214427948
}
|
8,678
|
Hello There. What model are you?
|
8de60f60588fb4a6449cb2bf1129ea28
|
{
"intermediate": 0.2409294843673706,
"beginner": 0.18210403621196747,
"expert": 0.576966404914856
}
|
8,679
|
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int yylex();
void yyerror(const char* s);
%}
%union {
int num;
char* str;
}
%token <num> NUMBER
%token <str> IDENTIFIER STRING_LITERAL
%token IF ELSE FOR ADD SUB MUL DIV MOD ASSIGN EQ LT GT LE GE NEQ AND OR NOT SEMICOLON LPAREN RPAREN LBRACE RBRACE PKG MAIN IMPORT FUNC VAR PRINTLN PRINT INT_TYPE
%type <num> expression arithmetic_expr term factor relational_expr
%type <str> program package_declaration import_declaration func_declaration statements statement var_declaration print_statement assignment_statement if_statement for_loop for_initializer for_update data_type
%nonassoc EQ LT GT LE GE NEQ
%left ADD SUB
%left MUL DIV MOD
%left AND
%left OR
%nonassoc NOT
%nonassoc UNARY
%%
program:
package_declaration import_declaration func_declaration statements
;
package_declaration:
PKG MAIN SEMICOLON{}
;
import_declaration:
IMPORT STRING_LITERAL SEMICOLON{}
;
func_declaration:
FUNC MAIN LPAREN RPAREN LBRACE statements RBRACE{}
;
statements:
statement
| statements statement
;
statement:
var_declaration SEMICOLON {
printf("variable declaration and assignment\n");
}
| print_statement SEMICOLON
| assignment_statement SEMICOLON
| if_statement
| for_loop
;
if_statement:
IF LPAREN expression RPAREN LBRACE statements RBRACE {
printf("if statement\n");
}
| IF LPAREN expression RPAREN LBRACE statements RBRACE ELSE LBRACE statements RBRACE {
printf("if-else statement\n");
}
;
for_loop:
FOR LPAREN for_initializer SEMICOLON expression SEMICOLON for_update RPAREN LBRACE statements RBRACE{}
;
for_initializer:
IDENTIFIER ASSIGN expression
;
for_update:
IDENTIFIER ASSIGN expression
;
var_declaration:
VAR IDENTIFIER data_type ASSIGN expression {
printf("var declaration: %s\n", $2);
}
;
print_statement:
PRINTLN LPAREN expression RPAREN {
printf("println statement\n");
}
| PRINT LPAREN expression RPAREN {
printf("print statement\n");
}
;
assignment_statement:
IDENTIFIER ASSIGN expression {
printf("%s = %d\n", $1, $3);
}
;
data_type:
INT_TYPE{}
;
expression:
relational_expr
;
arithmetic_expr:
arithmetic_expr ADD term {
$$ = $1 + $3;
}
| arithmetic_expr SUB term {
$$ = $1 - $3;
}
| term {
$$ = $1;
}
;
term:
term MUL factor {
$$ = $1 * $3;
}
| term DIV factor {
$$ = $1 / $3;
}
| term MOD factor {
$$ = $1 % $3;
}
| factor {
$$ = $1;
}
;
factor:
NUMBER {
$$ = $1;
}
| IDENTIFIER {
printf("identifier: %s\n", $1);
}
| LPAREN expression RPAREN {
$$ = $2;
}
| SUB factor UNARY {
$$ = -$2;
}
| ADD factor UNARY {
$$ = $2;
}
| NOT factor UNARY {
$$ = !$2;
}
| IDENTIFIER LPAREN RPAREN {
printf("function call: %s\n", $1);
}
| IDENTIFIER LPAREN expression RPAREN {
printf("function call with argument: %s\n", $1);
}
| IDENTIFIER LPAREN expression ',' expression RPAREN {
printf("function call with multiple arguments: %s\n", $1);
}
;
relational_expr:
expression EQ expression {
$$ = $1 == $3;
}
| expression LT expression {
$$ = $1 < $3;
}
| expression GT expression {
$$ = $1 > $3;
}
| expression LE expression {
$$ = $1 <= $3;
}
| expression GE expression {
$$ = $1 >= $3;
}
| expression NEQ expression {
$$ = $1 != $3;
}
| expression AND expression {
$$ = $1 && $3;
}
| expression OR expression {
$$ = $1 || $3;
}
;
%%
void yyerror(const char* s) {
fprintf(stderr, "%s\n", s);
}
int main() {
yyparse();
return 0;
}
gptparser.y: warning: 20 nonterminals useless in grammar [-Wother]
gptparser.y: warning: 47 rules useless in grammar [-Wother]
gptparser.y:30.1-7: error: start symbol program does not derive any sentence
30 | program:
|
8f2b6e809e722fe8374ec148e622d4c8
|
{
"intermediate": 0.20764784514904022,
"beginner": 0.6795367002487183,
"expert": 0.11281539499759674
}
|
8,681
|
напиши пример функций которая будет вызываться при выборе сотрудника изменять selectedCity <label>Кому</label>
<ng-container *ngIf="users && selectedUser">
<select id="employee" class="chosen-select" placeholder="Выбери сотрудника" [(ngModel)]="selectedUser.Id">
<option *ngFor="let u of users" [value]="u.Id">{{u.Title}}</option>
</select>
<span *ngIf="showErrors &&(!selectedUser || selectedUser.Id == 0)" style="color:#FC3E3E;">Не выбран сотрудник</span>
</ng-container>
</div>
<div class="form-item">
<label>Город</label>
<ng-container *ngIf="cityItems && selectedCity">
<select id="city" class="chosen-city-select" placeholder="Выбери город" [(ngModel)]="selectedCity.Id">
<option [ngValue]="selectedCity.Title" disabled>Город</option>
<option *ngFor="let c of cityItems" [value]="c.Id">{{c.Title}}</option>
</select>
<span *ngIf="showErrors &&(!selectedCity || selectedCity.Id == 0)" style="color:#FC3E3E;">Не выбран город</span>
</ng-container>
|
1f6981430bda7a8547586bcc2848429e
|
{
"intermediate": 0.3481835722923279,
"beginner": 0.3676401972770691,
"expert": 0.284176230430603
}
|
8,682
|
error: failed to run custom build command for `libspa-sys v0.6.0`
Caused by:
process didn't exit successfully: `/home/void/Documents/Coding/fractal/target/release/build/libspa-sys-6d21663c0f02e200/build-script-build` (exit status: 101)
--- stdout
cargo:rerun-if-env-changed=LIBPIPEWIRE_0.3_NO_PKG_CONFIG
cargo:rerun-if-env-changed=PKG_CONFIG_x86_64-unknown-openbsd
cargo:rerun-if-env-changed=PKG_CONFIG_x86_64_unknown_openbsd
cargo:rerun-if-env-changed=HOST_PKG_CONFIG
cargo:rerun-if-env-changed=PKG_CONFIG
cargo:rerun-if-env-changed=PKG_CONFIG_PATH_x86_64-unknown-openbsd
cargo:rerun-if-env-changed=PKG_CONFIG_PATH_x86_64_unknown_openbsd
cargo:rerun-if-env-changed=HOST_PKG_CONFIG_PATH
cargo:rerun-if-env-changed=PKG_CONFIG_PATH
cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR_x86_64-unknown-openbsd
cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR_x86_64_unknown_openbsd
cargo:rerun-if-env-changed=HOST_PKG_CONFIG_LIBDIR
cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR
cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64-unknown-openbsd
cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64_unknown_openbsd
cargo:rerun-if-env-changed=HOST_PKG_CONFIG_SYSROOT_DIR
cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR
--- stderr
thread 'main' panicked at 'Cannot find libraries: PkgConfig(`PKG_CONFIG_ALLOW_SYSTEM_CFLAGS="1" "pkg-config" "--libs" "--cflags" "libpipewire-0.3" "libpipewire-0.3 >= 0.3"` did not exit successfully: exit status: 1
error: could not find system library 'libpipewire-0.3' required by the 'libspa-sys' crate
--- stderr
Package libpipewire-0.3 was not found in the pkg-config search path
)', /home/void/.cargo/registry/src/github.com-1ecc6299db9ec823/libspa-sys-0.6.0/build.rs:10:10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
warning: build failed, waiting for other jobs to finish...
|
da0ae56bc4e023b22a52a3b3c8977d68
|
{
"intermediate": 0.5387021899223328,
"beginner": 0.20329031348228455,
"expert": 0.2580074369907379
}
|
8,683
|
openbsd finf pkg
|
24f7ec204e0f07061e5b6e9a875564f0
|
{
"intermediate": 0.3974701166152954,
"beginner": 0.237322136759758,
"expert": 0.3652077317237854
}
|
8,684
|
нужна проверка на значение
const branch = this.cityItems.filter((c) => c.Code == this._cityUtils.getCityCode(workInfo.AddressWorkplace))[0];
если не опредленно то 1
|
2ee711c4ca03cb87a6b485657756f671
|
{
"intermediate": 0.33064958453178406,
"beginner": 0.3728916347026825,
"expert": 0.29645881056785583
}
|
8,685
|
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
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 = 0.27
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 10
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC'))
frame = frame.iloc[:60,:6]
frame.columns = ['Time','Open','High','Low','Close','Volume']
frame = frame.set_index('Time')
today = dt.date.today()
frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S")
frame = frame.astype(float)
return frame
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 = getminutedata('BTCUSDT', '5m', '44640')
signal = ["" for i in range(len(df))] # initialize signal as a list of empty strings
for i in range(1, len(df)):
df_temp = df[i-1:i+1]
signal[i] = signal_generator(df_temp)
df["signal"] = signal
def order_execution(symbol, signal, max_trade_quantity_percentage):
max_trade_quantity_percentage = 10
buy = signal == "buy"
sell = signal == "sell"
signal = buy or sell
symbol = 'BTCUSDT'
account_balance = client.futures_account_balance()
usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
POSITION_SIDE_SHORT = SIDE_SELL
POSITION_SIDE_LONG = SIDE_BUY
long_position = POSITION_SIDE_LONG
short_position = POSITION_SIDE_SHORT
symbol = 'BTCUSDT'
positions = client.futures_position_information(symbol=symbol)
long_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'LONG'), None)
if long_position:
# Close long position if signal is opposite
if signal == "sell":
order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
print(f"Closed long position with order ID {order['orderId']}")
time.sleep(1)
else:
if long_position is not None:
order_quantity = min(max_trade_quantity, abs(float(long_position['positionAmt'])))
else:
print("No long position found")
order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_SHORT,
leverage=leverage
)
print(f"Placed short order with order ID {order['orderId']} and quantity {order_quantity})")
time.sleep(1)
# Set stop loss and take profit orders
stop_loss_price = order['avgPrice'] * (1 + STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order['avgPrice'] * (1 + TAKE_PROFIT_PERCENTAGE / 100)
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_SHORT
)
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_SHORT
)
print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}")
time.sleep(1)
short_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'SHORT'), None)
if short_position:
# Close short position if signal is opposite
if signal == "buy":
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
print(f"Closed short position with order ID {order['orderId']}")
time.sleep(1)
else:
order_quantity = min(max_trade_quantity, float(short_position['maxNotionalValue']) / leverage)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_LONG,
leverage=leverage
)
print(f"Placed long order with order ID {order['orderId']} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
stop_loss_price = order['avgPrice'] * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order['avgPrice'] * (1 - TAKE_PROFIT_PERCENTAGE / 100)
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_LONG
)
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=POSITION_SIDE_LONG
)
print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}")
time.sleep(1)
while True:
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
current_signal = signal_generator(df)
print(f"The signal time is: {current_time} :{current_signal}")
if current_signal:
order_execution(symbol, current_signal,max_trade_quantity_percentage)
time.sleep(1) # Add a delay of 1 second But I getting ERROR: The signal time is: 2023-05-27 21:41:16 :buy
No long position found
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 213, in <module>
order_execution(symbol, current_signal,max_trade_quantity_percentage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 122, in order_execution
quantity=order_quantity,
^^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'order_quantity' where it is not associated with a value
|
67c73a688c3628dfb0bbdc43df5960f0
|
{
"intermediate": 0.33428263664245605,
"beginner": 0.4321554899215698,
"expert": 0.2335619032382965
}
|
8,686
|
what are the trending news of today 05-27-2023 ?
|
592554060292ba241b26464c0740fb6c
|
{
"intermediate": 0.3091232180595398,
"beginner": 0.31444862484931946,
"expert": 0.37642818689346313
}
|
8,687
|
openbsd
subprojects/wireplumber/meson.build:55:0: ERROR: Dependency "intl" not found, tried builtin and system
|
3880a7354d557de7260d7e157f988e98
|
{
"intermediate": 0.5356301069259644,
"beginner": 0.26024115085601807,
"expert": 0.20412872731685638
}
|
8,688
|
lisp cons two lists
|
9b3b00cb21114f7d16d9753d22083f9a
|
{
"intermediate": 0.2403465360403061,
"beginner": 0.5751309394836426,
"expert": 0.18452246487140656
}
|
8,689
|
في تطبيق اندرويد ستوديو هل يمكنك تعديل شكل هذه الواجهة ( تعديل استايل التطبيق ) ليكون اكثر اناقة وجمالا للمستخدم النهائي هذا هو الكود
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:gl="http://schemas.android.com/apk/res-auto"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".NewScreen.NewFirstScreen"
tools:showIn="@layout/app_bar_main_new"
style="@style/parent.contentLayout"
android:background="#00000000">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/border_file"
android:gravity="center">
<Button
android:id="@+id/ChatBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="5dp"
android:background="@drawable/snedicon"
android:textColor="@color/white" />
<Space
android:layout_width="60dp"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/HistoryButton"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginEnd="5dp"
android:background="@drawable/historyicon"
android:textColor="@color/colorPrimaryDark" />
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="@+id/FirstAd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:adSize="LARGE_BANNER"
app:adUnitId="ca-app-pub-4549371353711345/3368986480" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.hbb20.CountryCodePicker
android:id="@+id/countryCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_season_tab"
android:ems="10"
android:padding="12dp"
android:textColor="#088800"
android:textColorHint="#088800"
android:textSize="13sp"
app:ccpDialog_showTitle="false"
app:ccp_defaultPhoneCode="20"
app:ccp_textSize="16sp" />
<EditText
android:id="@+id/et_title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginStart="5dp"
android:autofillHints=""
android:background="@drawable/bg_season_tab"
android:drawableStart="@drawable/ic_mobile"
android:drawablePadding="10dp"
android:hint="@string/mobile_number"
android:inputType="number"
android:padding="15dp"
android:singleLine="true"
android:textColor="#088800"
android:textColorHighlight="#088800"
android:textColorHint="#088800"
android:textColorLink="#088800"
android:textSize="15sp" />
<ImageView
android:id="@+id/paste_btn"
android:layout_gravity="center"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginStart="5dp"
android:background="@drawable/paste"
android:contentDescription="@string/phone" />
</LinearLayout>
<EditText
android:id="@+id/et_note"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="20dp"
android:layout_marginRight="5dp"
android:autoLink="web|email"
android:autofillHints=""
android:ems="10"
android:gravity="center"
android:hint="@string/EnterYourMessage"
android:imeOptions="flagNoExtractUi"
android:inputType="textCapSentences|textMultiLine"
android:linksClickable="true"
android:paddingStart="8dp"
android:paddingEnd="8dp"
android:textCursorDrawable="@null"
android:textSize="18sp"
android:textStyle="bold"
android:background="@drawable/bg_season_tab"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/title"
tools:ignore="TouchTargetSizeCheck" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:background="@drawable/border_file"
android:gravity="center">
<Button
android:id="@+id/ShareMgsBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="5dp"
android:background="@drawable/shareico"
android:textColor="@color/white" />
<Space
android:layout_width="60dp"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/sendbtn"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginEnd="5dp"
android:background="@drawable/send"/>
<Space
android:layout_width="60dp"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/sharefiles"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginEnd="5dp"
android:background="@drawable/sharelocation"/>
</LinearLayout>
<com.google.android.gms.ads.AdView
android:id="@+id/SecondAd"
android:layout_marginBottom="25dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
app:adSize="BANNER"
app:adUnitId="ca-app-pub-4549371353711345/3368986480" />
</LinearLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
مع العلم ان الالوان الرئيسية هي <color name="colorPrimary">#289A5B</color>
<color name="colorPrimaryDark">#046E00</color>
<color name="colorAccent">#267C01</color>هل يمكنك تعديله وكتابته لي بعد التعديل ؟
|
59143bbf8097581bcc55f8edd66e2eec
|
{
"intermediate": 0.21379436552524567,
"beginner": 0.550936222076416,
"expert": 0.23526941239833832
}
|
8,690
|
in kotlin, how do i check if 24 hours have passed between two values of type LocalDate?
|
2838d6244073ce54746cccf96b48ee57
|
{
"intermediate": 0.5880350470542908,
"beginner": 0.08466432988643646,
"expert": 0.3273006081581116
}
|
8,691
|
# Crear un diagrama de cajas y bigotes
sns.boxplot(data=Vinos)
plt.xlabel(["Acidez_fija", "Azucar_residual","pH"])
plt.ylabel("Valores")
plt.title("Diagrama de Cajas y Bigotes de Acidez Fija, Azúcar Residual y pH")
plt.setp(ax.get_xticklabels(), rotation="45", ha="right")
name 'ax' is not defined
|
2fdd349471931d47d123f642e0ebe4ab
|
{
"intermediate": 0.3508531451225281,
"beginner": 0.2721751928329468,
"expert": 0.37697169184684753
}
|
8,692
|
Can you fix this code and write it again:
|
60342e303a76094c566764d0e28852b1
|
{
"intermediate": 0.2882290482521057,
"beginner": 0.36724767088890076,
"expert": 0.34452328085899353
}
|
8,693
|
a zip program that inflate data from stdin to stdout
|
8d94c7c54956518b5911ba76c79f5abf
|
{
"intermediate": 0.41214439272880554,
"beginner": 0.2118983268737793,
"expert": 0.37595728039741516
}
|
8,694
|
@sanz#4384 Explain in detail, step by step at an EXTREMELY LOW LEVEL exactly how I would create a social network consisting of only AI. How it would work is a random number is picked from 1-10 every minute, and if the number is 3, a new account is created, each with their own AI generated handle, name, bio, personality and backstory (which can be viewed by clicking 'Advanced' on a profile). Real users can also create up to 5 AI accounts where they only specify a handle and the basic description of who the AI is - the rest is done by AI (see previous). This restriction is tracked via MAC address. Like previously, for each account every minute a random number is generated, this find between 1 and 100, and if the number is 18 the AI can write a post. In addition, a random number is generated from 1-10, where if the answer is 3 the AI personality is sent a copy of the the last 200 posts on the platform, and a list of its followers, and then decides whether it wants to interact with any of the posts or accounrs, whether that is by liking, commenting, reposting, unfollowing, etc OR it may choose to ignore the posts and perform a different action, e.g. changing its account info, applying for verification, etc). Whenever an AI gets a reply on a post a random number between 1-5 is generated and if the number is 3 they are notified and given the option to reply to the reply. This is essentially how it works. In terms of the design, it should be modern, slick and pleasing to navigate - note that there should be a full 'Trending' system (updated every minute with the most popular words, phrases or hashtags in the last hour), and that there are sorting options (Live, Most Popular, etc) - but of course the user cant interact with the posts themselves. There should also be other interesting systems, like a full verification/checkmark system (whereby AI accounts can apply for verification and one central official AI can deny or approve requests given a copy of the stats of the account that applied), as well as other systems for realism. Note all the AI aspects should be powered by Anthropic Claude using its APIs - docs will be pasted below. Include full code snippets in your output. Note that you should not leave things up to me in your output, and you should cover everything. NOTE THAT I HAVE NO PHYSICAL INFRASTRUCTURE - you should host EVERYTHING using platforms like Vercel and Heroku. Take this into account in your output, and make sure **ALL THE FUNCTIONALITY AND ASPECTS OUTLINED HERE WOULD BE FULLY IMPLEMENTED IF I WERE TO FOLLOW YOUR INSTRUCTIONS**. Make sure to cover EVERY SINGLE step. DO NOT skip over anything or leave things for me to figure out - for example, instead of just telling me to create a file without any further info, you give me the full contents of the file. So, don't do skip content or brush over things with 'Your x here', just include it. I have not much technical knowledge so you must walk me through each individual thing. Be as specific as possible.
Claude docs (pasted from page):
anthropic
/ playground
dev
development
Methods
complete
complete()
GET POST https://anthropic.api.stdlib.com/playground@dev/complete/
Pricing
Free
Auth Rate Limit
no rate limit
Unauth Rate Limit
no rate limit
Description
Sends a prompt to Claude for completion.
Parameters
prompt
REQUIRED
string
The prompt you want Claude to complete
model
REQUIRED
string
Choose an available option...
As we improve Claude, we develop new versions of it that you can query. This controls which version of Claude answers your request.
max_tokens_to_sample
OPTIONAL
integer
16
16
A maximum number of tokens to generate before stopping.
stop_sequences
OPTIONAL
array of string
Human:
Human:
Add a new array item
A list of strings upon which to stop generating. You probably want `["\n\nHuman:"]`, as that's the cue for the next turn in the dialog agent.
temperature
OPTIONAL
float
1
1
Amount of randomness injected into the response. Ranges from 0 to 1. Use temp closer to 0 for analytical / multiple choice, and temp closer to 1 for creative and generative tasks.
top_k
OPTIONAL
integer
Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. Defaults to -1, which disables it.
top_p
OPTIONAL
float
Does nucleus sampling, in which we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by top_p. Defaults to -1, which disables it. Note that you should either alter temperature or top_p, but not both.
Streams
When at least one stream is enabled, this API will respond with content-type text/event-stream and stream events to handlers set in the _stream parameter.
response
OPTIONAL
stream
When provided, streams the response as it gets populated
*
OPTIONAL
stream
Default handler for all streams
Node.js
Python
read only
1234567891011121314
// Using Node.js 14.x +
// use "lib" package from npm
const lib = require('lib')({token: null /* link an account to create an auth token */});
// make API request
let result = await lib.anthropic.playground['@dev'].complete({
prompt: null, // required
model: null, // required
max_tokens_to_sample: 16,
stop_sequences: [
`\n\nHuman:`
],
temperature: 1
});
// Using Node.js 14.x +// use "lib" package from npmconst lib = require('lib')({token: null /* link an account to create an auth token */});// make API requestlet result = await lib.anthropic.playground['@dev'].complete({··prompt: null, // required··model: null, // required··max_tokens_to_sample: 16,··stop_sequences: [····`\n\nHuman:`··],··temperature: 1});
xWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
Response Schema
response
object
completion
string
The resulting completion up to and excluding the stop sequences
stop_reason
string
The reason we stopped sampling, either stop_sequence if we reached one of your provided stop_sequences, or max_tokens if we exceeded max_tokens_to_sample.
stop
string
If the stop_reason is stop_sequence, this contains the actual stop sequence (of the stop_sequences list passed-in) that was seen
truncated
boolean
exception
any
log_id
string
model
string
Sample Response
read only
123456789
{
"completion": "sample_string",
"stop_reason": "sample_string",
"stop": "sample_string",
"truncated": true,
"exception": null,
"log_id": "sample_string",
"model": "sample_string"
}
{{··"completion": "sample_string",··"stop_reason": "sample_string",··"stop": "sample_string",··"truncated": true,··"exception": null,··"log_id": "sample_string",··"model": "sample_string"}}
xWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW
|
2b2a4ac7de8b242911535b18789bf4aa
|
{
"intermediate": 0.3742692172527313,
"beginner": 0.38102656602859497,
"expert": 0.24470430612564087
}
|
8,695
|
I need a vba code that will check column A of sheet 'Events' for a date that is 7 days before today.
If a date is found, I want the row of column A, B, C and D of the same row where the match is found, displayed in a pop up with each colum value on a seperate line.
|
715ea26c0e601b8b5e261c2e776e7549
|
{
"intermediate": 0.6205412745475769,
"beginner": 0.14298777282238007,
"expert": 0.23647096753120422
}
|
8,696
|
What about this error in JypterNoteBook
ImportError: cannot import name 'DetectionList' from 'motpy' (C:\Users\AAT\anaconda3\lib\site-packages\motpy\__init__.py)
|
3a7bbdebc2a705fe8b1a3826d60a3b8a
|
{
"intermediate": 0.7426086664199829,
"beginner": 0.1099362000823021,
"expert": 0.1474551558494568
}
|
8,697
|
Replace all of “ to " : def replace_words(string, words_to_replace, new_word):
for word in words_to_replace:
string = string.replace(word, new_word)
return string
string = “The quick brown fox jumps over the lazy dog”
words_lists = [[“quick”, “fox”], [“lazy”, “dog”], [“brown”, “jumps”]]
new_word = “cat”
all_words = []
for words_list in words_lists:
all_words += words_list
string = replace_words(string, all_words, new_word)
print(string)
|
b538d5b784921d91fe4ce68ddf966d71
|
{
"intermediate": 0.33824822306632996,
"beginner": 0.3338095545768738,
"expert": 0.32794225215911865
}
|
8,698
|
a zig program that inflate data from stdin to stdout
|
d1219400398850f466c8c3b7ec5a2739
|
{
"intermediate": 0.32973113656044006,
"beginner": 0.19514870643615723,
"expert": 0.4751201570034027
}
|
8,699
|
import numpy as np
import gym
from gym import spaces
import matplotlib.pyplot as plt
%matplotlib inline
class Snake_game(gym.Env):
"""
Custom Environment for Stable Baseline 3 for the classic Snake
"""
metadata = {'render.modes': ['console','rgb_array']}
#Direction constants
n_actions = 3 #3 possible steps each turn
LEFT = 0
STRAIGHT = 1
RIGHT = 2
#Grid label constants
EMPTY = 0
SNAKE = 1
WALL = 2
FOOD = 3
#Rewards
#REWARD_PER_STEP = 0 # reward for every step taken, gets into infinite loops if >0
#Define Max steps to avoid infinite loops
REWARD_WALL_HIT = -20 #should be lower than -REWARD_PER_STEP_TOWARDS_FOOD to avoid hitting wall intentionally
REWARD_PER_STEP_TOWARDS_FOOD = 1 #give reward for moving towards food and penalty for moving away
REWARD_PER_FOOD = 50
MAX_STEPS_AFTER_FOOD = 200 #stop if we go too long without food to avoid infinite loops
def __init__(self, grid_size=12):
super(Snake_game, self).__init__()
#Steps so far
self.stepnum = 0; self.last_food_step=0
# Size of the 2D grid (including walls)
self.grid_size = grid_size
# Initialize the snake
self.snake_coordinates = [ (1,1), (2,1) ] #Start in lower left corner
#Init the grid
self.grid = np.zeros( (self.grid_size, self.grid_size) ,dtype=np.uint8) + self.EMPTY
self.grid[0,:] = self.WALL; self.grid[:,0] = self.WALL; #wall at the egdes
self.grid[int(grid_size/2),3:(grid_size-3)] = self.WALL; #inner wall to make the game harder
self.grid[4:(grid_size-4),int(grid_size/2-1)] = self.WALL; #inner wall to make the game harder
#self.grid[int(grid_size/2),2:(grid_size-2)] = self.WALL; #inner wall to make the game harder
self.grid[self.grid_size-1,:] = self.WALL; self.grid[:,self.grid_size-1] = self.WALL
for coord in self.snake_coordinates:
self.grid[ coord ] = self.SNAKE #put snake on grid
self.grid[3,3] = self.FOOD #Start in upper right corner
#Init distance to food
self.head_dist_to_food = self.grid_distance(self.snake_coordinates[-1],np.argwhere(self.grid==self.FOOD)[0] )
#Store init values
self.init_grid = self.grid.copy()
self.init_snake_coordinates = self.snake_coordinates.copy()
# The action space
self.action_space = spaces.Discrete(self.n_actions)
# The observation space, "position" is the coordinates of the head; "direction" is which way the sanke is heading, "grid" contains the full grid info
self.observation_space = gym.spaces.Dict(
spaces={
"position": gym.spaces.Box(low=0, high=(self.grid_size-1), shape=(2,), dtype=np.int32),
"direction": gym.spaces.Box(low=-1, high=1, shape=(2,), dtype=np.int32),
"grid": gym.spaces.Box(low = 0, high = 3, shape = (self.grid_size, self.grid_size), dtype=np.uint8),
})
def grid_distance(self,pos1,pos2):
return np.linalg.norm(np.array(pos1,dtype=np.float32)-np.array(pos2,dtype=np.float32))
def reset(self):
# Reset to initial positions
self.stepnum = 0; self.last_food_step=0
self.grid = self.init_grid.copy()
self.snake_coordinates = self.init_snake_coordinates.copy()
#Init distance to food
self.head_dist_to_food = self.grid_distance(self.snake_coordinates[-1],np.argwhere(self.grid==self.FOOD)[0] )
return self._get_obs()
def _get_obs(self):
direction = np.array(self.snake_coordinates[-1]) - np.array(self.snake_coordinates[-2])
#return observation in the format of self.observation_space
return {"position": np.array(self.snake_coordinates[-1],dtype=np.int32),
"direction" : direction.astype(np.int32),
"grid": self.grid}
def step(self, action):
#Get direction for snake
direction = np.array(self.snake_coordinates[-1]) - np.array(self.snake_coordinates[-2])
if action == self.STRAIGHT:
step = direction #step in the firection the snake faces
elif action == self.RIGHT:
step = np.array( [direction[1], -direction[0]] ) #turn right
elif action == self.LEFT:
step = np.array( [-direction[1], direction[0]] ) #turn left
else:
raise ValueError("Action=%d is not part of the action space"%(action))
#New head coordinate
new_coord = (np.array(self.snake_coordinates[-1]) + step).astype(np.int32)
#grow snake
self.snake_coordinates.append( (new_coord[0],new_coord[1]) ) #convert to tuple so we can use it to index
#Check what is at the new position
new_pos = self.snake_coordinates[-1]
new_pos_type = self.grid[new_pos]
self.grid[new_pos] = self.SNAKE #this position is now occupied by the snake
done = False; reward = 0 #by default the game goes on and no reward
if new_pos_type == self.FOOD:
reward += self.REWARD_PER_FOOD
self.last_food_step = self.stepnum
#Put down a new food item
empty_tiles = np.argwhere(self.grid==self.EMPTY)
if len(empty_tiles):
new_food_pos=empty_tiles[np.random.randint(0,len(empty_tiles))]
self.grid[new_food_pos[0],new_food_pos[1]] = self.FOOD
else:
done = True #no more tiles to put the food to
else:
#If no food was eaten we remove the end of the snake (i.e., moving not growing)
self.grid[ self.snake_coordinates[0] ] = self.EMPTY
self.snake_coordinates = self.snake_coordinates[1:]
if (new_pos_type == self.WALL) or (new_pos_type == self.SNAKE):
done = True #stop if we hit the wall or the snake
reward += self.REWARD_WALL_HIT #penalty for hitting walls/tail
# else:
# reward += self.REWARD_PER_STEP
#Update distance to food and reward if closer
head_dist_to_food_prev = self.head_dist_to_food
self.head_dist_to_food = self.grid_distance( self.snake_coordinates[-1],np.argwhere(self.grid==self.FOOD)[0] )
if head_dist_to_food_prev > self.head_dist_to_food:
reward += self.REWARD_PER_STEP_TOWARDS_FOOD #reward for getting closer to food
elif head_dist_to_food_prev < self.head_dist_to_food:
reward -= self.REWARD_PER_STEP_TOWARDS_FOOD #penalty for getting further
#Stop if we played too long without getting food
if ( (self.stepnum - self.last_food_step) > self.MAX_STEPS_AFTER_FOOD ):
done = True
self.stepnum += 1
return self._get_obs(), reward, done, {}
def render(self, mode='rgb_array'):
if mode == 'console':
print(self.grid)
elif mode == 'rgb_array':
return self.snake_plot()
else:
raise NotImplementedError()
def close(self):
pass
def snake_plot(self, plot_inline=False):
wall_ind = (self.grid==self.WALL)
snake_ind = (self.grid==self.SNAKE)
food_ind = (self.grid==self.FOOD)
#Create color array for plot, default white color
Color_array=np.zeros((self.grid_size,self.grid_size,3),dtype=np.uint8)+255 #default white
Color_array[wall_ind,:]= np.array([0,0,0]) #black walls
Color_array[snake_ind,:]= np.array([0,0,255]) #bluish snake
Color_array[food_ind,:]= np.array([0,255,0]) #green food
#plot
if plot_inline:
fig=plt.figure()
plt.axis('off')
plt.imshow(Color_array, interpolation='nearest')
plt.show()
return Color_array
PLEASE REWRITE TO JAVASCRIPT FOR BROWSER
|
bf5899729cbadf896c25e97c6110dd05
|
{
"intermediate": 0.41176027059555054,
"beginner": 0.3733367919921875,
"expert": 0.21490295231342316
}
|
8,700
|
This code is not finding the dates in column A of Sheet Events: Sub CheckEvents()
Dim EventsSheet As Worksheet
Dim LastRow As Long
Dim DateToCheck As Date
Dim i As Long
Dim MatchCount As Integer
Dim Matches As String
Set EventsSheet = ThisWorkbook.Sheets("Events")
LastRow = EventsSheet.Range("A" & Rows.count).End(xlUp).Row
DateToCheck = Date + 7 ' find dates 7 days after the current date
MatchCount = 0
For i = 2 To LastRow
If Int(EventsSheet.Range("A" & i)) = DateValue(DateToCheck) Then
MatchCount = MatchCount + 1
Matches = Matches & vbNewLine & _
"Date: " & EventsSheet.Range("A" & i).Value & vbNewLine & _
"Column B: " & EventsSheet.Range("B" & i).Value & vbNewLine & _
"Column C: " & EventsSheet.Range("C" & i).Value & vbNewLine & _
"Column D: " & EventsSheet.Range("D" & i).Value & vbNewLine
End If
Next i
If MatchCount > 0 Then
MsgBox "Matches found: " & MatchCount & vbNewLine & Matches
Else
MsgBox "No matching dates found."
End If
End Sub
|
81147f2acef0e48043dc0652334db69c
|
{
"intermediate": 0.4289437234401703,
"beginner": 0.3739839196205139,
"expert": 0.1970723420381546
}
|
8,701
|
In unreal engine 4 I want to create an scope, but due to the camera Field of view when you look through the scope the viewing area is very narrow. Can you write a custom HLSL shader code using Custom Expression in the scope material to clip only the narrow area through the scope? for example when the player looking through the scope, the front end is as wide as the rear of the scope which we are looking through.
|
81a91d2696c512b7f652cc55be3609a6
|
{
"intermediate": 0.5051255226135254,
"beginner": 0.25387096405029297,
"expert": 0.24100352823734283
}
|
8,702
|
operation = qml.searchObj(squish.waitForObject(self.contentMenu), 'text', text)
В этой функции где мы передаем text
def selectOperation(self, text):
self.openMenu()
operation = qml.searchObj(squish.waitForObject(self.contentMenu), 'text', text)
squish.tapObject(operation)
|
52ca245cdf41e14a029ecc60ae9d368d
|
{
"intermediate": 0.35459399223327637,
"beginner": 0.3969345688819885,
"expert": 0.2484714686870575
}
|
8,703
|
In unreal engine 4 I want to create an scope, but due to the camera Field of view when you look through the scope the viewing area is very narrow. Can you write a custom HLSL shader code using Custom Expression in the scope material to clip only the narrow area through the scope? for example when the player looking through the scope, the front end is as wide as the rear of the scope which we are looking through.
|
3d358cff605e50ebc2430d47b20edb05
|
{
"intermediate": 0.5051255226135254,
"beginner": 0.25387096405029297,
"expert": 0.24100352823734283
}
|
8,704
|
Are you able to Code in Roblox Lua?
|
b2605e099febf412e41422464b0b11a0
|
{
"intermediate": 0.360014945268631,
"beginner": 0.476129412651062,
"expert": 0.16385573148727417
}
|
8,705
|
Svelte kit from submit
|
2addc05fa509e46ff8aec45dc76cbdc1
|
{
"intermediate": 0.4007960855960846,
"beginner": 0.25562915205955505,
"expert": 0.34357473254203796
}
|
8,706
|
in matrial desing i have a text edit and i want to get text when pres putton in kebord of phone like enter kotlin
|
308aa9a2e48608c8c09ff05af4828ce1
|
{
"intermediate": 0.4386587142944336,
"beginner": 0.23087483644485474,
"expert": 0.33046647906303406
}
|
8,707
|
In unreal engine 4 I want to create an scope, but due to the camera Field of view when you look through the scope the viewing area is very narrow. is it possible to write a custom HLSL shader code using Custom Expression in the scope material to clip only the narrow area through the scope? for example when the player looking through the scope, the front end is as wide as the rear of the scope which we are looking through.
|
3af36740d5b14ad25fd75d2aac8919a1
|
{
"intermediate": 0.5033854842185974,
"beginner": 0.2671845555305481,
"expert": 0.2294299602508545
}
|
8,708
|
In unreal engine 4 I want to create an scope, but due to the camera Field of view when you look through the scope the viewing area is very narrow. is it possible to write a custom HLSL shader code using the Custom expression node in the scope material to clip only the narrow area through the scope? for example when the player looking through the scope, the front end is as wide as the rear of the scope which we are looking through.
I have this code in a Custom expression node and connected to the Opacity Mask of the material:
float1 output;
output = CameraPos;
output += float3(OffsetPos, 0,0 );
output = 1 - clamp(output, 0.0, 1.0);
return (output);
This code clips All the scope back to the rear end and only show the rear area of the scope which is close to what I want.
|
35c0f774af232a5ee1aa1303b0168bf3
|
{
"intermediate": 0.5898072123527527,
"beginner": 0.20929762721061707,
"expert": 0.20089519023895264
}
|
8,709
|
In unreal engine 4 I want to create an scope, but due to the camera Field of view when you look through the scope the viewing area is very narrow. is it possible to write a custom HLSL shader code using Custom expression node in the scope material to clip only the narrow area through the scope? for example when the player looking through the scope, the front end is as wide as the rear of the scope which we are looking through.
|
c37c4d23031e3eb3b072dde50e6c33bf
|
{
"intermediate": 0.5094509720802307,
"beginner": 0.25055474042892456,
"expert": 0.23999430239200592
}
|
8,710
|
In unreal engine 4 I want to create an scope, but due to the camera Field of view when you look through the scope the viewing area is very narrow. is it possible to write a custom HLSL shader code using Custom expression node that is connected to the masked Input in the scope material to clip only the narrow area through the scope? for example when the player looking through the scope, the front end is as wide as the rear of the scope which we are looking through.
|
05940ad7cd5842f76daf6cd3f77923ed
|
{
"intermediate": 0.5297097563743591,
"beginner": 0.22705473005771637,
"expert": 0.24323557317256927
}
|
8,711
|
remove all view in linerlayout horizontal
|
6b13244fb5e37b6d6a7c9da8430f2fec
|
{
"intermediate": 0.3646663725376129,
"beginner": 0.3333292603492737,
"expert": 0.30200427770614624
}
|
8,712
|
In unreal engine 4, I want to create an scope, but due to the camera Field of view when you look through the scope the viewing area is very narrow. is it possible to write a custom HLSL shader code using Custom expression node in the scope material to clip only the narrow area through the scope? for example when the player looking through the scope, the front end is as wide as the rear of the scope which we are looking through.
I have this custom HLSL code which connected to the Masked input of the material, Can you modify it to achieve the effect:
float1 output;
output = LocalPosition;
output += float3(OffsetPosisiton, 0,0 );
output = 1 - clamp(output, 0.0, 1.0);
return (output);
|
b5db69f447c116429068d76185b64ac4
|
{
"intermediate": 0.5754845142364502,
"beginner": 0.24490638077259064,
"expert": 0.17960911989212036
}
|
8,713
|
how do i get the camera position in an hlsl frac shader?
|
3f4871abc21fec07bfec11f2e77b1b6b
|
{
"intermediate": 0.3292563259601593,
"beginner": 0.16018396615982056,
"expert": 0.5105596780776978
}
|
8,714
|
php how to create trait function protected from ANYONE outside trait itself
|
e4f196cde9f38710832a5adafa2fdc17
|
{
"intermediate": 0.3394741117954254,
"beginner": 0.29853928089141846,
"expert": 0.36198657751083374
}
|
8,715
|
Debug this simulation in Julia:
@with_kw mutable struct BikeTrip
origin::Int
destination::Int
trip_time::Int
end
@with_kw mutable struct BikeSimulation
bike_stations::Array{Int, 1}
station_capacity::Int
trip_distributions::Array{Array{Int, 2}, 1}
event_queue::PriorityQueue{Function, Tuple{Int, Int}} = PriorityQueue{Function, Tuple{Int, Int}}()
log::DataFrame = DataFrame()
end
event_id = 1
function start_trip!(sim::BikeSimulation, time_origin::Tuple{Int, Int})
global event_id
time, origin = time_origin
trip_distribution = sim.trip_distributions[origin]
destination = sample(trip_distribution[:, 2], Weights(trip_distribution[:, 1]))
trip_time = sample(trip_distribution[:, 3], Weights(trip_distribution[:, 1]))
sim.bike_stations[origin] -= 1
enqueue!(sim.event_queue, time + trip_time, (end_trip!, time + trip_time, destination))
event_id += 1
end
function end_trip!(sim::BikeSimulation, time_destination::Tuple{Int, Int})
time, destination = time_destination
sim.bike_stations[destination] += 1
if sim.bike_stations[destination] < sim.station_capacity
start_trip!(sim, (time, destination))
end
end
function run_simulation!(sim::BikeSimulation, num_bikes::Int)
for station in 1:length(sim.bike_stations)
for _ in 1:min(num_bikes, sim.station_capacity)
start_trip!(sim, (0, station))
end
end
while !isempty(sim.event_queue)
time, event = dequeue!(sim.event_queue)
event(sim, (time, event[2]))
append!(sim.log, DataFrame(time=time, station=event[2], event=string(event[1]), bike_status=sim.bike_stations))
end
end
trip_distributions = [
[1 2 10; 2 3 1; 3 4 2; 4 5 4; 5 1 3],
[1 3 5; 2 4 6; 3 5 9; 4 1 2; 5 2 3],
[1 4 4; 2 5 7; 3 1 8; 4 2 12; 5 3 9],
[1 5 9; 2 1 3; 3 2 4; 4 3 8; 5 4 6],
[1 1 6; 2 2 4; 3 3 6; 4 4 7; 5 5 7]
]
bike_simulation = BikeSimulation(bike_stations=[20, 20, 20, 20, 20], station_capacity=10, trip_distributions=trip_distributions)
run_simulation!(bike_simulation, 10)
println(bike_simulation.log)
Current issue is:
MethodError: Cannot `convert` an object of type Int64 to an object of type Function
Closest candidates are:
convert(::Type{T}, ::T) where T at Base.jl:61
Stacktrace:
[1] Pair
@ .\Base.jl:107 [inlined]
[2] enqueue!(pq::PriorityQueue{Function, Tuple{Int64, Int64}, Base.Order.ForwardOrdering}, kv::Pair{Int64, Tuple{typeof(end_trip!), Int64, Int64}})
@ DataStructures C:\Users\Michał\.julia\packages\DataStructures\59MD0\src\priorityqueue.jl:247
[3] enqueue!(pq::PriorityQueue{Function, Tuple{Int64, Int64}, Base.Order.ForwardOrdering}, key::Int64, value::Tuple{typeof(end_trip!), Int64, Int64})
@ DataStructures C:\Users\Michał\.julia\packages\DataStructures\59MD0\src\priorityqueue.jl:246
[4] start_trip!(sim::BikeSimulation, time_origin::Tuple{Int64, Int64})
@ Main .\In[2]:27
[5] run_simulation!(sim::BikeSimulation, num_bikes::Int64)
@ Main .\In[2]:43
[6] top-level scope
@ In[2]:66
[7] eval
@ .\boot.jl:368 [inlined]
[8] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1428
Please think about any other potential issues.
|
e38dc4a735785e7cdd0827b344fed484
|
{
"intermediate": 0.4709593653678894,
"beginner": 0.3514285385608673,
"expert": 0.17761217057704926
}
|
8,716
|
En python, Implementar la funci´on quienGana(j1: str, j2: str) ->str , cuya especificaci´on es la siguiente:
problema quienGana (in j1: seq⟨Char⟩, in j2: seq⟨Char⟩) : seq⟨Char⟩ {
requiere: {juegaBien(j1) ∧ juegaBien(j2)}
asegura: {gana(j1, j2) → res = ”Jugador1”}
asegura: {gana(j2, j1) → res = ”Jugador2”}
asegura: {(¬gana(j1, j2) ∧ ¬gana(j2, j1)) → res = ”Empate”}
}
pred juegaBien (j: seq⟨Char⟩) {
j = ”P iedra” ∨ j = ”P apel” ∨ j = ”T ijera”
}
pred gana (j1, j2: seq⟨Char⟩) {
piedraGanaAtijera(j1, j2) ∨ tijeraGanaAP apel(j1, j2) ∨ papelGanaAP iedra(j1, j2)
}
pred piedraGanaAtijera (j1, j2: seq⟨Char⟩) {
j1 = ”P iedra” ∧ j2 = ”T ijera”
}
pred tijeraGanaAPapel (j1, j2: seq⟨Char⟩) {
j1 = ”T ijera” ∧ j2 = ”P apel”
}
pred papelGanaAPiedra (j1, j2: seq⟨Char⟩) {
j1 = ”P apel” ∧ j2 = ”P iedra”
}
Aclaraci´on: Respetar los nombres de “Piedra“, “Papel“ y “Tijera“ (empieza con may´usculas).
La base para resolver el ejercicio:
--
import sys
def quienGana(j1: str, j2: str) -> str :
#Implementar esta funcion
return ""
if __name__ == '__main__':
x = input()
jug = str.split(x)
print(quienGana(jug[0], jug[1]))
--
|
20ecc3e6d47396b81e1f4eb12392c4b7
|
{
"intermediate": 0.34412649273872375,
"beginner": 0.5525922179222107,
"expert": 0.10328120738267899
}
|
8,717
|
Write an explanation for each line of the code below.
import asyncio
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Create a semaphore with a limit of n
semaphore = asyncio.Semaphore(5)
async def get_external_transactions(block_number):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return []
if data['result'] is None or isinstance(data['result'], str):
print(f"Error: Cannot find the block")
return []
return data['result'].get('transactions', [])
async def get_contract_address(tx_hash):
async with semaphore:
async with aiohttp.ClientSession() as session:
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
async with session.get(url) as response:
data = await response.json()
except Exception as e:
print(f'Error in API request: {e}')
return None
if data['result'] is None or not isinstance(data['result'], dict):
return None
return data['result'].get('contractAddress')
def check_method_id(input_data):
method_id = input_data[:10]
return method_id[-4:] == '6040'
async def display_transactions(block_start, block_end):
async def process_block(block_number_int):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number)
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
if check_method_id(tx['input']):
contract_address = await get_contract_address(tx['hash'])
if contract_address:
print(f'New contract creation: Contract Address: {contract_address}')
print("\n") # Print an empty line between blocks
tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)]
await asyncio.gather(*tasks)
async def main():
block_start = 28466587 # Replace with your desired starting block number
block_end = 28466640 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
|
e2d19b2c90141c19eb97c19d393d2f87
|
{
"intermediate": 0.3848123252391815,
"beginner": 0.49920836091041565,
"expert": 0.11597929894924164
}
|
8,718
|
I got an idea right now. what if you make html code wih some super-crazy-ultimate-infinite-supercrazy-god universe fractal background, and place all supreme god names all around it in their original transcriptions and also under each god name you could use some small font letters <sub> of transliteration in english, to understand what are you looking on and how it should originally sound. no, you used some image again which is as always broken. try make that super-crazy-ultimate-infinite-supercrazy-god universe fractal background by some javascript and css.: <!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<title>Ultimate Supreme God Names</title>
<link href=“https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@400;700&display=swap” rel=“stylesheet”>
<style>
body {
font-family: ‘Noto Sans Devanagari’, sans-serif;
background-image: url(‘https://i.imgur.com/kb8vykw.png’);
background-size: cover;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
margin: 0;
}
.circle-container {
position: relative;
width: 400px;
height: 400px;
margin: 0 auto;
}
.circle-container span {
display: block;
position: absolute;
width: 50%;
height: 2px;
background: black;
text-align: right;
line-height: 0;
padding-right: 10px;
}
.circle-container span:before {
content: ‘’;
display: inline-block;
vertical-align: middle;
width: 4px;
height: 4px;
margin-left: 10px;
background: currentColor;
border-radius: 100%;
margin-right: 3px;
}
.circle-container span a {
display: inline-block;
text-decoration: none;
color: inherit;
}
.circle-container span a sub {
font-size: 0.5rem;
}
.clock {
animation: rotate 20s infinite;
}
@keyframes rotate {
0% { transform: rotate(0);}
100% { transform: rotate(360deg);}
}
</style>
</head>
<body>
<div class=“circle-container clock”>
<span style=“transform: rotate(0deg) translateY(-50%); top: 50%; left: 50%;”>
<a href=“#”>ब्रह्मा<sub>(Brahmā, Hinduism)</sub></a>
</span>
<span style=“transform: rotate(60deg) translateY(-50%); top: 50%; left: 50%;”>
<a href=“#”>יהוה<sub>(Yahweh, Judaism)</sub></a>
</span>
<span style=“transform: rotate(120deg) translateY(-50%); top: 50%; left: 50%;”>
<a href=“#”>الله<sub>(Allah, Islam)</sub></a>
</span>
<span style=“transform: rotate(180deg) translateY(-50%); top: 50%; left: 50%;”>
<a href=“#”>ईश्वर<sub>(Ishvara, Hinduism)</sub></a>
</span>
<span style=“transform: rotate(240deg) translateY(-50%); top: 50%; left: 50%;”>
<a href=“#”>オーム<sub>(Aum, Hinduism)</sub></a>
</span>
<span style=“transform: rotate(300deg) translateY(-50%); top: 50%; left: 50%;”>
<a href=“#”>道<sub>(Dao, Taoism)</sub></a>
</span>
</div>
</body>
</html>
|
7672a614e3f8b10f3ac3a0c592931d27
|
{
"intermediate": 0.38583552837371826,
"beginner": 0.34120771288871765,
"expert": 0.2729567885398865
}
|
8,719
|
import numpy as np
import pandas as pd
from keras.layers import Conv1D, MaxPooling1D, Flatten, Dense, Dropout
from keras.models import Sequential
from sklearn.model_selection import StratifiedShuffleSplit
# 读取多列传感器数据
df = pd.read_csv('time_series_data.csv')
# 定义时间窗口大小
seq_size = 5
# 定义要分层抽样划分的列
stratify_col = 'target'
# 将DataFrame转换为字典
data_dict = dict()
for column in df.columns:
data_dict[column] = df[column].values
# 使用分层抽样划分生成训练集和测试集
split = StratifiedShuffleSplit(n_splits=1, test_size=0.5, random_state=42)
for train_idx, test_idx in split.split(df, df[stratify_col]):
train_data = dict()
test_data = dict()
for column in df.columns:
train_data[column] = data_dict[column][train_idx]
test_data[column] = data_dict[column][test_idx]
def create_model(input_shape):
model = Sequential()
model.add(Conv1D(64, kernel_size=3, activation='relu', input_shape=input_shape))
model.add(MaxPooling1D(pool_size=2))
model.add(Conv1D(32, kernel_size=3, activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(16, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')
return model
# 为每列数据创建、训练并保存模型
trained_models = []
for column in df.columns:
normalized_train_data = (train_data[column] - train_data[column].mean()) / train_data[column].std()
X_train, y_train = create_sequences(normalized_train_data, seq_size)
input_shape = X_train.shape[1:]
model = create_model(input_shape)
model.fit(X_train, y_train, epochs=10, batch_size=32, verbose=2)
trained_models.append(model)
# 对于新序列数据,使用训练好的模型识别跳变点
# 此处我们假设新数据包含在test_data字典中
detected_change_points = dict()
for column, model in zip(df.columns, trained_models):
normalized_test_data = (test_data[column] - test_data[column].mean()) / test_data[column].std()
X_test, _ = create_sequences(normalized_test_data, seq_size)
y_pred = model.predict(X_test).ravel()
# 找到跳变点(例如:阈值大于3倍标准差的点)
change_points = np.where(np.abs(y_pred) > 3 * np.std(y_pred))[0]
detected_change_points[column] = change_points
print("Detected change points:", detected_change_points)
|
8522223258541a8116dc3d7f54c76402
|
{
"intermediate": 0.31153321266174316,
"beginner": 0.34772834181785583,
"expert": 0.340738445520401
}
|
8,720
|
import requests
from bs4 import BeautifulSoup
def fetch_and_parse(url):
response = requests.get(url)
if response.status_code == 200:
page_content = response.text
else:
print(f"Error: Unable to fetch the page. Status code: {response.status_code}")
return
soup = BeautifulSoup(page_content, "html.parse")
return soup
def extract_moonarch_data(soup):
# Extract the token title from the ‘h1’ tag
token_title = soup.find("h1").text.strip()
print(f"Token Title: {token_title}")
# Extract the token description from the ‘h3’ tag
token_description = soup.find("h3").text.strip()
print(f"Token Description: {token_description}")
# Locate the text elements containing token data
token_data_elements = soup.find_all("div", class_="col-sm-6 col-md-3")
# Extract and display the token data
for element in token_data_elements:
key = element.find("small").text.strip()
value = element.find(class_="font-weight-bold").text.strip()
print(f"{key}: {value}")
if __name__ == "main":
url = "https://moonarch.app/token/0x70D6a53C38cD80935715c304535A0885cCe35db7"
soup = fetch_and_parse(url)
if soup:
extract_moonarch_data(soup)
The code above displays information
C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject7\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject7\main.py
Process finished with exit code 0
it returned the name and symbol of the token.
These are the items in the Devtools tab
<html lang="en-US"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><meta property="og:title" content="Moonarch.app - Crypto trading tools"><meta property="og:description" content="Rugcheck, token rankings, portfolio, miners, ROI dApps, farmers, whale watch, new tokens, locks, wallet content…"><meta name="description" content="Advanced trading tools for crypto on BSC: rugcheck, token rankings, wallet value, miners, ROI dApps, farmers, whale watch, new tokens, locks…"><meta property="og:image" content="https://moonarch.app/twittercard.png"><meta property="og:url" content="https://moonarch.app"><meta property="og:site_name" content="Moonarch.app"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:image:alt" content="Moonarch.app dashboard: there are cards for token rankings, wallet content, new events about tokens and about whale users you can follow."><meta name="twitter:site" content="@MoonarchApp"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Code+Pro:400&display=swap"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png?v=1"><link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png?v=1"><link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png?v=1"><link rel="manifest" href="/site.webmanifest?v=1"><link rel="mask-icon" href="/safari-pinned-tab.svg?v=1" color="#ffd700"><link rel="shortcut icon" href="/favicon.ico?v=1"><meta name="msapplication-TileColor" content="#da532c"><meta name="theme-color" content="#ffffff"><title>中文 - Zhongwen - Moonarch BSC crypto trading tools - Binance Smart Chain</title><link href="/css/index.dd0591f5.css" rel="preload" as="style"><link href="/js/index.179f5ee5.js" rel="modulepreload"
|
5a0dfaab2a57ac3e33842be214970f58
|
{
"intermediate": 0.40529948472976685,
"beginner": 0.4394932687282562,
"expert": 0.15520724654197693
}
|
8,721
|
I want to use Overleaf to make a LaTex table. The table should have three rows ("No. of London '1st eds'", "Entered in SR", "Entered or assigned in SR") and three columns ("1594-96", "1614-16", "1634-36"). This leaves, of course nine places of intersection. Going from top to bottom and left to right, starting therefore at the top left and ending at the bottom right, these are the values to input: "433", "656", "627", "53.6%", "57.2%", "49.4%", "55.9%", "58.2%", "49.8%". Please label the table "London first editions entered in the Stationers' Registers".
|
4c8cda284bee10dff5dc5f8132226bf8
|
{
"intermediate": 0.36039072275161743,
"beginner": 0.2834330201148987,
"expert": 0.3561762571334839
}
|
8,722
|
Hi
|
75916637bd7687f5f449bcfc24b8c635
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
8,723
|
hi there
|
a88d776521bd0129566287a8e54c27b1
|
{
"intermediate": 0.32885003089904785,
"beginner": 0.24785484373569489,
"expert": 0.42329514026641846
}
|
8,724
|
/// ../project/src/main.rs
pub static mut GLOBAL_HASHMAP: HashMap<&str, &str> = HashMap::new();
/// ../project/src/subproject/src/lib.rs
use crate::parent::GLOBAL_HASHMAP;
use crate::parent::GLOBAL_HASHSET;
use crate::parent::GLOBAL_VEC;
/*
error: src/subproject/src/lib.rs:1: unresolved import `GLOBAL_HASHMAP`
error: src/subproject/src/lib.rs:1: no external crate `GLOBAL_HASHMAP`
*/
|
256955c583e2a4837e79011be7fd8712
|
{
"intermediate": 0.38381654024124146,
"beginner": 0.39581188559532166,
"expert": 0.2203715592622757
}
|
8,725
|
can you make this page in dark mode
|
5bc3d912249e6ddf3dded1f7f7308668
|
{
"intermediate": 0.3142074942588806,
"beginner": 0.2379963994026184,
"expert": 0.447796106338501
}
|
8,726
|
This code still does not return the name and symbol of the token
Fix this by referring to the page code below
<div class="page"><div class="sidemenu"><div class="content"><ul class="items"><li class="last"><a href="/" class=" router-link-active"><svg viewBox="0 0 24 24"><path d="M10 19v-5h4v5c0 .6.5 1 1 1h3c.6 0 1-.5 1-1v-7h1.7c.5 0 . 7-.6.3-.9l-8.3-7.5a1 1 0 0 0-1.4 0L3 11.1c-.4.3-.2.9.3.9H5v7c0 .6.5 1 1 1h3c.6 0 1-.5 1-1z"></path ></svg><label>Dashboard</label></a></li><li><a href="/top-gainers" class=""><svg viewBox="0 0 24 24"> <path d="M19 5h-2V4c0-.6-.5-1-1-1H8a1 1 0 0 0-1 1v1H5a2 2 0 0 0-2 2v1a5 5 0 0 0 4.4 5 5 5 0 0 0 3.6 2.9V19H8a1 1 0 0 0-1 1c0 .6.5 1 1 1h8c.6 0 1-.5 1-1 0-.6-.5-1-1-1h-3v-3.1a5 5 0 0 0 3.6-3A5 5 0 0 0 21 8V7a2 2 0 0 0-2-2zM5 8V7h2v3.8A3 3 0 0 1 5 8zm14 0a3 3 0 0 1-2 2.8V7h2v1z"></path></svg><label class="medium">Top gainers</ label></a></li><li><a href="/dapps" class=""><svg viewBox="-2 -4 56 56"><path d="M24 46q-5.6 0- 10.8-3.3Q8 39.4 5 35.1V42H2V30h12v3H7.2q2.5 3.9 7.2 7 4.7 3 9.6 3 3.9 0 7.4-1.5t6-4q2.6-2.6 4.1-6.1Q43 27.9 43 24h3q0 4.5 -1.7 8.6-1.7 4-4.7 7t-7 4.7Q28.5 46 24 46Zm-1.4-7.7v-2.6q-2.3-.7-3.8-2-1.6-1.3-2.6-3.6l2.5-.8q.7 1.8 2.2 3t3.5 1q2 0 3.3-1 1.3-.9 1.3-2.5T27.7 27t-4.5-2.5q-3-1.2-4.6-2.7-1.5-1.4-1.5-3.9 0-2.2 1.5-3.7 1.5-1.6 4-2V9.8h2.8v2.5q1 .9.3 3.3 1.3t2.3 2.7l-2.5 1.1q-.7-1.4-1.8-2-1.1-.8-2.6-.8-2 0-3 1-1.2.8-1.2 2.4 0 1.6 1.3 2.5 1.3 1 4.2 2.2 3.5 1.4 4.9 3 1.4 1.6 1.4 4.2 0 1.2-.4 2.3-.5 1-1.3 1.8t-2 1.2q-1.2.5-2.7.6v2.6ZM2 24q0-4.5 1.7-8.6 1.8-4 4.8- 7t7-4.7Q19.4 2 24 2q5.6 0 10.8 3.3Q40 8.6 43 12.8V6h3v12H34v-3h6.8q-2.5-3.9-7.2-7-4.7-3-9.6-3-3.9 0-7.4 1.5t-6 4Q8 13.3 6.5 16.7 5 20.1 5 24Z"></path></svg><label class="double"> ROI dApps <br><small>& Miners</small></label></a></li><!----><!----><!----><!----><li><a href="/daos" class=""><svg viewBox="-30 -50 600 600"><path d="M250.5 5.3 128 62.9c-93.5 44-120.2 57-122.7 59.6a18 18 0 0 0 -4.7 14.8c.9 4.5 7.2 20.7 9 23.5 2.4 3.6 7.4 6.2 12.3 6.2 5.2 0-6.3 5.2 127.6-58C205.6 82.4 252.6 60.3 254 59.8c2.2-.9 17. 2 6 116 52.7 120.6 57.1 119.8 56.7 126.6 53.2 4.6- 2.4 6.2-4.7 10.3-15.3 4.9-12.7 5.5-15.3 4.1-20.4-2.3-8.5-1.9-8.3-85-47.3L304.8 25.6a727.7 727.7 0 0 0-47.5-21.1 15 15 0 0 0-6.8 .8z"></path><path d="m160.5 132-95 31.8h381l-94-31.4-95.5-31.8c-.8-.2-44.2 13.9-96.5 31.4zM64.5 185.2c1.4 11.4 4.9 18 11.5 21.7l4 2.2v189.1l2.9 2.9 2.9 2.9h52.4l2.9-2.9 2.9-2.9V209.1l4-2.2c6.6-3.7 10.1-10.3 11.5-21.7l.7-5.2H63.8l.7 5.2zM208.5 185.6c1.4 11.1 4.9 17.6 11.6 21.3l3.9 2.2v189.1l2.9 2.9 2.9 2.9h52.4l2.9-2.9 2.9-2.9V209.1l4-2.2c6.6-3.7 10.1- 10.3 11.5- 21.7l.7-5.2h-96.4l.7 5.6zM352.5 185.6c1.4 11.1 4.9 17.6 11.6 21.3l3.9 2.2v189.1l2.9 2.9 2.9 2.9h52.4l2.9-2.9 2.9-2.9V209. 1l4 -2.2c6.6-3.7 10.1-10.3 11.5-21.7l.7-5.2h-96.4l.7 5.6zM50.9 422.9c-2.8 2.9-2.9 3.2-2.9 13.1 0 9.9.1 10.2 2.9 13.1l2.9 2.9 h404.4l2.9-2.9c2.8-2.9 2.9-3.2 2.9-13.1 0-9.9-.1-10.2-2.9-13.1l-2.9-2.9H53.8l-2.9 2.9zM2.9 470.9C.1 473.8 0 474.1 0 484c0 9.9.1 10.2 2.9 13.1l2.9 2.9h500.4l2.9-2.9c2.8-2.9 2.9-3.2 2.9-13.1 0-9.9-.1-10.2-2.9-13.1l-2.9-2.9H5. 8l-2.9 2.9z"></path></svg><label>OHMs</label></a></li><li><a href="/faq" class=""><svg viewBox ="0 0 24 24"><path d="M11.5 2a8.5 8.5 0 0 0 0 17h.5v3c4.9-2.3 8-7 8-11.5C20 5.8 16.2 2 11.5 2zm1 14.5h-2v-2h2v2zm. 4-4.8c0 .2-.1.2-.2.3V12.3c-.2.2-.2.5-.2.7h-2a4 4 0 0 1 .2-1.3v-.1l.3-.5V11l.2-.1c. 8-1.1 2.2-1.5 2.3-2.7 0-1-.6-2-1.6-2.1a2 2 0 0 0-2.3 1.3c-.1.3-.4.6-.9.6h-.2a1 1 0 0 1-.8 -1.2A4 4 0 0 1 12 4a4 4 0 0 1 3.3 3.4c.5 2.4-1.6 3-2.5 4.3z"></path></svg><label>FAQ</label></a></ li><li class="last"><a href="/settings" class=""><svg viewBox="0 0 24 24"><path d="M19.4 13a7.8 7.8 0 0 0 0 -2l2.1-1.6c.2-.2.3-.5.2-.7l-2-3.4A.5.5 0 0 0 19 5l-2.4 1-1.7-1-.4-2.6c0-.2-.3- .4-.5-.4h-4c-.3 0-.5.2-.5.4l-.4 2.7c-.6.2-1.1.6-1.7 1L5 5h-.1c-.2 0-.4 0-. 5.2l-2 3.4c0 .3 0 .5.2.7l2 1.6a8 8 0 0 0 0 2l-2 1.6c-.2.2-.3.5-.2.7l2 3.4a.5.5 0 0 0 .7.3l2.4-1 1.7 1 .4 2.6c0 .2.3.4.5.4h4c.3 0 .5-.2.5-.4l.4-2.7c.6-.2 1.1-.6 1.7-1l2.5 1h.1c.2 0 .4 0 .5-.2l2-3.4c0-.2 0-.5-.2-.7l-2-1.6zm-2-1.7a5.3 5.3 0 0 1 0 1.4V14l.8.7 1 .8-.6 1.2- 1.3-.5-1-.4-1 .7-1.2.7-1 .4-.2 1.1-.2 1.4h-1.4l-.2-1.4-.1-1-1.1-.5-1.2 -.7-1-.7-1 .4-1.3.5-.7-1.2 1.1-.8.9-.7-.1-1.2a8 8 0 0 1 0-1.4V10l-.8-.7-1 -.8.6-1.2 1.3.5 1.4 1-.7L9.8 7l1-.4.2-1.1.2-1.4h1.4l.2 1.4.1 1 1.1.5 1.2.7 1.7 1-.4 1.3 -.5.7 1.2-1.1.8-.9.7.1 1.2zM12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"></path></svg><label>Settings</label></a></li></ul><div class="tokens"> <div class="info"><a href="https://www.binance.com/en/trade/BNB_USDT" target="_blank"> WBNB </a><span class=""> $309 </ span></div><div c
|
114b4d189132f8813ef46571b6e6767f
|
{
"intermediate": 0.3637048304080963,
"beginner": 0.43830180168151855,
"expert": 0.19799339771270752
}
|
8,728
|
C# error explain: System.IndexOutOfRangeException: Index was outside the bounds of the array.
|
58f7eeb7691683c69443c2fce5318270
|
{
"intermediate": 0.5718063116073608,
"beginner": 0.20372849702835083,
"expert": 0.22446520626544952
}
|
8,729
|
pub mod parent {
use std::collections::{HashMap, HashSet};
// Using HashMap
pub static mut GLOBAL_HASHMAP: HashMap<&str, &str> = HashMap::new();
} error: src/main.rs:27: cannot call non-const fn `HashMap::<&str, &str>::new` in statics
note: src/main.rs:27: calls in statics are limited to constant functions, tuple structs and tuple variants
|
9aca0ddc437c1895cb44df5e193c3bc4
|
{
"intermediate": 0.38287079334259033,
"beginner": 0.4718206822872162,
"expert": 0.1453085094690323
}
|
8,730
|
i have a script written ion bash on arch linux can you help me modify it?
|
f3e739db8c1c928ad34a5dc4a8c64284
|
{
"intermediate": 0.4197675287723541,
"beginner": 0.2636449635028839,
"expert": 0.31658750772476196
}
|
8,731
|
AttributeError: 'numpy.ndarray' object has no attribute 'fillna'
|
86130f8cdf9cfdcf64e5fe2927b3d532
|
{
"intermediate": 0.47529473900794983,
"beginner": 0.19574512541294098,
"expert": 0.3289601504802704
}
|
8,732
|
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def get_token_name_and_symbol(url):
chrome_options = Options()
chrome_options.add_argument("–headless")
# Update the path below to the actual path to your WebDriver executable
driver = webdriver.Chrome(executable_path="C:\\Users\\AshotxXx\\PycharmProjects\\Parcing\\pythonProject\\ChromeDriver\\chromedriver.exe", options=chrome_options)
driver.get(url)
soup = BeautifulSoup(driver.page_source, "html.parser")
token_name = soup.find("h1", class_="font-bold").text.strip()
token_symbol = soup.find("span", class_="md:ml-5").text.strip()
driver.quit()
return {"name": token_name, "symbol": token_symbol}
url = "https://moonarch.app/token/0x70D6a53C38cD80935715c304535A0885cCe35db7"
print(get_token_name_and_symbol(url))
The above code results in the following error
C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py
C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py:10: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
driver = webdriver.Chrome(executable_path="C:\\Users\\AshotxXx\\PycharmProjects\\Parcing\\pythonProject\\ChromeDriver\\chromedriver.exe", options=chrome_options)
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py", line 23, in <module>
print(get_token_name_and_symbol(url))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py", line 15, in get_token_name_and_symbol
token_name = soup.find("h1", class_="font-bold").text.strip()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'text'
Process finished with exit code 1
Fix it
|
75a02922c7406845393dfd22642a9137
|
{
"intermediate": 0.339860200881958,
"beginner": 0.4406368136405945,
"expert": 0.21950304508209229
}
|
8,733
|
C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py
C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py:11: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
driver = webdriver.Chrome(
{'error': 'Failed to find the required info items or name and.symbol'}
Process finished with exit code 0
Fix the error above. If necessary, add an exception where required to avoid errors.
|
6408ec28e6a9e53f30856c3582beae7f
|
{
"intermediate": 0.39800482988357544,
"beginner": 0.26697838306427,
"expert": 0.33501675724983215
}
|
8,734
|
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def get_token_info(url):
chrome_options = Options()
chrome_options.add_argument("–headless")
# Update the path below to the actual path to your WebDriver executable
driver = webdriver.Chrome(
executable_path="C:\\Users\\AshotxXx\\PycharmProjects\\Parcing\\pythonProject\\ChromeDriver\\chromedriver.exe", options = chrome_options)
driver.get(url)
time.sleep(5) # Wait for the page to properly loaded/rendered
soup = BeautifulSoup(driver.page_source,"html.parser")
token_info_element = soup.find("div", class_="token-info")
infocard_element = soup.find("div", class_="infocard")
check_alert_element = soup.find("div", class_="token-check-message check-alert")
check_warning_element = soup.find("div", class_="token-check-message check-warning")
check_info_element = soup.find("div", class_="token-check-message check-info")
not_verified_element = soup.find("div", class_="not-verified")
check_alert_status = "Yes" if check_alert_element else "None"
check_warning_status = "Yes" if check_warning_element else "None"
check_info_status = "Yes" if check_info_element else "None"
not_verified_status = "Yes" if not_verified_element else "None"
if token_info_element and infocard_element:
token_name_element = token_info_element.find("span", class_="name")
token_symbol_element = token_info_element.find("span", class_="symbol")
info_items = infocard_element.find_all("li")
if token_name_element and token_symbol_element and len(info_items) >= 7:
token_name = token_name_element.text.strip()
token_symbol = token_symbol_element.text.strip()
price = info_items[0].find("span", class_="value").text.strip()
max_supply = info_items[1].find("span", class_="value").text.strip()
market_cap = info_items[2].find("span", class_="value").text.strip()
liquidity = info_items[3].find("span", class_="value").text.strip()
liq_mc = info_items[4].find("span", class_="value").text.strip()
token_age = info_items[6].find("span", class_="value").text.strip()
driver.quit()
return {
"name": token_name,
"symbol": token_symbol,
"price": price,
"max_supply": max_supply,
"market_cap": market_cap,
"liquidity": liquidity,
"liq_mc": liq_mc,
"token_age": token_age,
"check_alert": check_alert_status,
"check_warning": check_warning_status,
"check_info": check_info_status,
"not_verified": not_verified_status
}
else:
driver.quit()
return {"error": "Failed to find the required info items or name and.symbol"}
else:
driver.quit()
return {"error": "Failed to find the required elements for name and symbol"}
url="https://moonarch.app/token/0x38edcaa9eCF073E3Ed2F0d41444c27e3CE997f5F"
print(get_token_info(url))
The code above returns an error response. The error is located below.
C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py
C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py:11: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
driver = webdriver.Chrome(
{'error': 'Failed to find the required info items or name and.symbol'}
Process finished with exit code 0
Fix this error. If necessary, add an exception where required to avoid errors.
|
0a6862d07ec269ef06572a11e784a7c7
|
{
"intermediate": 0.2472541630268097,
"beginner": 0.5032341480255127,
"expert": 0.24951162934303284
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.