row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
8,430
|
hi
|
d566a01fcef9d2725e0be52107fd57ad
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
8,431
|
hi
|
692f1395a326b22fbada63886c956f15
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
8,432
|
Please provide an example of simple plugin for Wordpress CRM
|
32592244fef4027264ad8f99443177de
|
{
"intermediate": 0.5642423629760742,
"beginner": 0.24613529443740845,
"expert": 0.18962231278419495
}
|
8,433
|
I have data of temperature of the world from 1951 (71 years ago) for July and I want to forecast the data for 2060 (38 years later).
write the code for matlab for this problem.
|
36e56e3668be99788cde03a1972ec924
|
{
"intermediate": 0.529987633228302,
"beginner": 0.21216347813606262,
"expert": 0.2578488886356354
}
|
8,434
|
Can you write a simple rust example
|
8389b0ac00c81ff286525b0202401461
|
{
"intermediate": 0.23160673677921295,
"beginner": 0.5035114288330078,
"expert": 0.26488184928894043
}
|
8,435
|
can i use jq in bash to write to vdf file or a different way?
|
e13115138c0cbe14b992b1a7907e7a70
|
{
"intermediate": 0.6377183794975281,
"beginner": 0.14604444801807404,
"expert": 0.21623718738555908
}
|
8,436
|
Что лучше использовать в page object такой вид записи для хранения локаторов, чтобы потом использовать их для клика и других действий на сайте
// Получить строку из таблицы
public getString(name) {
return this.methodologySettingsTab.getStringMethodology(name);
}
или
public get String() {
return (name) => methodologySettingsTab.getStringMethodology(name);
}
я пишу на playwright + ts
|
ac369ff4f70fd06176d61436d5a9a4e8
|
{
"intermediate": 0.3878217339515686,
"beginner": 0.34341558814048767,
"expert": 0.2687627375125885
}
|
8,437
|
Php how to force function argument to be one of few strings?
|
5a8f2a81f175676d28a94d8212b80b62
|
{
"intermediate": 0.3138311207294464,
"beginner": 0.2826784551143646,
"expert": 0.4034903943538666
}
|
8,438
|
写一个python程序,不管你用什么方法,帮我抓取https://1xbet.com/cn/allgamesentrance/crash的赔率,要求你确定可抓取再给我程序
|
e5ab14aabe66c92c01359a02ef7556a6
|
{
"intermediate": 0.3260785937309265,
"beginner": 0.32794812321662903,
"expert": 0.34597328305244446
}
|
8,440
|
I have this code : 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
df = getminutedata('BTCUSDT', '1m', '1440')
dataF = df
# Define function to generate trading signals
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 ''
signal = []
signal.append(0)
for i in range(1,len(dataF)):
df = dataF[i-1:i+1]
signal.append(signal_generator(df))
singal = signal_generator(df)
dataF["signal"] = signal
while True:
dataF.signal.value_counts()
dataF.iloc[:, :]
current_signal = signal_generator(signal.value_counts(df))
current_time = dt.datetime.now().strftime("%m/%d %H:%M:%S")
print(f"The signal time is: {current_time} :{current_signal}")
time.sleep(1)Please give me code for I can see live signals from signal_generator
|
36696156070c20662aa526eef490dcba
|
{
"intermediate": 0.4229305386543274,
"beginner": 0.3207150399684906,
"expert": 0.256354421377182
}
|
8,441
|
python ad to pdf watermark in blue colored (rgb) border with text "created on" custom text and current date. watermark should be in right bottom corner. color of text is blue. font is arial and font size is 32.
|
5ab3be4cb093df587544bcb0026be64c
|
{
"intermediate": 0.4074038863182068,
"beginner": 0.1963038444519043,
"expert": 0.3962922990322113
}
|
8,442
|
const [questionnaire, categories] = await prisma.$transaction([
prisma.questionnaire.findFirst({
orderBy: [{ startDate: “desc” }],
where: {
…filter,
approved: true,
disabled: false,
endDate: {
// gte: addDays(new Date(), -5), //previous code
gte: subDays(new Date(), -5), // return questionnaires with in the last 5 days of the current date
lte: new Date(),
},
startDate: {
lte: new Date(),
},
isDraft: false,
},
include: {
questionnaireItems: {
where: {
disabled: false,
},
include: {
item: {
include: {
translation: true,
itemMeasurements: true,
},
},
},
},
questionnaireRegionStatus: {
where: { regionCode: { in: regionCodes } },
},
},
}),
prisma.division.findMany({
where: { disabled: false },
include: {
group: {
where: { disabled: false },
include: {
class: {
where: { disabled: false },
include: {
subclass: {
where: { disabled: false },
include: {
translation: true,
},
},
translation: true,
},
},
translation: true,
},
},
translation: true,
},
}),
]); why is the above code not returning questionnaires that are equal to the current date or below the current date
|
1c5a8e60f7eb19da54baa513cf47a7ba
|
{
"intermediate": 0.47044897079467773,
"beginner": 0.331650048494339,
"expert": 0.19790101051330566
}
|
8,443
|
• Read in the dataset "heart_disease_patients.csv" into a
variable called heart_disease.
|
60af761d93b0728f351e028d96e0ecdd
|
{
"intermediate": 0.25254419445991516,
"beginner": 0.5254061818122864,
"expert": 0.22204963862895966
}
|
8,444
|
The dataset will split into 80% train and 20% test. The feature matrices will
assign to X_train and X_test, while the arrays of labels are assigned
to y_train and y_test where class 1 corresponds to a malignant tumor and
class 0 corresponds to a benign tumor. To obtain reproducible results, you
also defined a variable called SEED which is set to 1. • Read in the dataset "heart_disease_patients.csv" into a
variable called heart_disease
|
03a830e21dd5eb11d2229ad7488217ce
|
{
"intermediate": 0.22536420822143555,
"beginner": 0.3103953003883362,
"expert": 0.4642404615879059
}
|
8,445
|
php how to declare enum within class?
|
f28a658d64276d6d42f51427b7a67fc6
|
{
"intermediate": 0.35694029927253723,
"beginner": 0.4758523106575012,
"expert": 0.16720741987228394
}
|
8,446
|
根据以下json, 给出对应的javascript 类定义 :{
"table": "devicecurrentdata_view",
"rows":
[
{
"id": 4,
"socketIdentity": null,
"deviceIP": null,
"devicePort": null,
"batteryVolume": 85,
"voltage": 27.22000000,
"current": 2.31000000,
"latitude": 120.13400000,
"longitude": 133.77500000,
"position": 25,
"totalRunTime": null,
"totalRunDistance": null,
"runCount": null,
"workingStatus": 1,
"gatherTime": "2020-04-04 19:02:00",
"recordTime": "2023-04-20 10:16:00",
"areaId": 1,
"modelId": 1,
"modelType": 3
}
]
}
|
67c64888fddb711be39dadf31ff0bcda
|
{
"intermediate": 0.2983904778957367,
"beginner": 0.356391578912735,
"expert": 0.34521791338920593
}
|
8,447
|
I have data of temperature of the world from 1951 (71 years ago) for July and I want to forecast the data for 2060 (38 years later).
write the code for matlab for this problem. By using Ann model.
|
a674e41f3776a62d332ea138aa725556
|
{
"intermediate": 0.4630943536758423,
"beginner": 0.19330011308193207,
"expert": 0.34360548853874207
}
|
8,449
|
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
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
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
#Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
#Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
#No clear pattern
else:
return ''
df = getminutedata('BTCUSDT', '1m', '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, interval, lookback, max_trade_quantity_percentage):
MAX_TRADE_QUANTITY_PERCENTAGE = max_trade_quantity_percentage
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
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[i] == "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)
# Place short order if signal is the same
else:
order_quantity = min(max_trade_quantity, float(long_position['maxNotionalValue']) / leverage)
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[i] == "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)
# Place long order if signal is the same
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)
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
current_signal = signal_generator(df.signal.iloc[-1])
while True:
print(f"The signal time is: {current_time} :{current_signal}")
time.sleep(1) # Add a delay of 1 second
positions = client.futures_position_information(symbol='BTCUSDT')
current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") How I can print live signals with time.sleep(1) ?
|
c9c39f01a30667892dbf116a336517c1
|
{
"intermediate": 0.372067928314209,
"beginner": 0.3958898186683655,
"expert": 0.23204220831394196
}
|
8,450
|
In c++ write a code to get the cpu id using __asm__ __volatile__
|
9ddee945bf3b80ea1acf945555d27684
|
{
"intermediate": 0.26200148463249207,
"beginner": 0.37682729959487915,
"expert": 0.36117130517959595
}
|
8,451
|
get id(): string {
return this.vaults.id
}
|
5c3ef7901f2289ef747477f5b29d5bc5
|
{
"intermediate": 0.3880106806755066,
"beginner": 0.25986260175704956,
"expert": 0.35212668776512146
}
|
8,452
|
create user USER1 for login USER1 with password='123456' with default_schema = schema1
alter authorization on schema::schema1 to USER1
|
3b192db9760540a2816902723321f907
|
{
"intermediate": 0.35084742307662964,
"beginner": 0.26082131266593933,
"expert": 0.3883312940597534
}
|
8,453
|
write the code for matlab about this problem.
I have 72 rows of data in a matrix called "A" in one column. I know that data number 109 is equal to data 72 + 2, but I don't have the data between 72 and 109, now I want to predict this unknown data using LSTM neural network or ARIMA model.
|
f65230d040c93d67d4f8425316828122
|
{
"intermediate": 0.23294846713542938,
"beginner": 0.059571392834186554,
"expert": 0.7074801325798035
}
|
8,454
|
QGraphicsScene how to delete item after removeItem
|
3def0c69095c18972d0247e0070a7c4e
|
{
"intermediate": 0.35853737592697144,
"beginner": 0.3408450186252594,
"expert": 0.30061766505241394
}
|
8,455
|
what type hint use for json in python? Json can storage dict or list of values.
|
e2c0cad9ad45e355834c78210cc71fcf
|
{
"intermediate": 0.5774147510528564,
"beginner": 0.15940618515014648,
"expert": 0.2631790339946747
}
|
8,456
|
what means Field(...) here foo_bar: FooBar = Field(...)
|
55a3db629338adffa1e84b7083344e9d
|
{
"intermediate": 0.33433493971824646,
"beginner": 0.38668709993362427,
"expert": 0.2789779007434845
}
|
8,457
|
Write c code of encoder decoder for On–off keying
|
0db62dfd5d5ba34b64b05644a32dd029
|
{
"intermediate": 0.35822272300720215,
"beginner": 0.16750705242156982,
"expert": 0.47427019476890564
}
|
8,458
|
In c++ visual studio 2017, 64-bit, write a code to get the unique cpu id.
|
cca79565447f01b8b925b30ee958118e
|
{
"intermediate": 0.3179008960723877,
"beginner": 0.20845602452754974,
"expert": 0.47364306449890137
}
|
8,459
|
Given a SQLite database file path; write a python function that extract the schema of all table in the database and generate the PlantUML ERD.
|
5e8a4e85defea0ccc062ea5d27681ad3
|
{
"intermediate": 0.6073300838470459,
"beginner": 0.14968417584896088,
"expert": 0.24298568069934845
}
|
8,460
|
Multiply a vector with scalar with ranges in c++20
|
a35d2955628168c1d7dfd200953c2210
|
{
"intermediate": 0.4006519019603729,
"beginner": 0.2799087166786194,
"expert": 0.3194393515586853
}
|
8,461
|
In my AI chat. Only words and termins that user know and well understand them meaning (testing before chatting) will be used in conservation. Please provide me more wide list what I need to do from GUI for this
|
98b6a406f88241df075ce84f6c4baa89
|
{
"intermediate": 0.3599691689014435,
"beginner": 0.2163587212562561,
"expert": 0.4236721396446228
}
|
8,462
|
java code to display a 88 key piano keyboard as swing gui with pressable white and black keys in correct keyboard layout
|
37035112e8abc2daa3e114bd5e6df180
|
{
"intermediate": 0.4929691553115845,
"beginner": 0.15493068099021912,
"expert": 0.3521001636981964
}
|
8,463
|
how to make this sql querry order by
case when name like ‘O%’ then 0 else 1 end in C# entityframework
|
27f838eaf9539440df881aab68dd61d9
|
{
"intermediate": 0.5923351049423218,
"beginner": 0.285664826631546,
"expert": 0.12200017273426056
}
|
8,464
|
const [questionnaire, categories] = await prisma.$transaction([
prisma.questionnaire.findFirst({
orderBy: [{ startDate: "desc" }],
where: {
...filter,
approved: true,
disabled: false,
endDate: {
// gte: addDays(new Date(), -5), //previous code
gte: subDays(new Date(), 5), // return questionnaires with in the last 5 days of the current date
lte: new Date(),
},
startDate: {
// gte: subDays(new Date(), -5), // fetch records that are within 5 days range from current date
lte: new Date(),
},
isDraft: false,
},
include: {
questionnaireItems: {
where: {
disabled: false,
},
include: {
item: {
include: {
translation: true,
itemMeasurements: true,
},
},
},
},
questionnaireRegionStatus: {
where: { regionCode: { in: regionCodes } },
},
},
}),
prisma.division.findMany({
where: { disabled: false },
include: {
group: {
where: { disabled: false },
include: {
class: {
where: { disabled: false },
include: {
subclass: {
where: { disabled: false },
include: {
translation: true,
},
},
translation: true,
},
},
translation: true,
},
},
translation: true,
},
}),
]); update the code so that enddate and startdate takes endofday into considerations
|
a57fe4adf5a3ed2c49a88ecc45cb115a
|
{
"intermediate": 0.29516714811325073,
"beginner": 0.46180060505867004,
"expert": 0.24303220212459564
}
|
8,465
|
Write grammar for basic Go language which includes declaration, condition, loop etc. using bison in C
|
02b0ebf155bc9ddd385686d1e2e842eb
|
{
"intermediate": 0.1099041998386383,
"beginner": 0.8094256520271301,
"expert": 0.08067015558481216
}
|
8,466
|
python numpy function to calc angle betweent two vectors
|
7f3bc0f18e0e950ecaf7f31c4bb693d7
|
{
"intermediate": 0.43959105014801025,
"beginner": 0.2729288339614868,
"expert": 0.2874801754951477
}
|
8,467
|
i hev a list of name and id and i want to display in screen with this componenent <TouchableOpacity
onPress={onPress}
style={[styles.item]}
activeOpacity={0.5}>
<View style={styles.section}>
<Text style={{color: colors.secondary, marginRight: 10}}>{item}</Text>
<Arrow />
</View>
</TouchableOpacity>
<View style={{marginBottom: 1}}>{last ? null : <Separator />}</View>
|
e9dca8827c83d58f0c086bf6a554f17e
|
{
"intermediate": 0.4031314253807068,
"beginner": 0.20958879590034485,
"expert": 0.387279748916626
}
|
8,468
|
async function getMovieList(year) {
const response= await fetch(`https://jsonmock.hackerrank.com/api/movies?Year=${year}`);
const data = await response.json();
const movieList= data.data.map(movie=>movie.Title);
return movieList
}
async function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const year = readLine().trim();
const results = await getMovieList(year);
if (results.length > 0) {
for (const result of results) {
ws.write(`${result}\n`);
}
} else {
ws.write('No Results Found');
}
ws.end();
}
why above code give this error
(node:207773) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
node:internal/deps/undici/undici:4045
if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
^
TypeError: Cannot read properties of undefined (reading 'timeoutType')
at _resume (node:internal/deps/undici/undici:4045:33)
at resume (node:internal/deps/undici/undici:4015:7)
at connect (node:internal/deps/undici/undici:4004:7)
Node.js v18.6.0
|
a45c7509bbdd8bbeec80202160b96af6
|
{
"intermediate": 0.5498619079589844,
"beginner": 0.2462674081325531,
"expert": 0.20387066900730133
}
|
8,469
|
Переделай данный код из движка Godot 3.3 под код для движка Godot 4.0 используя его официальную документацию:
var from = global_transform.origin
var to = global_transform.origin - global_transform.basis.z.normalized() * 2.0
var space_state = get_world().direct_space_state
var collision = space_state.intersect_ray(from, to, [owner], 1)
|
e5744d7a2a9c127f22156568b2142f30
|
{
"intermediate": 0.3672020435333252,
"beginner": 0.32173505425453186,
"expert": 0.31106287240982056
}
|
8,470
|
Laravel 10. i have custom s3 service connected and users can upload/view/download files with no problem. Problem is - i need to limit amount of user interactions in total (not per user) for all users to 400 per second. How can i arrange it? Queue, jobs, whatever welcome.
|
f7767890a60b4889b066b6485fe29e50
|
{
"intermediate": 0.445605993270874,
"beginner": 0.26336556673049927,
"expert": 0.2910284698009491
}
|
8,471
|
const [questionnaire, categories] = await prisma.$transaction([
prisma.questionnaire.findFirst({
orderBy: [{ startDate: "desc" }],
where: {
...filter,
approved: true,
disabled: false,
endDate: {
// gte: addDays(new Date(), -5), //previous code
gte: startOfDay(endOfDay(subDays(new Date(), 5))), // return questionnaires with in the last 5 days of the current date
lte: new Date(),
},
startDate: {
// gte: subDays(new Date(), -5), // fetch records that are within 5 days range from current date
lte: new Date(),
},
isDraft: false,
},
include: {
questionnaireItems: {
where: {
disabled: false,
},
include: {
item: {
include: {
translation: true,
itemMeasurements: true,
},
},
},
},
questionnaireRegionStatus: {
where: { regionCode: { in: regionCodes } },
},
},
}),
prisma.division.findMany({
where: { disabled: false },
include: {
group: {
where: { disabled: false },
include: {
class: {
where: { disabled: false },
include: {
subclass: {
where: { disabled: false },
include: {
translation: true,
},
},
translation: true,
},
},
translation: true,
},
},
translation: true,
},
}),
]); how can i modify the query so that the startdate is below the endDate And also endDate should also fetch questionnaires that have not yet expired meaning if endDate is greater than current day it hasnt expired
|
ee4def49c587ad71a4aef7246efe1493
|
{
"intermediate": 0.36083030700683594,
"beginner": 0.5078063011169434,
"expert": 0.13136336207389832
}
|
8,472
|
To include questionnaires that have not yet expired, you can modify the endDate check as follows:
const questionnaire = await prisma.questionnaire.findFirst({
where: {
id: 123,
disabled: false,
approved: true,
isDraft: false,
startDate: {
lte: new Date(),
},
endDate: {
gte: new Date(),
},
},
});
if (questionnaire || (questionnaire && questionnaire.endDate == new Date())) {
// The questionnaire is active
} else {
// The questionnaire is not active
}
This change will include questionnaires that have not yet expired by adding an OR condition that checks if the endDate is equal to the current date. If the endDate is equal to the current date, the questionnaire is still considered active, so the if block will execute. If the endDate is in the future and the if block doesn’t execute, the questionnaire is not considered active.
Based on the above solution convert the below code const [questionnaire, categories] = await prisma.$transaction([
prisma.questionnaire.findFirst({
orderBy: [{ startDate: "desc" }],
where: {
...filter,
approved: true,
disabled: false,
endDate: {
// gte: addDays(new Date(), -5), //previous code
// gte: addDays(new Date(), -5), // return questionnaires with in the last 5 days of the current date
gte: new Date(),
},
startDate: {
// gte: subDays(new Date(), -5), // fetch records that are within 5 days range from current date
lte: new Date(),
},
isDraft: false,
},
include: {
questionnaireItems: {
where: {
disabled: false,
},
include: {
item: {
include: {
translation: true,
itemMeasurements: true,
},
},
},
},
questionnaireRegionStatus: {
where: { regionCode: { in: regionCodes } },
},
},
}),
prisma.division.findMany({
where: { disabled: false },
include: {
group: {
where: { disabled: false },
include: {
class: {
where: { disabled: false },
include: {
subclass: {
where: { disabled: false },
include: {
translation: true,
},
},
translation: true,
},
},
translation: true,
},
},
translation: true,
},
}),
]);
|
60f9c9c52bb6cf587418b3301d970b5c
|
{
"intermediate": 0.3606574237346649,
"beginner": 0.4170224666595459,
"expert": 0.22232015430927277
}
|
8,473
|
document.createElement options как использовать
|
1c59c3ee7ce373f01ce1a68052ee6a52
|
{
"intermediate": 0.3815859258174896,
"beginner": 0.2455781102180481,
"expert": 0.3728359341621399
}
|
8,474
|
endDate: {
// gte: addDays(new Date(), -5), //previous code
// gte: addDays(new Date(), -5), // return questionnaires with in the last 5 days of the current date]
gte: new Date(),
OR: [
{
equals: new Date(),
},
],
}, throwing Type '{ gte: Date; OR: { equals: Date; }[]; }' is not assignable to type 'string | DateTimeFilter | Date | undefined'.
Object literal may only specify known properties, and 'OR' does not exist in type 'DateTimeFilter | Date'.ts(2322)
|
33eff7900e849d0ed7c3d7def7d6bf50
|
{
"intermediate": 0.36483892798423767,
"beginner": 0.41776037216186523,
"expert": 0.2174006849527359
}
|
8,475
|
hi
|
1e694a58d5245595d8b243b29e8fcd6c
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
8,476
|
Laravel how can I make controller execute one at a time? So if user1 execute controller action, second user should wait
|
2f621a82c57b3b09b710c96b7efc9233
|
{
"intermediate": 0.2959178388118744,
"beginner": 0.0789785161614418,
"expert": 0.6251035928726196
}
|
8,477
|
function plusMinus(arr) {
let positive=0;
let negative=0;
let nullish=0;
for(let i =0;i<=arr.length;i++){
if(arr[i]>0) positive++;
if(arr[i]<0) negative++;
if(arr[i]===0) nullish++;
}
const positiveRatios=(positive/arr.length).toFixed(6)
const negativeRatios=(negative/arr.length).toFixed(6)
const nullishRatios=(nullish/arr.length).toFixed(6)
return {positiveRatios,negativeRatios,nullishRatios}
}
Function Description
Complete the plusMinus function in the editor below.
plusMinus has the following parameter(s):
int arr[n]: an array of integers
Print
Print the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with digits after the decimal. The function should not return a value.
Input Format
The first line contains an integer, , the size of the array.
The second line contains space-separated integers that describe .
Constraints
Output Format
Print the following lines, each to decimals:
proportion of positive values
proportion of negative values
proportion of zeros
|
085dce665e26c62d8db008cba86e946d
|
{
"intermediate": 0.40247783064842224,
"beginner": 0.332935631275177,
"expert": 0.26458656787872314
}
|
8,478
|
make a code to unify a google sreedsheet to an google forms
|
3c8af072da4a2b9aa2a48d311aaa5b3e
|
{
"intermediate": 0.45235270261764526,
"beginner": 0.1772889941930771,
"expert": 0.37035831809043884
}
|
8,479
|
i have two array of type interface SelectAnagMagistratoOption {
key: string
nome: string
cognome: string
grado: number
tipoMag: string
}
one named pippo and one pluto
i want to remove all the element from pippo that are in pluto filtering by key
|
8a460d4e058a95e8156be478ba0de2d0
|
{
"intermediate": 0.4850727915763855,
"beginner": 0.18622075021266937,
"expert": 0.32870644330978394
}
|
8,480
|
const ScreenerPage: NextPage = () => {
const {diaryToken} = useAuthContext();
const {selectedSingleApiKey} = useApiKeyProvider();
const [pages, setPages] = useState<"positions" | "orders" | "history">("orders");
const [accountInfo, setAccountInfo] = useState<Account | undefined>(undefined);
return <>
<Head>
<title>Скринер</title>
</Head>
<CabinetAlgoTradingHead />
<Grid sx={{backgroundColor: "#ECECEC"}} container spacing={1} height={999} p={1}>
<Grid item xs={1.7}>
<Box sx={{width: "100%", height: "100%"}}>
<ScreenerSymbols />
<AssetsBuySell />
</Box>
</Grid>
<Grid item xs={1.35} height="100%">
<Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: "100%", width: "100%", bgcolor: "#fff", borderRadius: "8px"}}>
<TradingCup />
</Box>
</Grid>
<Grid item xs={8.95}>
<ScreenerCharts />
<Grid container sx={{width: "100%", height: 256, mt: "4px", bgcolor: "#fff", borderRadius: "8px", display: "flex", alignContent: "flex-start"}}>
</Grid>
</Grid>
</Grid>
</>;
};
1. - нужно обернуть в import RGL, {WidthProvider, Layout} from "react-grid-layout";
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";
<Box maxWidth="100%" >
<ReactGridLayout
cols={30}
layout={layout}
onDragStop={}
onResizeStop={}
isDraggable={draggable}
rowHeight={40}
width={1200}
>
</ReactGridLayout>
</Box>
2. - 5 блоков нужно, чтобы было, которым можно изменять размер и перетаскивать
первый блок - <ScreenerSymbols />
второй блок - <AssetsBuySell />
третий блок - <Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: "100%", width: "100%", bgcolor: "#fff", borderRadius: "8px"}}>
<TradingCup />
</Box>
четвертый блок - <ScreenerCharts />
пятый блок - <Grid container sx={{width: "100%", height: 256, mt: "4px", bgcolor: "#fff", borderRadius: "8px", display: "flex", alignContent: "flex-start"}}> </Grid>
react typescript
|
ecb89813071284bb4adb5db62c81f17d
|
{
"intermediate": 0.4437636435031891,
"beginner": 0.4112638831138611,
"expert": 0.14497242867946625
}
|
8,481
|
const ScreenerPage: NextPage = () => {
const {diaryToken} = useAuthContext();
const {selectedSingleApiKey} = useApiKeyProvider();
const [pages, setPages] = useState<"positions" | "orders" | "history">("orders");
const [accountInfo, setAccountInfo] = useState<Account | undefined>(undefined);
return <>
<Head>
<title>Скринер</title>
</Head>
<CabinetAlgoTradingHead />
<Grid sx={{backgroundColor: "#ECECEC"}} container spacing={1} height={999} p={1}>
<Grid item xs={1.7}>
<Box sx={{width: "100%", height: "100%"}}>
<ScreenerSymbols />
<AssetsBuySell />
</Box>
</Grid>
<Grid item xs={1.35} height="100%">
<Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: "100%", width: "100%", bgcolor: "#fff", borderRadius: "8px"}}>
<TradingCup />
</Box>
</Grid>
<Grid item xs={8.95}>
<ScreenerCharts />
<Grid container sx={{width: "100%", height: 256, mt: "4px", bgcolor: "#fff", borderRadius: "8px", display: "flex", alignContent: "flex-start"}}>
</Grid>
</Grid>
</Grid>
</>;
};
1. - нужно обернуть в import RGL, {WidthProvider, Layout} from "react-grid-layout";
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";
<Box maxWidth="100%" >
<ReactGridLayout
cols={30}
layout={layout}
onDragStop={}
onResizeStop={}
isDraggable={draggable}
rowHeight={40}
width={1200}
>
</ReactGridLayout>
</Box>
2. - 5 блоков нужно, чтобы было, которым можно изменять размер и перетаскивать, ИЗМЕНЯТЬ РАЗМЕР ТОЖЕ НУЖНО, КАК И ПЕРЕТАСКИВАТЬ
первый блок - <ScreenerSymbols />
второй блок - <AssetsBuySell />
третий блок - <Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: "100%", width: "100%", bgcolor: "#fff", borderRadius: "8px"}}>
<TradingCup />
</Box>
четвертый блок - <ScreenerCharts />
пятый блок - <Grid container sx={{width: "100%", height: 256, mt: "4px", bgcolor: "#fff", borderRadius: "8px", display: "flex", alignContent: "flex-start"}}> </Grid>
3. - размеры по умолчанию должны остаться такими, какие сейчас в примере
react typescript
|
14ec8a8b65ea161c2bc59016a1054b08
|
{
"intermediate": 0.3345731794834137,
"beginner": 0.5701154470443726,
"expert": 0.09531140327453613
}
|
8,482
|
const ScreenerPage: NextPage = () => {
const {diaryToken} = useAuthContext();
const {selectedSingleApiKey} = useApiKeyProvider();
const [pages, setPages] = useState<"positions" | "orders" | "history">("orders");
const [accountInfo, setAccountInfo] = useState<Account | undefined>(undefined);
return <>
<Head>
<title>Скринер</title>
</Head>
<CabinetAlgoTradingHead />
<Grid sx={{backgroundColor: "#ECECEC"}} container spacing={1} height={999} p={1}>
<Grid item xs={1.7}>
<Box sx={{width: "100%", height: "100%"}}>
<ScreenerSymbols />
<AssetsBuySell />
</Box>
</Grid>
<Grid item xs={1.35} height="100%">
<Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: "100%", width: "100%", bgcolor: "#fff", borderRadius: "8px"}}>
<TradingCup />
</Box>
</Grid>
<Grid item xs={8.95}>
<ScreenerCharts />
<Grid container sx={{width: "100%", height: 256, mt: "4px", bgcolor: "#fff", borderRadius: "8px", display: "flex", alignContent: "flex-start"}}>
</Grid>
</Grid>
</Grid>
</>;
};
1. - нужно обернуть в import RGL, {WidthProvider, Layout} from "react-grid-layout";
import "react-grid-layout/css/styles.css";
import "react-resizable/css/styles.css";
<Box maxWidth="100%" >
<ReactGridLayout
cols={30}
layout={layout}
onDragStop={}
onResizeStop={}
isDraggable={draggable}
rowHeight={40}
width={1200}
>
</ReactGridLayout>
</Box>
2. - 5 блоков нужно, чтобы было, которым можно изменять размер и перетаскивать, ИЗМЕНЯТЬ РАЗМЕР ТОЖЕ НУЖНО, КАК И ПЕРЕТАСКИВАТЬ
первый блок - <ScreenerSymbols />
второй блок - <AssetsBuySell />
третий блок - <Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: "100%", width: "100%", bgcolor: "#fff", borderRadius: "8px"}}>
<TradingCup />
</Box>
четвертый блок - <ScreenerCharts />
пятый блок - <Grid container sx={{width: "100%", height: 256, mt: "4px", bgcolor: "#fff", borderRadius: "8px", display: "flex", alignContent: "flex-start"}}> </Grid>
3. - размеры по умолчанию должны остаться такими, какие сейчас в примере
react typescript
|
ad7414eaa9d13bdf2a427e21a733e931
|
{
"intermediate": 0.3345731794834137,
"beginner": 0.5701154470443726,
"expert": 0.09531140327453613
}
|
8,483
|
Create a confluence document that lists all the steps to update an angular application from v13 to v16
|
a1a1c35768dee9ff127bb28c756b2e9d
|
{
"intermediate": 0.4522010087966919,
"beginner": 0.20013469457626343,
"expert": 0.3476642668247223
}
|
8,484
|
Change the code below so that instead of entering a single block value, you can specify an interval
# Возращает адреса созданных токенов в одном блоке
import requests
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
def get_external_transactions(block_number):
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}'
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f'Error in API request: {e}')
return []
data = response.json()
if data['result'] is None:
print(f"Error: Cannot find the block")
return []
return data['result']['transactions']
def get_contract_address(tx_hash):
url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}'
try:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f'Error in API request: {e}')
return None
data = response.json()
if data['result'] is None:
return None
return data['result']['contractAddress']
def get_contract_name(contract_address):
method_signature = '0x06fdde03' # Keccak256 hash of the “name()” function signature
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:
response = requests.get(url)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f'Error in API request: {e}')
return None
data = response.json()
if data['result'] is None or data['result'][:2] == '0x':
return None
return bytes.fromhex(data['result'][2:]).decode('utf-8')
def display_transactions(block_number):
transactions = get_external_transactions(block_number)
if not transactions:
print('No transactions found.')
else:
print(f'Transactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
contract_address = get_contract_address(tx['hash'])
contract_name = get_contract_name(contract_address)
print(f"New contract creation: Contract Address: {contract_address} - Contract Name: {contract_name}")
block_number_int = 28523871
block_number = hex(28523871) # Replace with your desired block number (hexadecimal value)
display_transactions(block_number)
|
e72f66b715205f0d05f42760cc7a3d91
|
{
"intermediate": 0.29258430004119873,
"beginner": 0.43927299976348877,
"expert": 0.2681426703929901
}
|
8,485
|
grant IMPERSONATE on user::DBA to USER2; sql server complain Cannot find the user 'DBA', because it does not exist or you do not have permission.
|
5ecf3130103f429f21895aca470751fc
|
{
"intermediate": 0.3784603476524353,
"beginner": 0.22850753366947174,
"expert": 0.39303213357925415
}
|
8,486
|
I need a vba code that will open a Google Chrome web Page and go to this url, https://docs.google.com/spreadsheets/d/1EwbPXiLxGx-26Qdr_MERRxTrIJVeM6pNLDtGpAdlnKI/edit#gid=0
|
98f35a24153675355b52356b87d34e1f
|
{
"intermediate": 0.29894521832466125,
"beginner": 0.2264990210533142,
"expert": 0.47455576062202454
}
|
8,487
|
Where is issue in this code? 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 = 'Y0ReOvKcXm8e3wfIRYlgcdV9UG10M7XqxsGV0H83S8OMH3H3Fym3iqsfIcHDiq92'
API_SECRET = '0u8aMxMXyIy9dQCti8m4AOeSvAGEqugOiIDML4rxVWDx5dzI80TDGNCMOWn4geVg'
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
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', '1m', '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, interval, lookback, max_trade_quantity_percentage):
MAX_TRADE_QUANTITY_PERCENTAGE = max_trade_quantity_percentage
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
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[i] == "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)
# Place short order if signal is the same
else:
order_quantity = min(max_trade_quantity, float(long_position['maxNotionalValue']) / leverage)
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[i] == "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)
# Place long order if signal is the same
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}")
time.sleep(1) # Add a delay of 1 second
|
8f61b49da4a9dac05eb4c25a80db57b0
|
{
"intermediate": 0.4189985990524292,
"beginner": 0.39821821451187134,
"expert": 0.18278324604034424
}
|
8,488
|
async getQuotations(req: Request, res: Response, next: NextFunction) {
try {
const query: any = req.query;
const regionCodeOrCodes = await getRegionCodeOrCodes(req.user!);
const regionalStatusFilter =
getQuestionnaireRegionalStatusFilter(regionCodeOrCodes);
const questionnaire = await prisma.questionnaire.findFirst({
orderBy: [{ startDate: "desc" }],
where: {
designatedRole: rolesNum["DATA COLLECTOR"],
approved: true,
disabled: false,
endDate: {
gte: addDays(new Date(), -5),
},
startDate: {
lte: new Date(),
},
isDraft: false,
},
include: {
questionnaireItems: {
where: {
disabled: false,
},
include: {
item: {
include: {
translation: true,
itemMeasurements: true,
},
},
},
},
questionnaireRegionStatus: {
where: regionalStatusFilter,
},
},
});
const datacollectors = await prisma.user.findMany({
where:
req.user?.role === rolesNum.SUPERVISOR
? {
supervisorId: req.user?.id,
}
: { marketplace: { branchCode: req.user?.branchCode } },
});
if (
req.user?.role === rolesNum.SUPERVISOR &&
(!datacollectors || datacollectors.length < 1)
) {
return res
.status(httpStatusCodes.NOT_FOUND)
.json(
new ResponseJSON(
"Supervisor is not assigned any data collectors",
true,
httpStatusCodes.NOT_FOUND
)
);
}
if (!questionnaire) {
return res
.status(httpStatusCodes.NOT_FOUND)
.json(
new ResponseJSON(
"Not Questionnaires active right now",
true,
httpStatusCodes.NOT_FOUND
)
);
}
const result = await prisma.quotation.findMany({
where: {
questionnaireId: questionnaire?.id,
collectorId: {
in: datacollectors.map((el) => el.id),
},
...query,
},
include: {
collector: {
select: {
fullName: true,
id: true,
marketplaceCode: true,
},
},
quotes: {
include: {
quoteComments: true,
},
},
unfoundQuotes: {
include: {
quoteComments: true,
},
},
},
});
return res
.status(httpStatusCodes.OK)
.json(new ResponseJSON("Success", false, httpStatusCodes.OK, result));
} catch (error: any) {
console.log("Error --- ", error);
next(
apiErrorHandler(
error,
req,
errorMessages.INTERNAL_SERVER,
httpStatusCodes.INTERNAL_SERVER
)
);
}
} explain the above code
|
21bd0bcfa4d0695af7d3340a989c4ee1
|
{
"intermediate": 0.3394429087638855,
"beginner": 0.5048453211784363,
"expert": 0.15571175515651703
}
|
8,489
|
hi
|
f48385adb5e9d363583ed6876528d896
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
8,490
|
How I can set this problem ? File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 108
else:
^^^^
SyntaxError: invalid syntax , Give me example code as solution
|
ce5bf089e46c9fd4835b1ad271c55c00
|
{
"intermediate": 0.4377700388431549,
"beginner": 0.37205204367637634,
"expert": 0.19017794728279114
}
|
8,491
|
I have a few images that has some random letters and numbers (total length is 5).
white background and black text.
each image contains a single horizontal line that goes randomly through or under or above the text, the line has some random curve.
I want to remove that line from each of the images in C#.
|
f7882b0e2e03405d414f053fc45076c9
|
{
"intermediate": 0.3117925822734833,
"beginner": 0.2773205637931824,
"expert": 0.41088688373565674
}
|
8,492
|
how to get token login ID for google account login?
|
512d357305eabaaaf6035d1d43c19fc8
|
{
"intermediate": 0.36781543493270874,
"beginner": 0.27246204018592834,
"expert": 0.3597225546836853
}
|
8,493
|
hey is it possible to login some websites with only cookies ?
|
8598e16272d70b61a87e5950b7d25d64
|
{
"intermediate": 0.4180966317653656,
"beginner": 0.27129751443862915,
"expert": 0.31060585379600525
}
|
8,494
|
what does "n" param in openai.complete(params)
|
46a8b32c1d1fc111ca42c389b87bee93
|
{
"intermediate": 0.3898283839225769,
"beginner": 0.19895930588245392,
"expert": 0.41121232509613037
}
|
8,495
|
how to make function like Object.keys but returning array with proper types instead of string[]
|
b80c068e23719502037f59fd3208e454
|
{
"intermediate": 0.39138999581336975,
"beginner": 0.3440576493740082,
"expert": 0.26455238461494446
}
|
8,496
|
I have a table in Oracle SQL, lets call it table1. in it, i have a field called id which is a primary key. i also have another table, lets call it table2. in it, i have a foreign key called fk1 which references the id field from table1. how can i modify the definition of this foreign key so that when deleting a record from table1, automatically deletes related records from table2? this is an operation which is supposed to take two ‘ALTER TABLE’ statements
|
a38ecad846dff82ddb489b2c18a1d6ef
|
{
"intermediate": 0.5217491388320923,
"beginner": 0.1592857390642166,
"expert": 0.3189650774002075
}
|
8,497
|
what is dbo and why can i grant impersonate ti another user
|
dfdf4e09b57bdcf0817d9fea75869d6a
|
{
"intermediate": 0.4073334336280823,
"beginner": 0.13363154232501984,
"expert": 0.4590350389480591
}
|
8,498
|
Write python program for this:
Example 1
Input string:
do do decl tirele is{ 'bigeso' .'esla' }. done, do decl investment_937 is
{ 'bevela' . 'rela' . 'arla' . 'laan_577'}. done,do decl mabe_833 is {
'bearer' . 'ancar'. 'usdi_86'. 'teadira_966' }. done, done
Parsed result:
{'tirele': ['bigeso', 'esla'],
'inveso_937': ['bevela', 'rela', 'arla', 'laan_577'],
'mabe_833': ['bearer', 'ancear', 'usdi_86', 'teadira_966']}
Example 2
Input string:
do do decl usce is { 'arala_977' .'edbe'. 'mabe_990' }. done, do decl
atbian is {'arrius' . 'vezala_775' }. done, done
Parsed result:
{'usce': ['arala_977', 'edbe', 'mabe_990'],
'atbian': ['arrius', 'vezala_775']}
|
51563fb707200d1c4b35b76e172979b7
|
{
"intermediate": 0.34125185012817383,
"beginner": 0.29366812109947205,
"expert": 0.36507996916770935
}
|
8,499
|
Write me a Python function with docstrings that uses Gittins Index to solve a Multi-arm bandit problem for stock picking
|
c12fdc8465ac0ad481f4a8eeeda1525a
|
{
"intermediate": 0.4208977520465851,
"beginner": 0.21972519159317017,
"expert": 0.35937702655792236
}
|
8,500
|
Change the code below so that it sends requests and receives responses even faster than it does now. The functionality of the code should not change
# Возращает адреса созданных токенов в указанном интревале блоков!!!
import asyncio
import requests
import aiohttp
bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS'
# Modify the existing functions to use async and aiohttp…
async def get_external_transactions(block_number):
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:
print(f"Error: Cannot find the block")
return []
return data['result']['transactions']
async def get_contract_address(tx_hash):
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:
return None
return data['result']['contractAddress']
async def get_contract_name(contract_address):
async with aiohttp.ClientSession() as session:
method_signature = '0x06fdde03'
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
if not data.get('result') or data['result'][:2] == '0x':
return None
return bytes.fromhex(data['result'][2:]).decode('utf - 8')
async def display_transactions(block_start, block_end):
for block_number_int in range(block_start, block_end + 1):
block_number = hex(block_number_int)
transactions = await get_external_transactions(block_number) # Add the ‘await’ keyword here
if not transactions:
print(f'No transactions found in block {block_number_int}')
else:
print(f'ransactions in block {block_number_int}:')
for tx in transactions:
if tx['to'] is None:
contract_address = await get_contract_address(tx['hash'])
contract_name = await get_contract_name(contract_address)
print(f"New contract creation: Contract Address: {contract_address} - Contract Name: {contract_name}")
print("\n") # Print an empty line between blocks
async def main():
block_start = 28524001 # Replace with your desired starting block number
block_end = 28525888 # Replace with your desired ending block number
await display_transactions(block_start, block_end)
asyncio.run(main())
|
b32dcbe5547c0448fe50f42eba99d89d
|
{
"intermediate": 0.3563995063304901,
"beginner": 0.5206540822982788,
"expert": 0.12294647842645645
}
|
8,501
|
Can you share the code to create a modal with a form which has a number and string field with validations which shows up upon button click in javascript
|
dd2e2282831f4ed245fb9aff9f44d1bc
|
{
"intermediate": 0.5631187558174133,
"beginner": 0.09318342804908752,
"expert": 0.34369781613349915
}
|
8,502
|
how can i make a bot to send a message in a group in wolf.live using this api: "https://github.com/calico-crusade/WolfLive.Api", given that i already have the ID of said group.
|
ae46e29120a1a0309b3dd47f700c1756
|
{
"intermediate": 0.6401842832565308,
"beginner": 0.13651709258556366,
"expert": 0.223298579454422
}
|
8,503
|
gptparser.tab.c:158:13: error: conflicting types for ‘YYSTYPE’; have ‘int’
158 | typedef int YYSTYPE;
| ^~~~~~~
gptparser.y:8:3: note: previous declaration of ‘YYSTYPE’ with type ‘YYSTYPE’
8 | } YYSTYPE;
|
4b69a2cd2fd2fcf6465ff4c75018f25c
|
{
"intermediate": 0.35847795009613037,
"beginner": 0.33045271039009094,
"expert": 0.3110692799091339
}
|
8,504
|
const datacollectors = await prisma.user.findMany({
where:
req.user?.role === rolesNum.SUPERVISOR
? {
supervisorId: req.user?.id,
}
: { marketplace: { branchCode: req.user?.branchCode } },
}); const result = await prisma.quotation.findMany({
where: {
questionnaireId: questionnaire?.id,
collectorId: {
in: datacollectors.map((el) => el.id),
},
...query,
},
include: {
collector: {
select: {
fullName: true,
id: true,
marketplaceCode: true,
},
},
quotes: {
include: {
quoteComments: true,
},
},
unfoundQuotes: {
include: {
quoteComments: true,
},
},
},
}); what does the above code do
|
b369eee0f3a3784ad2dcc50420f8a027
|
{
"intermediate": 0.31029012799263,
"beginner": 0.3822210133075714,
"expert": 0.3074888288974762
}
|
8,505
|
как с помощью js скопировать svg элемент, чтобы можно было его просто нажав ctrl+v добавить в фигму?
пример svg элемента:
<svg width=“100” height=“100” viewBox=“0 0 100 100” fill=“none” xmlns=“http://www.w3.org/2000/svg”>
<rect width=“100” height=“100” fill=“#D9D9D9”/>
</svg>
|
9638e1dd65467b1738f3e4b576f0ca59
|
{
"intermediate": 0.3183837831020355,
"beginner": 0.31608495116233826,
"expert": 0.3655312657356262
}
|
8,506
|
How to get rich from nothing
|
3e996b700ae25b1dec41cdd91c905172
|
{
"intermediate": 0.342683881521225,
"beginner": 0.3609428107738495,
"expert": 0.2963733375072479
}
|
8,507
|
i need to send bulk sms from this code in nodejs
const from = VONAGE_BRAND_NAME
const to = TO_NUMBER
const text = 'A text message sent using the Vonage SMS API'
async function sendSMS() {
await vonage.sms.send({to, from, text})
.then(resp => { console.log('Message sent successfully'); console.log(resp); })
.catch(err => { console.log('There was an error sending the messages.'); console.error(err); });
}
sendSMS();
|
8d8ee9f3f69ff8157e255318242dabdd
|
{
"intermediate": 0.4681973457336426,
"beginner": 0.3646605908870697,
"expert": 0.1671420931816101
}
|
8,508
|
Create me a json format in markdown block code with the given ruleset:
Ruleset:
The list should include 20 most commonly used ingredients in cooking. (e.g., apple, almond, avocado)
The ingredients MUST start with the letter "A." (e.g., apple, asparagus, almond)
Must Exclude finished products like sauces that consist of many ingredients. (e.g., exclude "barbecue sauce," "tomato sauce")
Must use more general categories rather than specific items. (e.g., use "vegetable" category for "cucumber," "fruit" category for "apple")
ONLY Include ingredients from the categories of fruit, vegetable, nut, grain, legume, spice, herb, meat, dairy, condiments and fat.
Must Focus on ingredients that are commonly used in everyday cooking. (e.g., apple, almond, avocado)
Must Avoid including ingredients that are too specific or less commonly used. (e.g., exclude "angel hair pasta," "artichoke hearts")
MUST not include duplicates or variations of the same ingredient that violate the ruleset.
MUST Include only pure ingredients and exclude mixed or processed items, except for cases like "almond milk" that serve as alternatives for specific dietary needs.
Example:
{
"name": "Almond",
"picture": "almond.jpg",
"category": "nut"
}
|
4c2acdbca86575df2be3fb1853efd389
|
{
"intermediate": 0.32416582107543945,
"beginner": 0.3003646731376648,
"expert": 0.375469446182251
}
|
8,509
|
Instructions for configuring ddclient V10.0.0 on raspberry pi and updating dynamic DNS to cloudflare domain
|
d6229b59455b7e85972ff0d9cad230dd
|
{
"intermediate": 0.3758432865142822,
"beginner": 0.24307918548583984,
"expert": 0.38107746839523315
}
|
8,510
|
i have a spring application but hibernate makes queries to database with table name in lowercase which naming strategy should i use to avoid that and that hibernate would use names like specified in @Table annotation?
|
c61f2699b31063e059225bcf26e97705
|
{
"intermediate": 0.5645396709442139,
"beginner": 0.177364319562912,
"expert": 0.25809600949287415
}
|
8,511
|
Write HTML, CSS and JavaScript for a fun and unique game where a user must enter a password according to a rule which changes every level. As the user progresses the rules get increasingly absurd and difficult to meet. At certain levels (milestones), the password box will gain [a] new feature(s) that must be used to meet rules in the future. Gradually the game should get incredibly difficult and insane. Include a minimum of 30 levels.
|
3623e0a79d9da29a0712832eae796d12
|
{
"intermediate": 0.3103606700897217,
"beginner": 0.43493664264678955,
"expert": 0.254702627658844
}
|
8,512
|
How can I configure my raspberry pi 4 as a dynamic DNS to update my cloudflare A record?
|
ce1cef7ea2c8db8acd67f238a95e55e9
|
{
"intermediate": 0.5188443064689636,
"beginner": 0.23060663044452667,
"expert": 0.2505490481853485
}
|
8,513
|
How can I configure cloudflare-ddns on my raspberry pi 4 as a dynamic DNS to update my cloudflare A record?
|
c6fd6299cd8469234d2dc65a018c7964
|
{
"intermediate": 0.5724327564239502,
"beginner": 0.23152098059654236,
"expert": 0.19604626297950745
}
|
8,514
|
Pine script for algo trading in bank nifty buy call and put using vortex indicator crossovers, risk to reward ratio of 1 :4 and a trailing stopp loss of 5 point for 20 point move
|
e8c5407841c776aedfeaba378680d7df
|
{
"intermediate": 0.21192452311515808,
"beginner": 0.11696691066026688,
"expert": 0.6711085438728333
}
|
8,515
|
I want to set up my raspberry pi 4 as a dynamic DNS to update my Cloudflare subdomain A record content with the updated IP. I am using zone API tokens and do not want to use the global api. Create a script to monitor IP address changes and then have that script push changes to the Cloudflare API.
|
501aa5b645be754dfad6da98a67963db
|
{
"intermediate": 0.65641850233078,
"beginner": 0.1583782136440277,
"expert": 0.18520325422286987
}
|
8,516
|
%{
#include <stdio.h>
#include <stdlib.h>
int yylex();
void yyerror(char const* s);
%}
%token IDENTIFIER
%token NUMBER
%token IF
%token ELSE
%token FOR
%token ADD
%token SUB
%token MUL
%token DIV
%token MOD
%token ASSIGN
%token EQ
%token LT
%token GT
%token LE
%token GE
%token NEQ
%token AND
%token OR
%token NOT
%token SEMICOLON
%token LPAREN
%token RPAREN
%token LBRACE
%token RBRACE
%start program
%%
program:
statements
;
statements:
statement SEMICOLON
| statements statement SEMICOLON
;
statement:
IDENTIFIER ASSIGN expression {
printf(“%d = %d\n”, $1, 3);
}
| 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 LPAREN IDENTIFIER ASSIGN expression SEMICOLON expression SEMICOLON IDENTIFIER ADD ASSIGN expression RPAREN LBRACE statements RBRACE {
printf("for loop\n");
}
;
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: %d\n”, 1); }
| LPAREN expression RPAREN {
$ = $2; }
;
%%
int main() {
yyparse();
return 0;
}
void yyerror(char const* s) {
fprintf(stderr, “%s\n”, s);
}
Modify this parser so it doesn’t say “syntax error” to this input
package main
import “fmt”
func main() {
var oddtotal int = 0;
fmt.Println(“List of odd Numbers from 1 to 10 are”)
for x := 1; x <= 10; x++ {
// if number is odd
if x%2 != 0 {
fmt.Print(x, “\t”)
oddtotal = oddtotal + x
}
}
fmt.Println("\nSum of odd Numbers from 1 to 10 = ",oddtotal)
}
|
ca9ad316a076ee8fae171a66004b254e
|
{
"intermediate": 0.1358359456062317,
"beginner": 0.7486011981964111,
"expert": 0.11556287854909897
}
|
8,517
|
Instructions for setting up a respberry pi 4 as a Dynamic DNS to update my cloudflare subdomain A record. I want to use cloudflare-python and use a cloudflare API token NOT the global API key. Assume I already have a cloudflare account, my zone API token name is TOKEN_NAME_DDNS, my zones API is abcdefghijklmnop, my top level domain is toplevel.domain, and the A record I want to update with my IP is ddns.toplevel.domain. The script should update cloudflare every 5 minutes
|
cdd53b9479db903ee735cf8609415b15
|
{
"intermediate": 0.4861133396625519,
"beginner": 0.2647560238838196,
"expert": 0.24913059175014496
}
|
8,518
|
Zuora workflow liquid logic to Apply Credit memo's to all invoice in old memo date order
|
e03e709080d6d255e22916f2a2155ca8
|
{
"intermediate": 0.5796459317207336,
"beginner": 0.14396996796131134,
"expert": 0.27638405561447144
}
|
8,519
|
Write me a python script that will take a youtube playlist as input, get a random video from it and print the URL of the video to stdout. The script should keep in state the already given videos, so it never gives a duplicate video. The state can be kept in a text file next to the script.
|
222bd65cacd3696cbaca92aa40ec28b0
|
{
"intermediate": 0.3638553023338318,
"beginner": 0.20952466130256653,
"expert": 0.4266200065612793
}
|
8,520
|
Fix tasks 5, 6 and 7: package transactions:
import org.apache.spark.rdd.RDD
import org.apache.spark.SparkContext
import java.util.Locale
import java.util.TimeZone
import java.text.SimpleDateFormat
@main def main(): Unit =
/*
* Let us start by setting up a Spark context which runs locally
* using two worker threads.
*
* Here we go:
*
*/
val sc = new SparkContext("local[2]", "transactions")
/*
* The following setting controls how ``verbose'' Spark is.
* Comment this out to see all debug messages.
* Warning: doing so may generate massive amount of debug info,
* and normal program output can be overwhelmed!
*/
sc.setLogLevel("WARN")
/*
* Next, let us set up our input.
*/
val path = "a02-transactions/data/"
/*
* After the path is configured, we need to set up the input
* files. This exercise has two input files.
*
*/
val filename_balances = path ++ "ACMEBank-simulated-balances-2013-12-31-end-of-day.txt"
val filename_transactions = path ++ "ACMEBank-simulated-transactions-from-2014-01-01-to-2014-12-31-inclusive.txt"
/*
* Let us now set up RDDs for the balances and transactions.
*
*/
val lines_balances : RDD[String] = sc.textFile(filename_balances)
val lines_transactions : RDD[String] = sc.textFile(filename_transactions)
/* The following requirement sanity-checks the number of lines in the files
* -- if this requirement fails you are in trouble.
*/
require(lines_balances.count() == 10000 &&
lines_transactions.count() == 1000000)
/*
* Now parse the balances to a more convenient RDD
* consisting of pairs (i,b) where i is an account identifier
* and b is the start-of-year balance (in euro cents).
*
*/
val balances : RDD[(String,Long)] =
lines_balances.map(line => { val ib = line.split(" +"); (ib(0),ib(1).toLong) } )
/*
* Next let us set up an RDD for the transcations. This requires
* a somewhat more intricate parser because we are converting the
* __timestamps__ given in UTC (Coordinated Universal Time) in the data
* into an internal binary representation as a Long, namely the number
* of milliseconds since January 1, 1970, 00:00:00:000 UTC.
*
*/
/*
* Set up a time stamp formatter using the Java date formatters.
* https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html
*/
val stamp_fmt = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss:SSS zzz", Locale.UK)
stamp_fmt.setTimeZone(TimeZone.getTimeZone("UTC"))
val start_inclusive_d = stamp_fmt.parse("Wed 01 Jan 2014 00:00:00:000 UTC")
// val end_exclusive_d = stamp_fmt.parse("Thu 01 Jan 2015 00:00:00:000 UTC")
val start_inclusive = start_inclusive_d.getTime() // first millisec in 2014
// val end_exclusive = end_exclusive_d.getTime() // first millisec in 2015
// val millis_2014 = end_exclusive - start_inclusive // # millisecs in 2014
/*
* Let us create a transaction RDD consisting of 4-tuples with the following
* structure:
*
* 1) the time stamp (a Long between 'start_inclusive' and 'end_exclusive')
* 2) the source account identifier (e.g. "A1234")
* 3) the target account identifier (e.g. "A1234")
* 4) the transferred amount (in euro cents)
*
*/
val stamp_len = "Wed 01 Jan 2014 00:00:00:000 UTC".length
val transactions : RDD[(Long,String,String,Long)] =
lines_transactions.map(line => {
val stamp = line.take(stamp_len)
val rest = line.drop(stamp_len+1).split(" +")
(stamp_fmt.parse(stamp).getTime(), // timestamp
rest(0), // source id
rest(1), // target id
rest(2).toLong // amount transferred
)
} )
/*
* Our input is now set up. Now it is time for you to step in!
*
*/
/*
* Task 1:
* Find the identifier of the account with the largest balance at
* end-of-day, December 31, 2013.
*
* Write the CODE that finds the identifier below.
* Once you have the VALUE of the identifier, save it in "transactionsSolutions.scala".
*
*/
val task1: String = balances.reduce((a, b) => if (a._2 > b._2) a else b)._1
println("OUTPUT: The identifier for Task 1 is \"%s\"".format(task1))
/*
* Task 2:
* Find the total volume (total amount of money
* transferred in all the transactions), in euro cents.
*
* Write the CODE that finds the volume below.
* Once you have the VALUE of the volume, save it in "transactionsSolutions.scala".
*
*/
val task2: Long = transactions.map(_._4).sum().toLong
println("OUTPUT: The volume for Task 2 is %d".format(task2))
/*
* Task 3:
* Find the identifier of the account with the largest balance at
* end-of-day, December 31, 2014.
*
* Write the CODE that finds the identifier below.
* Once you have the VALUE of the identifier, save it in "transactionsSolutions.scala".
*
* Hints: Key with account identifies, take union of initial balances
* and transactions. Reduce by key. Each transaction decreases
* the balance of the source account and increases the balance
* of the target account. All transactions have distinct time
* stamps.
*
*
*/
val initialBalances: RDD[(String, Long)] = balances.union(transactions.map(t => (t._2, 0L))).distinct()
val updatedBalances: RDD[(String, Long)] = transactions
.flatMap(t => Seq((t._2, -t._4), (t._3, t._4)))
.reduceByKey(_ + _)
val task3: String = initialBalances
.join(updatedBalances)
.mapValues(t => t._1 + t._2)
.reduce((a, b) => if (a._2 > b._2) a else b)
._1
println("OUTPUT: The identifier for Task 3 is \"%s\"".format(task3))
/*
* Task 4:
* Find the number of idle accounts (that is, accounts that do
* not take part in any transaction) in the year 2014.
*
* Write the CODE that finds the number of accounts below.
* Once you have the VALUE, save it in "transactionsSolutions.scala".
*
*/
val task4: Long = balances
.leftOuterJoin(transactions.flatMap(t => Seq((t._2, 1), (t._3, 1))))
.filter { case (_, (balance, transactions)) => balance > 0 && transactions.isEmpty }
.count()
println("OUTPUT: The number of accounts for Task 4 is %d".format(task4))
/*
* Task 5:
* The year 2014 can be partitioned into exactly 365*24 = 8760
* consecutive hours. Each hour lasts 3600000 milliseconds.
* That is, in terms of time stamps, the first hour of 2014 starts
* with the time stamp 1388534400000 and ends with the time
* stamp 1388537999999. The second hour of 2014 starts with the time
* stamp 1388538000000 and ends with the time stamp 1388541599999.
* And so forth, until we are at the last hour of 2014, which starts
* with the time stamp 1420066800000 and ends with the time stamp
* 1420070399999. Find the number of hours in 2014 during which the
* total volume of transactions is at least ten million euro
* (at least one billion euro cents).
*
* Write the CODE that finds the number of hours below.
* Once you have the VALUE, save it in "transactionsSolutions.scala".
*
*/
val task5: Long = transactions
.filter { case (_, _, _, amount) => amount >= 100000000 } // Filter transactions with at least one billion euro cents
.map { case (timestamp, _, _, _) => timestamp / 3600000 } // Map the timestamp to hours
.distinct() // Get distinct hours
.count() // Count the number of distinct hours
println("OUTPUT: The number of hours for Task 5 is %d".format(task5))
/*
* Task 6 (more challenging):
*
* Find the number of accounts whose balance is at least
* one million euro (one hundred million euro cents)
* at any time instant during the year 2014.
* Note that these time instants may be different for
* different accounts.
*
* Write the CODE that finds the number of accounts below.
* Once you have the VALUE, save it in "transactionsSolutions.scala".
*
* Hints: group by identifier (mind your memory!),
* order by timestamp. All transactions have distinct
* timestamps.
*
*/
val balancesMap: Map[String, Long] = balances.collect().toMap
val task6: Long = transactions
.flatMap { case (_, from, to, _) => Seq(from, to) } // Create a sequence of account identifiers
.distinct() // Get distinct account identifiers
.filter(account => balancesMap.getOrElse(account, 0L) >= 100000000) // Filter accounts with at least one million euro
.count() // Count the number of qualifying accounts
println("OUTPUT: The number of accounts for Task 6 is %d".format(task6))
/*
* Task 7 (more challenging):
*
* ACME Bank pays interest to its 10000 accounts using a
* fixed interest rate of 0.1% per annum. The basis
* for the annual interest calculation is the daily
* __minimum__ balance on each account.
* (The year 2014 partitions into exactly 365 consecutive
* days, each 86400000 milliseconds long; cf. Task 5.)
* That is, for each day, we find the minimum balance on each
* account during that day, and then sum these minimum balances
* over accounts to get the interest payment basis for the day.
* Finally we sum over the 365 days in 2014 to get the total
* annual basis for interest payment, in euro cents.
* (The actual payment that ACME Bank makes then, in aggregate,
* at end-of-year to its accounts is the annual basis times 0.1%
* divided by 365; this, however, need not concern us.)
* In determining the daily minimum balance at an account,
* observe that every transaction is timestamped so that it takes
* place during a unique day. That is, the accounts affected by
* the transaction both have two different balances during the day
* of the transaction. Namely, the balance before the transaction
* and after the transaction. The minimum of these two balances is
* the balance that contributes in the calculation of the daily minimum
* balance for the day of the transaction.
*
* Your task is to compute the annual basis for interest payment
* for the year 2014, in euro cents.
*
* Write the CODE that computes the basis below.
* Once you have the VALUE, save it in "transactionsSolutions.scala".
*
* Hint: all transactions have distinct timestamps.
*
*/
val task7: Long = transactions
.groupBy { case (timestamp, _, _, _) => timestamp / 86400000 } // Group transactions by day
.values // Get only the transaction values
.flatMap { dayTransactions =>
dayTransactions
.groupBy { case (_, account, _, _) => account } // Group transactions by account identifier
.values // Get only the transactions for each account
.map { accountTransactions =>
val minBalance = accountTransactions.map { case (_, _, _, balance) => balance }.min // Find the minimum balance for each account on the day
minBalance
}
}
.sum // Sum the minimum balances over the 365 days
.toLong
println("OUTPUT: The basis for Task 7 is %d".format(task7))
|
d25933beb76dae3d070f1fe0c28674b7
|
{
"intermediate": 0.3584275245666504,
"beginner": 0.36351683735847473,
"expert": 0.2780556380748749
}
|
8,521
|
can a python program be made to turn a image into a stereogram
|
ba0141f58a2bfbdaf1b4d795e7a8c26a
|
{
"intermediate": 0.3108423054218292,
"beginner": 0.1142156571149826,
"expert": 0.5749421119689941
}
|
8,522
|
Exercise 2
A parity check is one way of detecting errors in bytes that have been transmitted. Before sending the bytes, a decision is made that each byte must have an even number of ones (even parity) or an odd number of ones (odd parity). Any byte that is received with the wrong parity can then be identified as an error.
Write a program in the Brookshear machine code which determines whether the bit pattern stored in memory location A0 has even or odd parity and place the result in memory location B0:
• If the bit pattern in A0 has even parity, B0 should contain 00.
• If the bit pattern in A0 has odd parity, B0 should contain FF.
Here are some example inputs and the expected outputs
Value in memory location A0 before running the program Value in memory location B0 after running the program
35
(00110101 in binary) 00
(even parity as there are four 1’s in the bit pattern)
A8
(10101000 in binary) FF
(odd parity as there are three 1’s in the bit pattern)
00
(00000000 in binary) 00
(even parity as there are zero 1’s in the bit pattern, and zero is an even number)
There are several ways to solve this problem, but most solutions will require you to be able to:
• Use a bit mask to copy the bit in a particular position from a bit string, while setting the other bits to 0. For example, if you copy first bit in 10101000 and 00110101, you will get 10000000 and 00000000 respectively.
• Rotate the bits in a bit pattern so that the bit you want is in the last position.
For example, moving the first bit in 10000000 to get 00000001
It is possible to solve the problem without a loop, but most efficient solutions will use a loop to reduce the number of instructions and registers used.
|
ad6b4a0cd3d20a3f32a1ddbbd4d63e4e
|
{
"intermediate": 0.3497885763645172,
"beginner": 0.2710997760295868,
"expert": 0.37911170721054077
}
|
8,523
|
how do i use docker on a new project
|
7132c47aa9c001ba755730cf18f5790e
|
{
"intermediate": 0.5080152750015259,
"beginner": 0.13613934814929962,
"expert": 0.3558453917503357
}
|
8,524
|
i have an alertdialog in kotlin, with an ok button and a cancel button. how do i assign actions to these buttons - so that on clicking ok, it performs some tasks (e.g. run a function) and when cancelled, it just cancels?
|
3289799c4253417a88f09ba683e3998c
|
{
"intermediate": 0.5767629146575928,
"beginner": 0.1722889542579651,
"expert": 0.2509481906890869
}
|
8,525
|
%{
#include <stdio.h>
#include <stdlib.h>
int yylex();
void yyerror(char const* s);
%}
%token IDENTIFIER
%token NUMBER
%token IF
%token ELSE
%token FOR
%token ADD
%token SUB
%token MUL
%token DIV
%token MOD
%token ASSIGN
%token EQ
%token LT
%token GT
%token LE
%token GE
%token NEQ
%token AND
%token OR
%token NOT
%token SEMICOLON
%token LPAREN
%token RPAREN
%token LBRACE
%token RBRACE
%token PACKAGE MAIN IMPORT FUNC VAR PRINTLN_START PRINTLN_END PRINT_START PRINT_END
%token STRING_LITERAL
%token INT
%start program
%%
program:
package_declaration import_declaration func_declaration
;
package_declaration:
PACKAGE 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”);
}
| PRINTLN_START expression PRINTLN_END SEMICOLON {
printf(“println statement\n”);
}
| PRINT_START expression PRINT_END SEMICOLON {
printf(“print statement\n”);
}
IDENTIFIER ASSIGN expression {
printf(“%d = %d\n”, $1, 3);
}
| 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 LPAREN IDENTIFIER ASSIGN expression SEMICOLON expression SEMICOLON IDENTIFIER ADD ASSIGN expression RPAREN LBRACE statements RBRACE {
printf("for loop\n");
}
;
var_declaration:
VAR IDENTIFIER data_type ASSIGN expression
;
data_type:
INT
;
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: %d\n”, 1); }
| LPAREN expression RPAREN {
$ = $2; }
;
%%
int main() {
yyparse();
return 0;
}
void yyerror(char const* s) {
fprintf(stderr, “%s\n”, s);
}
gptparser.y: warning: shift/reduce conflict on token PRINTLN_START [-Wcounterexamples]
Example: • PRINTLN_START expression PRINTLN_END SEMICOLON
Shift derivation
statements
↳ 5: statement
↳ 9: • PRINTLN_START expression PRINTLN_END SEMICOLON
Reduce derivation
statements
↳ 6: statements statement
↳ 5: statement ↳ 9: PRINTLN_START expression PRINTLN_END SEMICOLON
↳ 7: ε •
|
5ed88d94ec39e0611c4a845e67f22966
|
{
"intermediate": 0.26886701583862305,
"beginner": 0.482776403427124,
"expert": 0.24835661053657532
}
|
8,526
|
How would I stop a python script I started with ./cloudflare_ddns.py
|
651d3175abfc561693a50a09304a795e
|
{
"intermediate": 0.397928386926651,
"beginner": 0.25566402077674866,
"expert": 0.34640759229660034
}
|
8,527
|
I ran this script
#!/usr/bin/env python3
import requests
import json
import time
from cloudflare import CloudFlare
# Set your Cloudflare API token and zone ID
api_token = ‘TOKEN_NAME_DDNS’
zone_id = ‘abcdefghijklmnop’
# Set the A record to update
a_record_name = ‘ddns.toplevel.domain’
# Create a new CloudFlare object
cf = CloudFlare(token=api_token)
# Get the current public IP address of the Pi
def get_ip():
return requests.get(‘https://api.ipify.org’).text
# Get the current IP address from CloudFlare
def get_current_ip():
records = cf.zones.dns_records.get(zone_id)
for record in records:
if record[‘name’] == a_record_name:
return record[‘content’]
# Update the A record with the current IP address
def update_ip():
current_ip = get_current_ip()
new_ip = get_ip()
if current_ip != new_ip:
print(f’Updating A record {a_record_name} to IP {new_ip}')
cf.zones.dns_records.put(
zone_id,
record_id,
data={
‘type’: ‘A’,
‘name’: a_record_name,
‘content’: new_ip,
‘proxied’: False,
}
)
# Get the record ID of the A record
record_id = None
records = cf.zones.dns_records.get(zone_id)
for record in records:
if record[‘name’] == a_record_name:
record_id = record[‘id’]
# Loop forever and update every 5 minutes
while True:
update_ip()
time.sleep(300)
and got these errors
./cloudflare_ddns.py: line 8: import: command not found
./cloudflare_ddns.py: line 9: import: command not found
./cloudflare_ddns.py: line 10: import: command not found
./cloudflare_ddns.py: line 11: from: command not found
./cloudflare_ddns.py: line 14: api_token: command not found
./cloudflare_ddns.py: line 15: zone_id: command not found
./cloudflare_ddns.py: line 18: a_record_name: command not found
./cloudflare_ddns.py: line 21: syntax error near unexpected token `('
./cloudflare_ddns.py: line 21: `cf = CloudFlare(token=api_token)'
|
8411eb85bd5e7dfadfedca19ecdbf468
|
{
"intermediate": 0.43465930223464966,
"beginner": 0.4352853000164032,
"expert": 0.13005545735359192
}
|
8,528
|
sed -i "s/'/'/g; s/'/'g" cloudflare_ddns.py
sed: -e expression #1, char 15: unterminated `s' command
|
e8a2fcf90116d23f4f82e22b82291b26
|
{
"intermediate": 0.3640173375606537,
"beginner": 0.3893313407897949,
"expert": 0.24665139615535736
}
|
8,529
|
make a minecraft 1.19.3 plugin - bounty *****send me only code!!! no any other text!*****
In the plugin several commands and actions:
/bounty {player} - it show how much money you get if you kill him.
bounty add {player} {amount}
that is to add this amount of money to the amount of the player’s bounty.
The plugin will only work in the worlds listed in config.yml
As soon as I killed someone I will receive the money that was put in their bounty and then their
bounty will be reset. (only in the worlds registered in config.yml)
when someone does the command bounty add {player} {amount}
So the player who did the command will be deducted the amount of money he registered, if he doesn’t have enough the command won’t work. (Works with the Economy plugin - Vault)
The /bounty {player} command: This command will display the amount of money you will receive if you kill the specified player.
The bounty add {player} {amount} command: This command allows you to add a certain amount of money to the bounty of the specified player.
Limiting plugin functionality to specific worlds: The plugin will only be active and functional in the worlds listed in the config.yml file.
Reward and reset bounty on player kill: Whenever you kill a player, you will receive the money from their bounty, and their bounty will be reset. This functionality will only work in the worlds registered in the config.yml file.
Deducting money when using the bounty add {player} {amount} command: When a player executes this command, the specified amount of money will be deducted from their own balance. If the player doesn’t have enough money, the command will not work. This feature works in conjunction with an Economy plugin like Vault.
|
050958db49125b2030a09f124c4325df
|
{
"intermediate": 0.4561539590358734,
"beginner": 0.23037222027778625,
"expert": 0.31347376108169556
}
|
8,530
|
i want to write a coroutine in kotlin. i have a function whose purpose is to download a file and create a database from data parsed from the file. how would that look like?
|
a4f6b5551af003b16bb76a564993fb8e
|
{
"intermediate": 0.6126236319541931,
"beginner": 0.20643101632595062,
"expert": 0.1809452772140503
}
|
8,531
|
can I have a script in python that can left click once randomly every few minutes and move mouse at random
|
d5c4625929b1094876a76b00098f6c48
|
{
"intermediate": 0.37819117307662964,
"beginner": 0.15099598467350006,
"expert": 0.4708128869533539
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.