row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
9,541
|
import {useCallback, useEffect, useState} from "react";
import {ReadyState} from "../enums/readyState";
type CupItem = {
futures_price_micro: number;
quantity: number;
spot_quantity: number;
side: string;
};
export interface BestMicroPrice {
buy: number;
sell: number;
}
export function useRustWsServer() {
const [connection, setConnection] = useState<WebSocket|null>(null);
const [readyState, setReadyState] = useState(0);
const [cup, setCup] = useState<Array<CupItem>>([]);
const [bestMicroPrice, setBestMicroPrice] = useState<BestMicroPrice|null>(null);
const [maxVolume, setMaxVolume] = useState(1);
function splitCupSides(rawData: {[key: number]: CupItem}): Array<CupItem> {
const sellRecords = [];
const buyRecords = [];
let max = 0;
for (const value of Object.values(rawData)) {
if (value.side === "Buy") {
buyRecords.push(value);
} else if (value.side === "Sell") {
sellRecords.push(value);
}
if (value.quantity > max) {
max = value.quantity;
}
}
sellRecords.sort((a, b) => {
return b.futures_price_micro - a.futures_price_micro;
});
buyRecords.sort((a, b) => {
return b.futures_price_micro - a.futures_price_micro;
});
setMaxVolume(max);
return [...sellRecords, ...buyRecords];
}
const cupSubscribe = useCallback((symbol: string, camera: number, zoom: number, rowCount: number) => {
if (null === connection || readyState !== ReadyState.OPEN) return;
connection.send(JSON.stringify({
"commands": [
{
commandType: "SUBSCRIBE_SYMBOL",
symbol,
camera: Math.round(camera / zoom) * zoom,
zoom,
rowCount,
},
],
}));
}, [readyState]);
const cupUnsubscribe = useCallback((symbol: string) => {
if (null === connection || readyState !== ReadyState.OPEN) return;
connection.send(JSON.stringify({
"commands": [
{
commandType: "UNSUBSCRIBE_SYMBOL",
symbol,
},
],
}));
}, [readyState]);
useEffect(() => {
const url = process.env.NEXT_PUBLIC_RUST_WS_SERVER;
if (url) {
const ws = new WebSocket(url);
setConnection(ws);
}
}, []);
useEffect(() => {
if (null !== connection) {
connection.onmessage = (message: MessageEvent) => {
if (!message.data) return;
const data = JSON.parse(message.data);
if (!data?.commands || data.commands.length === 0) return;
const domUpdate = data.commands.find((item: any) => "undefined" !== typeof item.SymbolDomUpdate);
if (!domUpdate) return;
setCup(splitCupSides(domUpdate.SymbolDomUpdate.dom_rows));
setBestMicroPrice({
buy: domUpdate.SymbolDomUpdate.best_prices_futures.best_ask_micro,
sell: domUpdate.SymbolDomUpdate.best_prices_futures.best_bid_micro,
});
};
connection.onopen = () => {
setReadyState(ReadyState.OPEN);
};
connection.onclose = () => {
setReadyState(ReadyState.CLOSED);
};
}
}, [connection]);
return {
readyState,
cupSubscribe,
cupUnsubscribe,
cup,
maxVolume,
bestMicroPrice,
};
}
import {BestMicroPrice, useRustWsServer} from "../../hooks/rustWsServer";
import {createContext, Reducer, useEffect, useReducer, useRef, useState} from "react";
import CupDrawer from "../CupDrawer/CupDrawer";
import {IconButton} from "@mui/material";
import {AddRounded, RemoveRounded} from "@mui/icons-material";
import {ReadyState} from "../../enums/readyState";
import {useSelector} from "react-redux";
import {AppState} from "../../store/store";
interface CupConfigSubscription {
pair: string | null;
zoom: number;
camera: number;
rowCount: number;
}
export const CupControlsContext = createContext<{
cupControlsState: any;
cupControlsDispatcher: any;
}>({
cupControlsState: null,
cupControlsDispatcher: null,
});
const TradingCup = () => {
const symbol = useSelector((state: AppState) => state.screenerSlice.symbol);
const {cup, bestMicroPrice, maxVolume, readyState, cupSubscribe, cupUnsubscribe} = useRustWsServer();
const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbol.toUpperCase()]);
const tickSize = useSelector((state: AppState) => state.binanceTickSize.futures[symbol.toUpperCase()]);
const [cupConfig, setCupConfig] = useState<CupConfigSubscription>({
pair: null,
zoom: 10,
camera: 0,
rowCount: 40,
});
useEffect(() => {
if (symbol) {
setCupConfig({
...cupConfig,
pair: symbol.toUpperCase(),
camera: 0,
});
}
}, [symbol]);
useEffect(() => {
if (readyState === ReadyState.OPEN) {
if (null !== cupConfig.pair) {
cupSubscribe(
cupConfig.pair,
cupConfig.camera,
cupConfig.zoom,
cupConfig.rowCount,
);
}
}
return () => {
if (cupConfig.pair != null) {
cupUnsubscribe(cupConfig.pair);
}
};
}, [
cupConfig.pair,
cupConfig.camera,
cupConfig.zoom,
cupConfig.rowCount,
readyState,
]);
return (
<>
</>
);
};
export default TradingCup;
import {each, get, map, reduce, range, clamp, reverse} from 'lodash'
import {ESide} from "../../interfaces/interfaces";
import {abbreviateNumber, blendColors, blendRGBColors, getRatio, shadeColor} from "../../utils/utils";
import {
bubbleSize, clusterBg,
clusterGreen,
clusterRed,
clustersCountUI,
deepGreen,
deepRed,
lightGreen,
lightRed,
maxClusterWidth,
minuteMs,
rowHeight,
timeFrame,
visibleClustersCount
} from "../../constants/consts";
export default class ClustersClientControllers {
xWidthInMs = timeFrame * clustersCountUI
DOMBorderOffset = 0
abnormalDensities = 200
clusters = []
currentMin = 0
tempCluster = {}
tempCurrentMin
totals = []
tempTotal = {}
root: ClientController
canvasHeight = 0
canvasWidth = 0
tradesArr: any = []
public bestPrices: any = null
clustersCtx
orderFeedCtx
public cameraPrice = null
public zoom = 10
clusterCellWidth
virtualServerTime = null
tradesFilterBySymbol = {}
constructor(root) {
this.root = root
window['clusters'] = this
this.restoreClusterSettings()
}
renderTrades = () => {
this.clearOrderFeed();
reduce(this.tradesArr, (prev, cur, index) => {
this.renderTrade(prev, cur, this.tradesArr.length - (index as any))
prev = cur
console.log(prev);
return prev
})
}
clearOrderFeed = () => {
this.orderFeedCtx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
}
renderTrade = (prev, item, index) => {
//const anomalyQty = this.root.instruments[this.root.selectedSymbol].anomalies.anomaly_qty;
console.log(item); //
price_float
:
0.4139
price_micro
:
4139000
quantity
:
6
side
:
"Buy"
time
:
1685607036920
//if (size < 1) return;
const ctx = this.orderFeedCtx
let xPos = (this.canvasWidth - (index * (bubbleSize * 1.5))) - bubbleSize;
const offsetFromTop = this.root.tradingDriverController.upperPrice - item.price_micro;
const y = ((offsetFromTop / this.root.tradingDriverController.getZoomedStepMicro()) - 1) * rowHeight
const label = abbreviateNumber(item.quantity * item.price_float)
const {width: textWidth} = ctx.measureText(label);
const itemUsdt = item.quantity * item.price_float;
const tradeFilter = this.getTradeFilterBySymbol(this.getSymbol())
const maxUsdtBubbleAmount = tradeFilter * 30;
const maxPixelBubbleAmount = 35;
const realBubbleSize = (itemUsdt / maxUsdtBubbleAmount) * maxPixelBubbleAmount
const size = clamp(realBubbleSize, (textWidth/2)+3, maxPixelBubbleAmount)
const bubbleX = xPos;
const bubbleY = y + 8;
ctx.beginPath();
let bigRatio = (realBubbleSize / maxPixelBubbleAmount) / 3;
bigRatio = bigRatio > 0.95 ? 0.95 : bigRatio;
ctx.fillStyle = item.side === "Sell" ? deepGreen.lighten(bigRatio).toString() : deepRed.lighten(bigRatio).toString()
ctx.strokeStyle = 'black';
ctx.arc(xPos, bubbleY, size, 0, 2 * Math.PI)
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#FFFFFF"
ctx.fillText(label, bubbleX - (textWidth / 2), (bubbleY + (rowHeight / 2)) - 2)
}
1. В компоненте TradingCup запрашивается cup из useRustWsServer, сделать отрисовку канвас как в методах renderTrade renderTrades .
2. renderTrade renderTrades то другой немного компонент с немного другими данными, нужно использовать его в TradingCup только с нашими данными type CupItem = {
futures_price_micro: number;
quantity: number;
spot_quantity: number;
side: string;
};
3. В методе renderTrade() показатели quantity и price_float перемножаются, чтобы получить объем в $. Нам это не нужно, будем выводить только quantity.
Нужно все отрисовать в канвасе И использовать тоже самое соединение, что установлено в rustWsServer.ts
обязательно везде typescript
|
e285035127d5878bf799614c4f70ee61
|
{
"intermediate": 0.3489033579826355,
"beginner": 0.4464230239391327,
"expert": 0.2046736478805542
}
|
9,542
|
best article on prey predator system
|
67a4b2cb7fe825002a62271d0f6f9833
|
{
"intermediate": 0.32477280497550964,
"beginner": 0.36521098017692566,
"expert": 0.3100161552429199
}
|
9,543
|
<svg-icon
name="card-theme"
width="32"
height="32"
:class="{ active: isActive}"
@click="setIsTable('true')"
/>
<svg-icon
name="table-theme"
width="32"
height="32"
:class="{ active: !isActive}"
@click="setIsTable('')"
/>
isActive = true
.active {
width: 46px;
height: 46px;
background: #FAFAFA;
box-shadow: inset 1px 2px 3px rgba(0, 0, 0, 0.25);
border-radius: 100px;
display: flex;
align-items: center;
justify-content: center;
}
Почему не работает динамический класс?
|
c95e5295f26e522183c3e82877bfabb0
|
{
"intermediate": 0.37943002581596375,
"beginner": 0.3718937039375305,
"expert": 0.24867618083953857
}
|
9,544
|
How to get the value from Option<String> or default it to "Hello" in Rust
|
2a47da4a4ae4a279b2f9637765480b5e
|
{
"intermediate": 0.4188527464866638,
"beginner": 0.3651367127895355,
"expert": 0.21601051092147827
}
|
9,545
|
Previous operation has not finished这是什么意思?
|
c5d6e212565859f0001d6a87e6565410
|
{
"intermediate": 0.32570117712020874,
"beginner": 0.3671545386314392,
"expert": 0.30714431405067444
}
|
9,546
|
Act as a VBA programmer. Write me VBA code to create PowerPoint slides about business analyst think like a seniorbusiness analist use your knowledge and create at least 10 slides and use Italian as language for the slides.
|
afac57b349d8b1aa08d9d715d650d1f8
|
{
"intermediate": 0.1697935163974762,
"beginner": 0.6872751712799072,
"expert": 0.14293129742145538
}
|
9,547
|
Can you optimize the following C# Code:
#define Http2
//#define CLOUD_FLARE
//#define SEND_LUMINATI_HEADER
using System;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.IO;
using System.Text;
using System.Diagnostics;
#if CLOUD_FLARE
using CloudFlareBypass.Models;
using CloudFlareBypass.Solvers;
using CloudFlareBypass.DelegateHandler;
#endif
#pragma warning disable CA1416
namespace Test.Helpers;
public static class HttpClientHelper
{
public const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36";
private static WebProxy? _localProxy;
#if CLOUD_FLARE
private static readonly IChallengeDetector ChallengeDetector = new ChallengeDetector();
private static readonly IBrowserHandler BrowserHandler = new BrowserHandler().Use(new CloudFlare());
#endif
// public static readonly string? ProxySessionId;
private const string TimeoutPropertyKey = "RequestTimeout";
private static readonly HttpRequestOptionsKey<TimeSpan?> TimeoutOptionsKey;
static HttpClientHelper()
{
// ProxySessionId = Strings.GetRandomUsername(5, 10);
KeepUpdatingLocalProxy();
TimeoutOptionsKey = new HttpRequestOptionsKey<TimeSpan?>(TimeoutPropertyKey);
}
public static async Task<string> GetValidContent(HttpMethod httpMethod, string url, string wordsToSearch, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
string content;
bool valid;
var triesCounter = 0;
do
{
if (proxy != null)
{
while (proxy != null && !proxy.Increment())
{
proxy = ProxyHelper.GetAvailableProxy();
}
//writeLineDEBUG($"NEW Proxy: { proxy.ProxyString } | NOF: { proxy.NumOfFail } | UC: { proxy.UseCounter }");
}
else if (ProxyHelper.UseProxies)
{
proxy = ProxyHelper.GetAvailableProxy();
}
content = await Request(httpMethod, url, post, timeout, cookies, proxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (autoRedirect == false && content.StartsWith("$Redirected to$|:"))
{
valid = true;
break;
}
valid = wordsToSearch == null || wordsToSearch.Split('|').Any(w => content.ToLower().Contains(w.ToLower()));
if (!valid)
{
if (proxy != null)
{
proxy.Enough = true;
proxy.NumOfFailIncrement();
Debug.WriteLine($"OLD Proxy: {proxy.ProxyString} | NOF: {proxy.FailCounter} | UC: {proxy.UsageCounter}");
}
await Task.Delay(700).ConfigureAwait(false);
}
}
while (!valid && (maxTries == -1 || ++triesCounter < maxTries));
if (valid)
proxy?.ResetFailCounter();
return content;
}
public static async Task<string> GetContentDoesNotContain(HttpMethod httpMethod, string url, string wordsToSearch, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool alsoNotEmpty = true, int notLessThan = 700, bool noProxy = false)
{
string content;
bool valid;
var triesCounter = 0;
do
{
if (proxy != null)
{
while (proxy != null && !proxy.Increment())
{
proxy = ProxyHelper.GetAvailableProxy();
}
//writeLineDEBUG($"NEW Proxy: { proxy.ProxyString } | NOF: { proxy.NumOfFail } | UC: { proxy.UseCounter }");
}
else if (ProxyHelper.UseProxies)
{
proxy = ProxyHelper.GetAvailableProxy();
}
content = await Request(httpMethod, url, post, timeout, cookies, proxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (autoRedirect == false && content.StartsWith("$Redirected to$|:"))
{
valid = true;
break;
}
valid = !alsoNotEmpty || content.Length > notLessThan;
if (valid && !string.IsNullOrEmpty(wordsToSearch))
{
var words = wordsToSearch.Split('|');
var contentLowered = content.ToLower();
foreach (var word in words)
{
if (contentLowered.Contains(word.ToLower()))
{
valid = false;
break;
}
}
}
if (valid || proxy == null) continue;
proxy.Enough = true;
proxy.NumOfFailIncrement();
Debug.WriteLine($"OLD Proxy: {proxy.ProxyString} | NOF: {proxy.FailCounter} | UC: {proxy.UsageCounter}");
//Thread.Sleep(300);
}
while (!valid && (maxTries == -1 || ++triesCounter < maxTries));
if (valid)
proxy?.ResetFailCounter();
//writeLineDEBUG($"Valid Content Proxy: { proxy.ProxyString } | UC: { proxy.useCounter }");
return content;
}
public static async Task<HttpStatusCode> MakeSureFileDownloaded(HttpMethod httpMethod, string url, string path, bool overrideExist = true, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
HttpStatusCode statusCode;
bool downloaded;
var triesCounter = 0;
do
{
if (proxy != null)
{
while (proxy != null && !proxy.Increment())
{
proxy = ProxyHelper.GetAvailableProxy();
}
//writeLineDEBUG($"NEW Proxy: { proxy.ProxyString } | NOF: { proxy.numOfFail } | UC: { proxy.useCounter }");
}
else if (ProxyHelper.UseProxies)
{
proxy = ProxyHelper.GetAvailableProxy();
}
statusCode = await DownloadFile(httpMethod, url, path, overrideExist, post, timeout, cookies, proxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (autoRedirect == false && statusCode == HttpStatusCode.Redirect)
{
downloaded = true;
break;
}
downloaded = statusCode is HttpStatusCode.OK or HttpStatusCode.Found;
if (!downloaded)
{
if (proxy != null)
{
proxy.Enough = true;
proxy.NumOfFailIncrement();
Debug.WriteLine($"OLD Proxy: {proxy.ProxyString} | NOF: {proxy.FailCounter} | UC: {proxy.UsageCounter} | Download:{statusCode}");
}
//Thread.Sleep(300);
}
} while (!downloaded && (maxTries == -1 || ++triesCounter < maxTries));
if (downloaded)
proxy?.ResetFailCounter();
return statusCode;
}
public static async Task<byte[]?> MakeSureFileDownloadedToMemory(HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
byte[]? result;
bool downloaded;
var triesCounter = 0;
do
{
if (proxy != null)
{
while (proxy != null && !proxy.Increment())
{
proxy = ProxyHelper.GetAvailableProxy();
}
//writeLineDEBUG($"NEW Proxy: { proxy.ProxyString } | NOF: { proxy.numOfFail } | UC: { proxy.useCounter }");
}
else if (ProxyHelper.UseProxies)
{
proxy = ProxyHelper.GetAvailableProxy();
}
result = await DownloadFileToMemory(httpMethod, url, post, timeout, cookies, proxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
//BadGateway > 502 | Forbidden > 403 | Unauthorized > 401 etc....
downloaded = result != null && result.Length != 3;
if (downloaded || (autoRedirect == false && result == Encoding.UTF8.GetBytes(HttpStatusCode.Redirect.ToString())))
break;
if (!downloaded)
{
if (proxy != null)
{
proxy.Enough = true;
proxy.NumOfFailIncrement();
Debug.WriteLine($"OLD Proxy: {proxy.ProxyString} | NOF: {proxy.FailCounter} | UC: {proxy.UsageCounter}");
}
//Thread.Sleep(300);
}
} while (!downloaded && (maxTries == -1 || ++triesCounter < maxTries));
if (downloaded)
proxy?.ResetFailCounter();
return result;
}
public static async Task<string> Request(HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
string output;
try
{
var response = await SendAsync(httpMethod, url, post, timeout, cookies, proxy?.WebProxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (!autoRedirect && response.StatusCode == HttpStatusCode.Redirect)
return $"$Redirected to$|:{response.Headers.Location}";
output = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (Exception e)
{
var err = e.InnerException == null ? e.Message : e.InnerException.Message;
//writeLineDEBUG(err);
output = err;
}
return output;
}
public static async Task<HttpStatusCode> DownloadFile(HttpMethod httpMethod, string url, string path, bool overrideExist = true, byte[]? post = null, int timeout = 120_000, CookieContainer? cookies = null, Proxy? proxy = null, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
url = TryGetValidUrl(url)!;
if (string.IsNullOrWhiteSpace(url)) return HttpStatusCode.RequestUriTooLong;
if (!overrideExist && File.Exists(path)) return HttpStatusCode.Found;
try
{
var response = await SendAsync(httpMethod, url, post, timeout, cookies, proxy?.WebProxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.Found)) return response.StatusCode;
await using var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
await using var fs = File.Create(path);
await responseStream.CopyToAsync(fs).ConfigureAwait(false);
}
catch
{
return HttpStatusCode.BadRequest;
}
return HttpStatusCode.OK;
}
public static async Task<byte[]?> DownloadFileToMemory(HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 120_000, CookieContainer? cookies = null, Proxy? proxy = null, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
url = TryGetValidUrl(url)!;
if (string.IsNullOrWhiteSpace(url)) return default;
try
{
var response = await SendAsync(httpMethod, url, post, timeout, cookies, proxy?.WebProxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (response.StatusCode is not HttpStatusCode.OK)
return Encoding.UTF8.GetBytes(((int)response.StatusCode).ToString());
return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
catch
{
return default;
}
}
private static Task<HttpResponseMessage> SendAsync(HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, WebProxy? proxy = null, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
var uri = new Uri(url);
var finalProxy = noProxy ? null : proxy ?? _localProxy;
#if Http2
var handler = (Http2CustomHandler)CreateWinHttpHandler(timeout, cookies, finalProxy, autoRedirect);
#else
var handler = CreateHttpHandler(cookies, proxy, autoRedirect);
#endif
#if CLOUD_FLARE
var forceBrowser = aHeaders?.FirstOrDefault(h => h.Key.Equals("force-browser", StringComparison.InvariantCultureIgnoreCase)).Value;
HttpMessageHandler handler = session == null
? handler
: new DelegateHandler(ChallengeDetector, BrowserHandler, session) { MaxTimeout = forceBrowser == "true" ? int.MaxValue : 120_000, InnerHandler = handler };
using var client = new HttpClient(handler);
#else
using var client = new HttpClient(handler);
#endif
client.DefaultRequestHeaders.Host = uri.Host;
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
var request = new HttpRequestMessage
{
RequestUri = uri,
Method = httpMethod
};
request.SetTimeout(TimeSpan.FromMilliseconds(timeout));
request.Headers.ExpectContinue = false;
if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "accept"))
request.Headers.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "accept-encoding"))
request.Headers.AcceptEncoding.ParseAdd("gzip, deflate, br");
if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "accept-language"))
request.Headers.AcceptLanguage.ParseAdd("en-US,en;q=0.9,ar;q=0.8");
//if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "referer"))
// request.Headers.Referrer = uri;
if (aHeaders != null)
foreach (var header in aHeaders)
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
#if SEND_LUMINATI_HEADER
if (Bot.OnlyPaidProxies)
request.Headers.TryAddWithoutValidation("x-lpm-session", ProxySessionId);
#endif
#if CLOUD_FLARE
if (Bot.Session != null && proxy?.Credentials?.GetCredential(uri, "Basic") is { } credential)
Bot.Session.AuthCredential = new AuthCredential(credential.UserName, credential.Password);
#endif
if (post != null)
{
request.Content = new ByteArrayContent(post);
var contentType = aHeaders?.FirstOrDefault(h => h.Key.Equals("content-type", StringComparison.InvariantCultureIgnoreCase)).Value;
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType ?? "application/x-www-form-urlencoded");
}
return client.SendAsync(request);
}
public static async Task<string> GetValidContent<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, string wordsToSearch, byte[]? post = null, int timeout = 60_000, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
var triesCounter = 0;
while (maxTries == -1 || triesCounter < maxTries)
{
var content = await Request(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (autoRedirect == false && content.StartsWith("$Redirected to$|:"))
break;
if (string.IsNullOrEmpty(wordsToSearch) || wordsToSearch.Split('|').Any(w => content.Contains(w, StringComparison.OrdinalIgnoreCase)))
return content;
await Task.Delay(700).ConfigureAwait(false);
triesCounter++;
}
return string.Empty;
}
public static async Task<string> GetContentDoesNotContain<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, string wordsToSearch, byte[]? post = null, int timeout = 60_000, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool alsoNotEmpty = true, int notLessThan = 700) where T : HttpMessageHandler
{
var triesCounter = 0;
while (maxTries == -1 || triesCounter < maxTries)
{
var content = await Request(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (autoRedirect == false && content.StartsWith("$Redirected to$|:"))
break;
if ((!alsoNotEmpty || content.Length > notLessThan) && (string.IsNullOrEmpty(wordsToSearch) || !wordsToSearch.Split('|').Any(word => content.Contains(word, StringComparison.OrdinalIgnoreCase))))
return content;
await Task.Delay(700).ConfigureAwait(false);
triesCounter++;
}
return string.Empty;
}
public static async Task<HttpStatusCode> MakeSureFileDownloaded<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, string path, bool overrideExist = true, byte[]? post = null, int timeout = 60_000, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
HttpStatusCode statusCode;
bool downloaded;
var triesCounter = 0;
do
{
statusCode = await DownloadFile(client, httpMethod, url, path, overrideExist, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (autoRedirect == false && statusCode == HttpStatusCode.Redirect)
break;
downloaded = statusCode is HttpStatusCode.OK or HttpStatusCode.Found;
if (!downloaded)
await Task.Delay(700).ConfigureAwait(false);
}
while (!downloaded && (maxTries == -1 || ++triesCounter < maxTries));
return statusCode;
}
public static async Task<byte[]?> MakeSureFileDownloadedToMemory<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
byte[]? result;
bool downloaded;
var triesCounter = 0;
do
{
result = await DownloadFileToMemory(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
//BadGateway > 502 | Forbidden > 403 | Unauthorized > 401 etc....
downloaded = result != null && result.Length != 3;
if (downloaded || (autoRedirect == false && result == Encoding.UTF8.GetBytes(HttpStatusCode.Redirect.ToString())))
break;
await Task.Delay(700).ConfigureAwait(false);
}
while (!downloaded && (maxTries == -1 || ++triesCounter < maxTries));
return result;
}
public static async Task<string> Request<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
string output;
try
{
var response = await SendAsync(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (!autoRedirect && response.StatusCode == HttpStatusCode.Redirect)
return $"$Redirected to$|:{response.Headers.Location}";
output = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (Exception e)
{
var err = e.InnerException == null ? e.Message : e.InnerException.Message;
//writeLineDEBUG(err);
output = err;
}
return output;
}
public static async Task<HttpStatusCode> DownloadFile<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, string path, bool overrideExist = true, byte[]? post = null, int timeout = 120_000, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
url = TryGetValidUrl(url)!;
if (string.IsNullOrWhiteSpace(url)) return HttpStatusCode.RequestUriTooLong;
if (!overrideExist && File.Exists(path)) return HttpStatusCode.Found;
try
{
var response = await SendAsync(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.Found)) return response.StatusCode;
await using var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
await using var fs = File.Create(path);
await responseStream.CopyToAsync(fs).ConfigureAwait(false);
}
catch
{
return HttpStatusCode.BadRequest;
}
return HttpStatusCode.OK;
}
public static async Task<byte[]?> DownloadFileToMemory<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 120_000, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
url = TryGetValidUrl(url)!;
if (string.IsNullOrWhiteSpace(url)) return default;
try
{
var response = await SendAsync(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (response.StatusCode is not HttpStatusCode.OK)
return Encoding.UTF8.GetBytes(((int)response.StatusCode).ToString());
return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
catch
{
return default;
}
}
private static Task<HttpResponseMessage> SendAsync<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
var uri = new Uri(url);
var request = new HttpRequestMessage
{
RequestUri = uri,
Method = httpMethod
};
request.SetTimeout(TimeSpan.FromMilliseconds(timeout));
request.Headers.ExpectContinue = false;
//if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "referer"))
// request.Headers.Referrer = uri;
if (aHeaders != null)
foreach (var header in aHeaders)
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
#if SEND_LUMINATI_HEADER
if (Bot.OnlyPaidProxies)
request.Headers.TryAddWithoutValidation("x-lpm-session", ProxySessionId);
#endif
#if CLOUD_FLARE
if (Bot.Session != null && proxy?.Credentials?.GetCredential(uri, "Basic") is { } credential)
Bot.Session.AuthCredential = new AuthCredential(credential.UserName, credential.Password);
#endif
if (post != null)
{
request.Content = new ByteArrayContent(post);
var contentType = aHeaders?.FirstOrDefault(h => h.Key.Equals("content-type", StringComparison.InvariantCultureIgnoreCase)).Value;
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType ?? "application/x-www-form-urlencoded");
}
TryToSetHandlerRedirect(client.Handler, autoRedirect);
return client.SendAsync(request);
}
/// <summary>
/// Returns a valid URL if it's valid or missing just http: |
/// Returns null if it's not valid
/// </summary>
public static string? TryGetValidUrl(string? url)
{
if (url == null) return null;
if (url.StartsWith("//")) url = $"http:{url}";
return CheckUrlValid(url) ? url : null;
}
public static bool CheckUrlValid(string source)
{
return Uri.TryCreate(source, UriKind.Absolute, out var uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}
private static async void KeepUpdatingLocalProxy()
{
#if DEBUG
while (true)
{
try
{
using var client = new System.Net.Sockets.TcpClient();
var result = client.BeginConnect("127.0.0.1", 17073, null, null);
result.AsyncWaitHandle.WaitOne(2000);
client.EndConnect(result);
_localProxy = _localProxy ?? new WebProxy("127.0.0.1", 17073);
}
catch
{
_localProxy = null;
}
await Task.Delay(3000).ConfigureAwait(false);
}
#else
_localProxy = null;
#endif
// ReSharper disable once FunctionNeverReturns
}
#region Http Client & Handler
public static CustomHttpClient<T> CreateHttpClient<T>(T handler, bool disposeHandler = true) where T : HttpMessageHandler
{
var client = new CustomHttpClient<T>(handler, disposeHandler);
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
client.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9,ar;q=0.8");
//client.DefaultRequestHeaders.ExpectContinue = false;
return client;
}
public static HttpClientHandler CreateHttpHandler(CookieContainer? cookies = null, WebProxy? proxy = null, bool autoRedirect = true)
{
return new HttpClientHandler
{
ServerCertificateCustomValidationCallback = delegate { return true; },
SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12,
UseProxy = proxy != null,
Proxy = proxy,
UseCookies = /*cookies != null*/ true,
CookieContainer = cookies ?? new CookieContainer(),
AllowAutoRedirect = autoRedirect,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli
};
}
#if Http2
public static WinHttpHandler CreateWinHttpHandler(int timeout = 60_000, CookieContainer? cookies = null, WebProxy? proxy = null, bool autoRedirect = true, bool keepAlive = true)
{
var sTimeout = TimeSpan.FromMilliseconds(timeout);
return new WinHttpHandler
{
ServerCertificateValidationCallback = delegate { return true; },
SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12,
WindowsProxyUsePolicy = proxy == null ? WindowsProxyUsePolicy.DoNotUseProxy : WindowsProxyUsePolicy.UseCustomProxy,
Proxy = proxy,
CookieUsePolicy = /*cookies == null ? CookieUsePolicy.IgnoreCookies : */CookieUsePolicy.UseSpecifiedCookieContainer,
CookieContainer = cookies ?? new CookieContainer(),
AutomaticRedirection = autoRedirect,
TcpKeepAliveEnabled = keepAlive,
ReceiveDataTimeout = sTimeout,
ReceiveHeadersTimeout = sTimeout,
SendTimeout = sTimeout,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli
};
}
#endif
#if CLOUD_FLARE
public static DelegateHandler CreateFlareHandler(ISession session, HttpMessageHandler innerHandler, bool forceBrowser = false)
{
return new DelegateHandler(ChallengeDetector, BrowserHandler, session) { MaxTimeout = forceBrowser ? int.MaxValue : 160_000, InnerHandler = innerHandler };
}
#endif
private static void TryToSetHandlerRedirect<T>(T handler, bool autoRedirect = true) where T : HttpMessageHandler
{
#if CLOUD_FLARE
if (handler is DelegateHandler dh)
handler = dh.InnerHandler;
#endif
switch (handler)
{
case WinHttpHandler whh:
whh.AutomaticRedirection = autoRedirect;
break;
case HttpClientHandler hch:
hch.AllowAutoRedirect = autoRedirect;
break;
}
}
public static void SetTimeout(this HttpRequestMessage request, TimeSpan? timeout)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
request.Options.Set(TimeoutOptionsKey, timeout);
}
public static TimeSpan? GetTimeout(this HttpRequestMessage request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
return request.Options.TryGetValue(TimeoutOptionsKey, out var value) ? value : null;
}
public class CustomHttpClient<T> : HttpClient where T : HttpMessageHandler
{
//public TimeSpan DefaultTimeout { get; set; } = TimeSpan.FromSeconds(100);
public T Handler { get; }
public CustomHttpClient(T handler, bool disposeHandler = true) : base(handler, disposeHandler)
{
Timeout = System.Threading.Timeout.InfiniteTimeSpan;
Handler = handler;
}
public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
#if Http2
if (Handler is WinHttpHandler)
request.Version = new Version("2.0");
#if CLOUD_FLARE
else if (Handler is DelegateHandler dh && dh.InnerHandler is WinHttpHandler)
request.Version = new Version("2.0");
#endif
#endif
using var cts = GetCancellationTokenSource(request, cancellationToken);
try
{
var response = await base.SendAsync(request, cts?.Token ?? cancellationToken).ConfigureAwait(false);
if (!response.Content.Headers.TryGetValues("Content-Encoding", out var ce) || ce.First() != "br")
return response;
//var buffer = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
//response.Content = new ByteArrayContent(Brotli.DecompressBuffer(buffer, 0, buffer.Length));
var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
response.Content = new StreamContent(new BrotliStream(stream, CompressionMode.Decompress));
return response;
}
catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException(ex.Message, ex);
}
}
private CancellationTokenSource? GetCancellationTokenSource(HttpRequestMessage request, CancellationToken cancellationToken)
{
var timeout = request.GetTimeout() ?? Timeout;
if (timeout == System.Threading.Timeout.InfiniteTimeSpan)
{
// No need to create a CTS if there's no timeout
return null;
}
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(timeout);
return cts;
}
}
#if Http2
public class Http2CustomHandler : WinHttpHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Version = new Version("2.0");
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!response.Content.Headers.TryGetValues("Content-Encoding", out var ce) || ce.First() != "br")
return response;
//var buffer = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
//response.Content = new ByteArrayContent(Brotli.DecompressBuffer(buffer, 0, buffer.Length));
var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
response.Content = new StreamContent(new BrotliStream(stream, CompressionMode.Decompress));
return response;
}
}
#endif
#endregion
}
|
30f2a11bb9852f5501ade036192fb7b1
|
{
"intermediate": 0.3547944128513336,
"beginner": 0.34378373622894287,
"expert": 0.30142179131507874
}
|
9,548
|
Can you optimize the following C# Code:
#define Http2
//#define SEND_LUMINATI_HEADER
using System;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Authentication;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.IO;
using System.Text;
using System.Diagnostics;
#pragma warning disable CA1416
namespace Test.Helpers;
public static class HttpClientHelper
{
public const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36";
private static WebProxy? _localProxy;
// public static readonly string? ProxySessionId;
private const string TimeoutPropertyKey = "RequestTimeout";
private static readonly HttpRequestOptionsKey<TimeSpan?> TimeoutOptionsKey;
static HttpClientHelper()
{
// ProxySessionId = Strings.GetRandomUsername(5, 10);
KeepUpdatingLocalProxy();
TimeoutOptionsKey = new HttpRequestOptionsKey<TimeSpan?>(TimeoutPropertyKey);
}
public static async Task<string> GetValidContent(HttpMethod httpMethod, string url, string wordsToSearch, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
string content;
bool valid;
var triesCounter = 0;
do
{
if (proxy != null)
{
while (proxy != null && !proxy.Increment())
{
proxy = ProxyHelper.GetAvailableProxy();
}
//writeLineDEBUG($"NEW Proxy: { proxy.ProxyString } | NOF: { proxy.NumOfFail } | UC: { proxy.UseCounter }");
}
else if (ProxyHelper.UseProxies)
{
proxy = ProxyHelper.GetAvailableProxy();
}
content = await Request(httpMethod, url, post, timeout, cookies, proxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (autoRedirect == false && content.StartsWith("$Redirected to$|:"))
{
valid = true;
break;
}
valid = wordsToSearch == null || wordsToSearch.Split('|').Any(w => content.ToLower().Contains(w.ToLower()));
if (!valid)
{
if (proxy != null)
{
proxy.Enough = true;
proxy.NumOfFailIncrement();
Debug.WriteLine($"OLD Proxy: {proxy.ProxyString} | NOF: {proxy.FailCounter} | UC: {proxy.UsageCounter}");
}
await Task.Delay(700).ConfigureAwait(false);
}
}
while (!valid && (maxTries == -1 || ++triesCounter < maxTries));
if (valid)
proxy?.ResetFailCounter();
return content;
}
public static async Task<string> GetContentDoesNotContain(HttpMethod httpMethod, string url, string wordsToSearch, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool alsoNotEmpty = true, int notLessThan = 700, bool noProxy = false)
{
string content;
bool valid;
var triesCounter = 0;
do
{
if (proxy != null)
{
while (proxy != null && !proxy.Increment())
{
proxy = ProxyHelper.GetAvailableProxy();
}
//writeLineDEBUG($"NEW Proxy: { proxy.ProxyString } | NOF: { proxy.NumOfFail } | UC: { proxy.UseCounter }");
}
else if (ProxyHelper.UseProxies)
{
proxy = ProxyHelper.GetAvailableProxy();
}
content = await Request(httpMethod, url, post, timeout, cookies, proxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (autoRedirect == false && content.StartsWith("$Redirected to$|:"))
{
valid = true;
break;
}
valid = !alsoNotEmpty || content.Length > notLessThan;
if (valid && !string.IsNullOrEmpty(wordsToSearch))
{
var words = wordsToSearch.Split('|');
var contentLowered = content.ToLower();
foreach (var word in words)
{
if (contentLowered.Contains(word.ToLower()))
{
valid = false;
break;
}
}
}
if (valid || proxy == null) continue;
proxy.Enough = true;
proxy.NumOfFailIncrement();
Debug.WriteLine($"OLD Proxy: {proxy.ProxyString} | NOF: {proxy.FailCounter} | UC: {proxy.UsageCounter}");
//Thread.Sleep(300);
}
while (!valid && (maxTries == -1 || ++triesCounter < maxTries));
if (valid)
proxy?.ResetFailCounter();
//writeLineDEBUG($"Valid Content Proxy: { proxy.ProxyString } | UC: { proxy.useCounter }");
return content;
}
public static async Task<HttpStatusCode> MakeSureFileDownloaded(HttpMethod httpMethod, string url, string path, bool overrideExist = true, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
HttpStatusCode statusCode;
bool downloaded;
var triesCounter = 0;
do
{
if (proxy != null)
{
while (proxy != null && !proxy.Increment())
{
proxy = ProxyHelper.GetAvailableProxy();
}
//writeLineDEBUG($"NEW Proxy: { proxy.ProxyString } | NOF: { proxy.numOfFail } | UC: { proxy.useCounter }");
}
else if (ProxyHelper.UseProxies)
{
proxy = ProxyHelper.GetAvailableProxy();
}
statusCode = await DownloadFile(httpMethod, url, path, overrideExist, post, timeout, cookies, proxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (autoRedirect == false && statusCode == HttpStatusCode.Redirect)
{
downloaded = true;
break;
}
downloaded = statusCode is HttpStatusCode.OK or HttpStatusCode.Found;
if (!downloaded)
{
if (proxy != null)
{
proxy.Enough = true;
proxy.NumOfFailIncrement();
Debug.WriteLine($"OLD Proxy: {proxy.ProxyString} | NOF: {proxy.FailCounter} | UC: {proxy.UsageCounter} | Download:{statusCode}");
}
//Thread.Sleep(300);
}
} while (!downloaded && (maxTries == -1 || ++triesCounter < maxTries));
if (downloaded)
proxy?.ResetFailCounter();
return statusCode;
}
public static async Task<byte[]?> MakeSureFileDownloadedToMemory(HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
byte[]? result;
bool downloaded;
var triesCounter = 0;
do
{
if (proxy != null)
{
while (proxy != null && !proxy.Increment())
{
proxy = ProxyHelper.GetAvailableProxy();
}
//writeLineDEBUG($"NEW Proxy: { proxy.ProxyString } | NOF: { proxy.numOfFail } | UC: { proxy.useCounter }");
}
else if (ProxyHelper.UseProxies)
{
proxy = ProxyHelper.GetAvailableProxy();
}
result = await DownloadFileToMemory(httpMethod, url, post, timeout, cookies, proxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
//BadGateway > 502 | Forbidden > 403 | Unauthorized > 401 etc....
downloaded = result != null && result.Length != 3;
if (downloaded || (autoRedirect == false && result == Encoding.UTF8.GetBytes(HttpStatusCode.Redirect.ToString())))
break;
if (!downloaded)
{
if (proxy != null)
{
proxy.Enough = true;
proxy.NumOfFailIncrement();
Debug.WriteLine($"OLD Proxy: {proxy.ProxyString} | NOF: {proxy.FailCounter} | UC: {proxy.UsageCounter}");
}
//Thread.Sleep(300);
}
} while (!downloaded && (maxTries == -1 || ++triesCounter < maxTries));
if (downloaded)
proxy?.ResetFailCounter();
return result;
}
public static async Task<string> Request(HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, Proxy? proxy = null, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
string output;
try
{
var response = await SendAsync(httpMethod, url, post, timeout, cookies, proxy?.WebProxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (!autoRedirect && response.StatusCode == HttpStatusCode.Redirect)
return $"$Redirected to$|:{response.Headers.Location}";
output = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (Exception e)
{
var err = e.InnerException == null ? e.Message : e.InnerException.Message;
//writeLineDEBUG(err);
output = err;
}
return output;
}
public static async Task<HttpStatusCode> DownloadFile(HttpMethod httpMethod, string url, string path, bool overrideExist = true, byte[]? post = null, int timeout = 120_000, CookieContainer? cookies = null, Proxy? proxy = null, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
url = TryGetValidUrl(url)!;
if (string.IsNullOrWhiteSpace(url)) return HttpStatusCode.RequestUriTooLong;
if (!overrideExist && File.Exists(path)) return HttpStatusCode.Found;
try
{
var response = await SendAsync(httpMethod, url, post, timeout, cookies, proxy?.WebProxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.Found)) return response.StatusCode;
await using var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
await using var fs = File.Create(path);
await responseStream.CopyToAsync(fs).ConfigureAwait(false);
}
catch
{
return HttpStatusCode.BadRequest;
}
return HttpStatusCode.OK;
}
public static async Task<byte[]?> DownloadFileToMemory(HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 120_000, CookieContainer? cookies = null, Proxy? proxy = null, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
url = TryGetValidUrl(url)!;
if (string.IsNullOrWhiteSpace(url)) return default;
try
{
var response = await SendAsync(httpMethod, url, post, timeout, cookies, proxy?.WebProxy, autoRedirect, aHeaders, noProxy).ConfigureAwait(false);
if (response.StatusCode is not HttpStatusCode.OK)
return Encoding.UTF8.GetBytes(((int)response.StatusCode).ToString());
return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
catch
{
return default;
}
}
private static Task<HttpResponseMessage> SendAsync(HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, CookieContainer? cookies = null, WebProxy? proxy = null, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool noProxy = false)
{
var uri = new Uri(url);
var finalProxy = noProxy ? null : proxy ?? _localProxy;
#if Http2
var handler = (Http2CustomHandler)CreateWinHttpHandler(timeout, cookies, finalProxy, autoRedirect);
#else
var handler = CreateHttpHandler(cookies, proxy, autoRedirect);
#endif
using var client = new HttpClient(handler);
client.DefaultRequestHeaders.Host = uri.Host;
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
var request = new HttpRequestMessage
{
RequestUri = uri,
Method = httpMethod
};
request.SetTimeout(TimeSpan.FromMilliseconds(timeout));
request.Headers.ExpectContinue = false;
if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "accept"))
request.Headers.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "accept-encoding"))
request.Headers.AcceptEncoding.ParseAdd("gzip, deflate, br");
if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "accept-language"))
request.Headers.AcceptLanguage.ParseAdd("en-US,en;q=0.9,ar;q=0.8");
//if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "referer"))
// request.Headers.Referrer = uri;
if (aHeaders != null)
foreach (var header in aHeaders)
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
#if SEND_LUMINATI_HEADER
if (Bot.OnlyPaidProxies)
request.Headers.TryAddWithoutValidation("x-lpm-session", ProxySessionId);
#endif
if (post != null)
{
request.Content = new ByteArrayContent(post);
var contentType = aHeaders?.FirstOrDefault(h => h.Key.Equals("content-type", StringComparison.InvariantCultureIgnoreCase)).Value;
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType ?? "application/x-www-form-urlencoded");
}
return client.SendAsync(request);
}
public static async Task<string> GetValidContent<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, string wordsToSearch, byte[]? post = null, int timeout = 60_000, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
var triesCounter = 0;
while (maxTries == -1 || triesCounter < maxTries)
{
var content = await Request(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (autoRedirect == false && content.StartsWith("$Redirected to$|:"))
break;
if (string.IsNullOrEmpty(wordsToSearch) || wordsToSearch.Split('|').Any(w => content.Contains(w, StringComparison.OrdinalIgnoreCase)))
return content;
await Task.Delay(700).ConfigureAwait(false);
triesCounter++;
}
return string.Empty;
}
public static async Task<string> GetContentDoesNotContain<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, string wordsToSearch, byte[]? post = null, int timeout = 60_000, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null, bool alsoNotEmpty = true, int notLessThan = 700) where T : HttpMessageHandler
{
var triesCounter = 0;
while (maxTries == -1 || triesCounter < maxTries)
{
var content = await Request(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (autoRedirect == false && content.StartsWith("$Redirected to$|:"))
break;
if ((!alsoNotEmpty || content.Length > notLessThan) && (string.IsNullOrEmpty(wordsToSearch) || !wordsToSearch.Split('|').Any(word => content.Contains(word, StringComparison.OrdinalIgnoreCase))))
return content;
await Task.Delay(700).ConfigureAwait(false);
triesCounter++;
}
return string.Empty;
}
public static async Task<HttpStatusCode> MakeSureFileDownloaded<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, string path, bool overrideExist = true, byte[]? post = null, int timeout = 60_000, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
HttpStatusCode statusCode;
bool downloaded;
var triesCounter = 0;
do
{
statusCode = await DownloadFile(client, httpMethod, url, path, overrideExist, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (autoRedirect == false && statusCode == HttpStatusCode.Redirect)
break;
downloaded = statusCode is HttpStatusCode.OK or HttpStatusCode.Found;
if (!downloaded)
await Task.Delay(700).ConfigureAwait(false);
}
while (!downloaded && (maxTries == -1 || ++triesCounter < maxTries));
return statusCode;
}
public static async Task<byte[]?> MakeSureFileDownloadedToMemory<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, int maxTries = -1, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
byte[]? result;
bool downloaded;
var triesCounter = 0;
do
{
result = await DownloadFileToMemory(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
//BadGateway > 502 | Forbidden > 403 | Unauthorized > 401 etc....
downloaded = result != null && result.Length != 3;
if (downloaded || (autoRedirect == false && result == Encoding.UTF8.GetBytes(HttpStatusCode.Redirect.ToString())))
break;
await Task.Delay(700).ConfigureAwait(false);
}
while (!downloaded && (maxTries == -1 || ++triesCounter < maxTries));
return result;
}
public static async Task<string> Request<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
string output;
try
{
var response = await SendAsync(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (!autoRedirect && response.StatusCode == HttpStatusCode.Redirect)
return $"$Redirected to$|:{response.Headers.Location}";
output = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (Exception e)
{
var err = e.InnerException == null ? e.Message : e.InnerException.Message;
//writeLineDEBUG(err);
output = err;
}
return output;
}
public static async Task<HttpStatusCode> DownloadFile<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, string path, bool overrideExist = true, byte[]? post = null, int timeout = 120_000, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
url = TryGetValidUrl(url)!;
if (string.IsNullOrWhiteSpace(url)) return HttpStatusCode.RequestUriTooLong;
if (!overrideExist && File.Exists(path)) return HttpStatusCode.Found;
try
{
var response = await SendAsync(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (response.StatusCode is not (HttpStatusCode.OK or HttpStatusCode.Found)) return response.StatusCode;
await using var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
await using var fs = File.Create(path);
await responseStream.CopyToAsync(fs).ConfigureAwait(false);
}
catch
{
return HttpStatusCode.BadRequest;
}
return HttpStatusCode.OK;
}
public static async Task<byte[]?> DownloadFileToMemory<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 120_000, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
url = TryGetValidUrl(url)!;
if (string.IsNullOrWhiteSpace(url)) return default;
try
{
var response = await SendAsync(client, httpMethod, url, post, timeout, autoRedirect, aHeaders).ConfigureAwait(false);
if (response.StatusCode is not HttpStatusCode.OK)
return Encoding.UTF8.GetBytes(((int)response.StatusCode).ToString());
return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
catch
{
return default;
}
}
private static Task<HttpResponseMessage> SendAsync<T>(CustomHttpClient<T> client, HttpMethod httpMethod, string url, byte[]? post = null, int timeout = 60_000, bool autoRedirect = true, Dictionary<string, string?>? aHeaders = null) where T : HttpMessageHandler
{
var uri = new Uri(url);
var request = new HttpRequestMessage
{
RequestUri = uri,
Method = httpMethod
};
request.SetTimeout(TimeSpan.FromMilliseconds(timeout));
request.Headers.ExpectContinue = false;
//if (aHeaders == null || aHeaders.Keys.All(k => k.ToLower() != "referer"))
// request.Headers.Referrer = uri;
if (aHeaders != null)
foreach (var header in aHeaders)
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
#if SEND_LUMINATI_HEADER
if (Bot.OnlyPaidProxies)
request.Headers.TryAddWithoutValidation("x-lpm-session", ProxySessionId);
#endif
if (post != null)
{
request.Content = new ByteArrayContent(post);
var contentType = aHeaders?.FirstOrDefault(h => h.Key.Equals("content-type", StringComparison.InvariantCultureIgnoreCase)).Value;
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType ?? "application/x-www-form-urlencoded");
}
TryToSetHandlerRedirect(client.Handler, autoRedirect);
return client.SendAsync(request);
}
/// <summary>
/// Returns a valid URL if it's valid or missing just http: |
/// Returns null if it's not valid
/// </summary>
public static string? TryGetValidUrl(string? url)
{
if (url == null) return null;
if (url.StartsWith("//")) url = $"http:{url}";
return CheckUrlValid(url) ? url : null;
}
public static bool CheckUrlValid(string source)
{
return Uri.TryCreate(source, UriKind.Absolute, out var uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}
private static async void KeepUpdatingLocalProxy()
{
#if DEBUG
while (true)
{
try
{
using var client = new System.Net.Sockets.TcpClient();
var result = client.BeginConnect("127.0.0.1", 17073, null, null);
result.AsyncWaitHandle.WaitOne(2000);
client.EndConnect(result);
_localProxy = _localProxy ?? new WebProxy("127.0.0.1", 17073);
}
catch
{
_localProxy = null;
}
await Task.Delay(3000).ConfigureAwait(false);
}
#else
_localProxy = null;
#endif
// ReSharper disable once FunctionNeverReturns
}
#region Http Client & Handler
public static CustomHttpClient<T> CreateHttpClient<T>(T handler, bool disposeHandler = true) where T : HttpMessageHandler
{
var client = new CustomHttpClient<T>(handler, disposeHandler);
client.DefaultRequestHeaders.UserAgent.ParseAdd(UserAgent);
client.DefaultRequestHeaders.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9,ar;q=0.8");
//client.DefaultRequestHeaders.ExpectContinue = false;
return client;
}
public static HttpClientHandler CreateHttpHandler(CookieContainer? cookies = null, WebProxy? proxy = null, bool autoRedirect = true)
{
return new HttpClientHandler
{
ServerCertificateCustomValidationCallback = delegate { return true; },
SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12,
UseProxy = proxy != null,
Proxy = proxy,
UseCookies = /*cookies != null*/ true,
CookieContainer = cookies ?? new CookieContainer(),
AllowAutoRedirect = autoRedirect,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli
};
}
#if Http2
public static WinHttpHandler CreateWinHttpHandler(int timeout = 60_000, CookieContainer? cookies = null, WebProxy? proxy = null, bool autoRedirect = true, bool keepAlive = true)
{
var sTimeout = TimeSpan.FromMilliseconds(timeout);
return new WinHttpHandler
{
ServerCertificateValidationCallback = delegate { return true; },
SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12,
WindowsProxyUsePolicy = proxy == null ? WindowsProxyUsePolicy.DoNotUseProxy : WindowsProxyUsePolicy.UseCustomProxy,
Proxy = proxy,
CookieUsePolicy = /*cookies == null ? CookieUsePolicy.IgnoreCookies : */CookieUsePolicy.UseSpecifiedCookieContainer,
CookieContainer = cookies ?? new CookieContainer(),
AutomaticRedirection = autoRedirect,
TcpKeepAliveEnabled = keepAlive,
ReceiveDataTimeout = sTimeout,
ReceiveHeadersTimeout = sTimeout,
SendTimeout = sTimeout,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli
};
}
#endif
private static void TryToSetHandlerRedirect<T>(T handler, bool autoRedirect = true) where T : HttpMessageHandler
{
switch (handler)
{
case WinHttpHandler whh:
whh.AutomaticRedirection = autoRedirect;
break;
case HttpClientHandler hch:
hch.AllowAutoRedirect = autoRedirect;
break;
}
}
public static void SetTimeout(this HttpRequestMessage request, TimeSpan? timeout)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
request.Options.Set(TimeoutOptionsKey, timeout);
}
public static TimeSpan? GetTimeout(this HttpRequestMessage request)
{
if (request == null)
throw new ArgumentNullException(nameof(request));
return request.Options.TryGetValue(TimeoutOptionsKey, out var value) ? value : null;
}
public class CustomHttpClient<T> : HttpClient where T : HttpMessageHandler
{
//public TimeSpan DefaultTimeout { get; set; } = TimeSpan.FromSeconds(100);
public T Handler { get; }
public CustomHttpClient(T handler, bool disposeHandler = true) : base(handler, disposeHandler)
{
Timeout = System.Threading.Timeout.InfiniteTimeSpan;
Handler = handler;
}
public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
#if Http2
if (Handler is WinHttpHandler)
request.Version = new Version("2.0");
#endif
using var cts = GetCancellationTokenSource(request, cancellationToken);
try
{
var response = await base.SendAsync(request, cts?.Token ?? cancellationToken).ConfigureAwait(false);
if (!response.Content.Headers.TryGetValues("Content-Encoding", out var ce) || ce.First() != "br")
return response;
//var buffer = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
//response.Content = new ByteArrayContent(Brotli.DecompressBuffer(buffer, 0, buffer.Length));
var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
response.Content = new StreamContent(new BrotliStream(stream, CompressionMode.Decompress));
return response;
}
catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)
{
throw new TimeoutException(ex.Message, ex);
}
}
private CancellationTokenSource? GetCancellationTokenSource(HttpRequestMessage request, CancellationToken cancellationToken)
{
var timeout = request.GetTimeout() ?? Timeout;
if (timeout == System.Threading.Timeout.InfiniteTimeSpan)
{
// No need to create a CTS if there's no timeout
return null;
}
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(timeout);
return cts;
}
}
#if Http2
public class Http2CustomHandler : WinHttpHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Version = new Version("2.0");
var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (!response.Content.Headers.TryGetValues("Content-Encoding", out var ce) || ce.First() != "br")
return response;
//var buffer = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
//response.Content = new ByteArrayContent(Brotli.DecompressBuffer(buffer, 0, buffer.Length));
var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
response.Content = new StreamContent(new BrotliStream(stream, CompressionMode.Decompress));
return response;
}
}
#endif
#endregion
}
|
e8f15fcbdeeeb172404665e6fee13f82
|
{
"intermediate": 0.35278746485710144,
"beginner": 0.40159815549850464,
"expert": 0.2456144243478775
}
|
9,549
|
нужно исправить код: public.test_mv_incident_report_monitor as SELECT i.id, i.rule_id, i.rule_group, i.uuser, i.created_at, i.priority, i.is_deals, i.is_blacklisted, CASE WHEN i.is_deals THEN min(b.dealdtime) ELSE min(osec.dtime) END AS incidentstartdtime, CASE WHEN i.is_deals THEN max(b.dealdtime) ELSE max(osec.dtime) END AS incidentenddtime, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.ticker::text, ','::text) ELSE string_agg(DISTINCT osec.ticker::text, ','::text) END AS ticker, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.business::text, ','::text) ELSE string_agg(DISTINCT osec.business::text, ','::text) END AS business, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.counterparty::text, ','::text) ELSE string_agg(DISTINCT osec.counterparty::text, ','::text) END AS counterparty, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.client::text, ','::text) ELSE string_agg(DISTINCT osec.client::text, ','::text) END AS client, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.dealmode::text, ','::text) ELSE string_agg(DISTINCT osec.dealmode::text, ','::text) END AS dealmode, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.dealtype::text, ','::text) ELSE string_agg(DISTINCT osec.dealtype::text, ','::text) END AS dealtype, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.desk::text, ','::text) ELSE ''::text END AS desk, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.entity::text, ','::text) ELSE ''::text END AS entity, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.location::text, ','::text) ELSE string_agg(DISTINCT osec.placement_location::text, ','::text) END AS location, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.portfolio::text, ','::text) ELSE ''::text END AS portfolio, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.salesteam::text, ','::text) ELSE ''::text END AS sales_team, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.trader::text, ','::text) ELSE string_agg(DISTINCT osec.trader::text, ','::text) END AS trader, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.user_id::text, ','::text) ELSE string_agg(DISTINCT osec.user_id::text, ','::text) END AS "user", CASE WHEN i.is_deals THEN string_agg(DISTINCT b.venue::text, ','::text) ELSE string_agg(DISTINCT osec.venue::text, ','::text) END AS venue, string_agg(DISTINCT ri.asset_class::text, ','::text) AS asset_class, string_agg(DISTINCT ri.business_line::text, ','::text) AS business_line, oa.job_id AS jobid, i.financial_result_rub, i.financial_result_usd, i.financial_result_eur, i.financial_result_cny, rr.rule_name, i.mode_incident, rr.is_archived, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.middleoffice::text, ','::text) ELSE string_agg(DISTINCT osec.middle_office::text, ','::text) END AS middle_office, CASE WHEN i.is_deals THEN string_agg(DISTINCT b.back_office::text, ','::text) ELSE string_agg(DISTINCT osec.back_office::text, ','::text) END AS back_office FROM operation_audit oa JOIN incident_monitor i ON oa.tafs_id = i.id AND oa.entity_type::text = 'INCIDENT_MONITOR'::text LEFT JOIN incident_monitor_deals d ON i.id = d.incident_id AND d.check_orders = false LEFT JOIN deals_import b ON b.id = d.deal_id LEFT JOIN incident_monitor_orders io ON i.id = io.incident_id AND io.check_deals = false LEFT JOIN orders_import osec ON osec.id = io.order_id LEFT JOIN ref_issues ri ON ri.ticker::text = b.ticker::text AND ri.venue::text = b.venue::text OR ri.ticker::text = osec.ticker::text AND ri.venue::text = osec.venue::text AND ri.active LEFT JOIN ref_rules rr ON i.rule_id::text = rr.rule_id::text GROUP BY i.id, i.rule_id, i.rule_group, i.uuser, i.created_at, i.priority, i.is_deals, i.is_blacklisted, oa.job_id, rr.rule_name, rr.is_archived; alter materialized view public.test_mv_incident_report_monitor owner to ap; так, чтобы добавилось поле watchlist, в котором выводились name из таблицы watch_list_ref_counterparty ( id uuid not null constraint watch_list_ref_counterparty_pk primary key, name varchar, ref_counterparty_id_list varchar, count_incidents_without_status integer, count_incidents_with_status integer ); для клиентов, в которых они участвуют
|
0943bcc9c1ed7144beefdbc7a2f4a672
|
{
"intermediate": 0.23415471613407135,
"beginner": 0.4726247489452362,
"expert": 0.29322052001953125
}
|
9,550
|
Can you create me a Minecraft Skript that toggles pvp on and off, but players with permission event.pvpbypass can attack even if pvp is disabled?
|
7a7d497763c5b400d0a629ab23a9ae07
|
{
"intermediate": 0.4910169541835785,
"beginner": 0.19779238104820251,
"expert": 0.311190664768219
}
|
9,551
|
what I want to do here is to make a visual marix constructor onhover menu, which you can use to update these vertices and edges arrays on the fly to model or draw in that visual marix constructor. I'm not sure how to corretly interpret that VMC. any ideas?: 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],
];
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],
];
// 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;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
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, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
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;
});
|
ae8274341050b1abf3ecd8c93d87acf2
|
{
"intermediate": 0.3572104275226593,
"beginner": 0.31404921412467957,
"expert": 0.3287404179573059
}
|
9,552
|
need that menu to disappear while out of the model bounds or range, because it glitching the performance. maybe you can do that mousemove function even better? output full fixed mousemove function code. also, there is some problem with the reddot not appearing when hovering on vertices. need to make that reddot to be the point where you point the cursor and from that exact point you can add a new edge option. I have already some style for that reddot point as well.: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
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],
];
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],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
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];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 10 / 1;
const amplitude = maxDeviation / 1;
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.008;
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 + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.5);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.5);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
if (bestIndex === -1) {
redDot.style.display = 'none';
} else {
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
}
}
else {
vmcMenu.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}); here's style: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 32px;
height: 32px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
<div class="red-dot" id="red-dot"></div>
</div>
</body>
</html>
|
3dec1397fe8e2aa5399f5e5406fb9e77
|
{
"intermediate": 0.46562841534614563,
"beginner": 0.3070106506347656,
"expert": 0.2273610234260559
}
|
9,553
|
need that menu to disappear while out of the model bounds or range, because it glitching the performance. maybe you can do that mousemove function even better? output full fixed mousemove function code. also, there is some problem with the reddot not appearing when hovering on vertices. need to make that reddot to be the point where you point the cursor and from that exact point you can add a new edge option. I have already some style for that reddot point as well.: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
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],
];
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],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
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];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 10 / 1;
const amplitude = maxDeviation / 1;
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.008;
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 + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.5);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.5);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
if (bestIndex === -1) {
redDot.style.display = 'none';
} else {
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
}
}
else {
vmcMenu.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}); here's style: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 32px;
height: 32px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
<div class="red-dot" id="red-dot"></div>
</div>
</body>
</html>
|
577db359d75993d17cf460888eb65c06
|
{
"intermediate": 0.46562841534614563,
"beginner": 0.3070106506347656,
"expert": 0.2273610234260559
}
|
9,554
|
how to filter array in javascript and check the other array?
|
709e7814f38ace8ef680d00453f9eb6a
|
{
"intermediate": 0.6138095855712891,
"beginner": 0.09578384459018707,
"expert": 0.29040658473968506
}
|
9,555
|
I am using the function check_not_nested in R 4.0.2 and it works just fine, but when switching to R 4.2.2 I get the following error message:
Function check_not_nested not found in environment usethis.
why?
|
2f854a8a457805f0e18eeb645aa6829d
|
{
"intermediate": 0.4152269661426544,
"beginner": 0.3888686001300812,
"expert": 0.1959044188261032
}
|
9,556
|
Convert string 192.168.110.1 date=2023-06-01 time=14:45:29 devname="FG60_CHITA_2" devid="FGT60FTK21027413" eventtime=1685598329379539561 tz="+0900" logid="0419016384" type="utm" to JSON
|
db6cb609aee3bf425ed356c1c544f58a
|
{
"intermediate": 0.3936181366443634,
"beginner": 0.23018763959407806,
"expert": 0.37619420886039734
}
|
9,557
|
do you have an api that i can use
|
dc974b3a8c3fa7555ce2ecbc931fc285
|
{
"intermediate": 0.6702500581741333,
"beginner": 0.1453167349100113,
"expert": 0.1844332367181778
}
|
9,558
|
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 = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
params = {
"symbol": symbol,
"interval": interval,
"startTime": int(dt.datetime.timestamp(dt.datetime.now() - dt.timedelta(minutes=lookback))),
"endTime": int(dt.datetime.timestamp(dt.datetime.now()))
}
response = requests.get(url, params=params)
data = response.json()
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append([
timestamp,
float(d[1]),
float(d[2]),
float(d[3]),
float(d[4]),
float(d[5])
])
df = pd.DataFrame(ohlc, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume'])
df.set_index('Open time', inplace=True)
return df
df = get_klines('BTCUSDT', '15m', 1440)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '15m', 1440)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
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)
while True:
df = get_klines('BTCUSDT', '15m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 209, in <module>
signal = signal_generator(df)
^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 66, in signal_generator
open = df.Open.iloc[-1]
~~~~~~~~~~~~^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\indexing.py", line 1103, in __getitem__
return self._getitem_axis(maybe_callable, axis=axis)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\indexing.py", line 1656, in _getitem_axis
self._validate_integer(key, axis)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\indexing.py", line 1589, in _validate_integer
raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds, What I need to change ?
|
efef55ce5dc3ea17fcbcc0d8bb91745d
|
{
"intermediate": 0.40732917189598083,
"beginner": 0.36594638228416443,
"expert": 0.22672443091869354
}
|
9,559
|
can you use python and chromedrive to webscrape data from this website, https://brokercheck.finra.org/, my input would be the name, output would be the examinations part on the website
|
7ad821ab751e7168ec9b7628085d7033
|
{
"intermediate": 0.4919739067554474,
"beginner": 0.11976458877325058,
"expert": 0.3882615566253662
}
|
9,560
|
Wenn ich in flutter einen Qr_Code scanne dann kommt die Fehlermeldung im Code:
"Disposed CameraController"
"StopImageStream() was called on a disposed CameraController"
Wie fixe ich das?
void _throwIfNotInitialized(String functionName) {
if (!value.isInitialized) {
throw CameraException(
'Uninitialized CameraController',
'$functionName() was called on an uninitialized CameraController.',
);
}
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'$functionName() was called on a disposed CameraController.',
);
}
}
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:math';
import 'package:camera_platform_interface/camera_platform_interface.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../camera.dart';
/// Signature for a callback receiving the a camera image.
///
/// This is used by [CameraController.startImageStream].
// TODO(stuartmorgan): Fix this naming the next time there's a breaking change
// to this package.
// ignore: camel_case_types
typedef onLatestImageAvailable = Function(CameraImage image);
/// Completes with a list of available cameras.
///
/// May throw a [CameraException].
Future<List<CameraDescription>> availableCameras() async {
return CameraPlatform.instance.availableCameras();
}
// TODO(stuartmorgan): Remove this once the package requires 2.10, where the
// dart:async `unawaited` accepts a nullable future.
void _unawaited(Future<void>? future) {}
/// The state of a [CameraController].
class CameraValue {
/// Creates a new camera controller state.
const CameraValue({
required this.isInitialized,
this.errorDescription,
this.previewSize,
required this.isRecordingVideo,
required this.isTakingPicture,
required this.isStreamingImages,
required bool isRecordingPaused,
required this.flashMode,
required this.exposureMode,
required this.focusMode,
required this.exposurePointSupported,
required this.focusPointSupported,
required this.deviceOrientation,
required this.description,
this.lockedCaptureOrientation,
this.recordingOrientation,
this.isPreviewPaused = false,
this.previewPauseOrientation,
}) : _isRecordingPaused = isRecordingPaused;
/// Creates a new camera controller state for an uninitialized controller.
const CameraValue.uninitialized(CameraDescription description)
: this(
isInitialized: false,
isRecordingVideo: false,
isTakingPicture: false,
isStreamingImages: false,
isRecordingPaused: false,
flashMode: FlashMode.auto,
exposureMode: ExposureMode.auto,
exposurePointSupported: false,
focusMode: FocusMode.auto,
focusPointSupported: false,
deviceOrientation: DeviceOrientation.portraitUp,
isPreviewPaused: false,
description: description,
);
/// True after [CameraController.initialize] has completed successfully.
final bool isInitialized;
/// True when a picture capture request has been sent but as not yet returned.
final bool isTakingPicture;
/// True when the camera is recording (not the same as previewing).
final bool isRecordingVideo;
/// True when images from the camera are being streamed.
final bool isStreamingImages;
final bool _isRecordingPaused;
/// True when the preview widget has been paused manually.
final bool isPreviewPaused;
/// Set to the orientation the preview was paused in, if it is currently paused.
final DeviceOrientation? previewPauseOrientation;
/// True when camera [isRecordingVideo] and recording is paused.
bool get isRecordingPaused => isRecordingVideo && _isRecordingPaused;
/// Description of an error state.
///
/// This is null while the controller is not in an error state.
/// When [hasError] is true this contains the error description.
final String? errorDescription;
/// The size of the preview in pixels.
///
/// Is `null` until [isInitialized] is `true`.
final Size? previewSize;
/// Convenience getter for `previewSize.width / previewSize.height`.
///
/// Can only be called when [initialize] is done.
double get aspectRatio => previewSize!.width / previewSize!.height;
/// Whether the controller is in an error state.
///
/// When true [errorDescription] describes the error.
bool get hasError => errorDescription != null;
/// The flash mode the camera is currently set to.
final FlashMode flashMode;
/// The exposure mode the camera is currently set to.
final ExposureMode exposureMode;
/// The focus mode the camera is currently set to.
final FocusMode focusMode;
/// Whether setting the exposure point is supported.
final bool exposurePointSupported;
/// Whether setting the focus point is supported.
final bool focusPointSupported;
/// The current device UI orientation.
final DeviceOrientation deviceOrientation;
/// The currently locked capture orientation.
final DeviceOrientation? lockedCaptureOrientation;
/// Whether the capture orientation is currently locked.
bool get isCaptureOrientationLocked => lockedCaptureOrientation != null;
/// The orientation of the currently running video recording.
final DeviceOrientation? recordingOrientation;
/// The properties of the camera device controlled by this controller.
final CameraDescription description;
/// Creates a modified copy of the object.
///
/// Explicitly specified fields get the specified value, all other fields get
/// the same value of the current object.
CameraValue copyWith({
bool? isInitialized,
bool? isRecordingVideo,
bool? isTakingPicture,
bool? isStreamingImages,
String? errorDescription,
Size? previewSize,
bool? isRecordingPaused,
FlashMode? flashMode,
ExposureMode? exposureMode,
FocusMode? focusMode,
bool? exposurePointSupported,
bool? focusPointSupported,
DeviceOrientation? deviceOrientation,
Optional<DeviceOrientation>? lockedCaptureOrientation,
Optional<DeviceOrientation>? recordingOrientation,
bool? isPreviewPaused,
CameraDescription? description,
Optional<DeviceOrientation>? previewPauseOrientation,
}) {
return CameraValue(
isInitialized: isInitialized ?? this.isInitialized,
errorDescription: errorDescription,
previewSize: previewSize ?? this.previewSize,
isRecordingVideo: isRecordingVideo ?? this.isRecordingVideo,
isTakingPicture: isTakingPicture ?? this.isTakingPicture,
isStreamingImages: isStreamingImages ?? this.isStreamingImages,
isRecordingPaused: isRecordingPaused ?? _isRecordingPaused,
flashMode: flashMode ?? this.flashMode,
exposureMode: exposureMode ?? this.exposureMode,
focusMode: focusMode ?? this.focusMode,
exposurePointSupported:
exposurePointSupported ?? this.exposurePointSupported,
focusPointSupported: focusPointSupported ?? this.focusPointSupported,
deviceOrientation: deviceOrientation ?? this.deviceOrientation,
lockedCaptureOrientation: lockedCaptureOrientation == null
? this.lockedCaptureOrientation
: lockedCaptureOrientation.orNull,
recordingOrientation: recordingOrientation == null
? this.recordingOrientation
: recordingOrientation.orNull,
isPreviewPaused: isPreviewPaused ?? this.isPreviewPaused,
description: description ?? this.description,
previewPauseOrientation: previewPauseOrientation == null
? this.previewPauseOrientation
: previewPauseOrientation.orNull,
);
}
@override
String toString() {
return '${objectRuntimeType(this, 'CameraValue')}('
'isRecordingVideo: $isRecordingVideo, '
'isInitialized: $isInitialized, '
'errorDescription: $errorDescription, '
'previewSize: $previewSize, '
'isStreamingImages: $isStreamingImages, '
'flashMode: $flashMode, '
'exposureMode: $exposureMode, '
'focusMode: $focusMode, '
'exposurePointSupported: $exposurePointSupported, '
'focusPointSupported: $focusPointSupported, '
'deviceOrientation: $deviceOrientation, '
'lockedCaptureOrientation: $lockedCaptureOrientation, '
'recordingOrientation: $recordingOrientation, '
'isPreviewPaused: $isPreviewPaused, '
'previewPausedOrientation: $previewPauseOrientation, '
'description: $description)';
}
}
/// Controls a device camera.
///
/// Use [availableCameras] to get a list of available cameras.
///
/// Before using a [CameraController] a call to [initialize] must complete.
///
/// To show the camera preview on the screen use a [CameraPreview] widget.
class CameraController extends ValueNotifier<CameraValue> {
/// Creates a new camera controller in an uninitialized state.
CameraController(
CameraDescription description,
this.resolutionPreset, {
this.enableAudio = true,
this.imageFormatGroup,
}) : super(CameraValue.uninitialized(description));
/// The properties of the camera device controlled by this controller.
CameraDescription get description => value.description;
/// The resolution this controller is targeting.
///
/// This resolution preset is not guaranteed to be available on the device,
/// if unavailable a lower resolution will be used.
///
/// See also: [ResolutionPreset].
final ResolutionPreset resolutionPreset;
/// Whether to include audio when recording a video.
final bool enableAudio;
/// The [ImageFormatGroup] describes the output of the raw image format.
///
/// When null the imageFormat will fallback to the platforms default.
final ImageFormatGroup? imageFormatGroup;
/// The id of a camera that hasn't been initialized.
@visibleForTesting
static const int kUninitializedCameraId = -1;
int _cameraId = kUninitializedCameraId;
bool _isDisposed = false;
StreamSubscription<CameraImageData>? _imageStreamSubscription;
FutureOr<bool>? _initCalled;
StreamSubscription<DeviceOrientationChangedEvent>?
_deviceOrientationSubscription;
/// Checks whether [CameraController.dispose] has completed successfully.
///
/// This is a no-op when asserts are disabled.
void debugCheckIsDisposed() {
assert(_isDisposed);
}
/// The camera identifier with which the controller is associated.
int get cameraId => _cameraId;
/// Initializes the camera on the device.
///
/// Throws a [CameraException] if the initialization fails.
Future<void> initialize() => _initializeWithDescription(description);
/// Initializes the camera on the device with the specified description.
///
/// Throws a [CameraException] if the initialization fails.
Future<void> _initializeWithDescription(CameraDescription description) async {
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'initialize was called on a disposed CameraController',
);
}
try {
final Completer<CameraInitializedEvent> initializeCompleter =
Completer<CameraInitializedEvent>();
_deviceOrientationSubscription = CameraPlatform.instance
.onDeviceOrientationChanged()
.listen((DeviceOrientationChangedEvent event) {
value = value.copyWith(
deviceOrientation: event.orientation,
);
});
_cameraId = await CameraPlatform.instance.createCamera(
description,
resolutionPreset,
enableAudio: enableAudio,
);
_unawaited(CameraPlatform.instance
.onCameraInitialized(_cameraId)
.first
.then((CameraInitializedEvent event) {
initializeCompleter.complete(event);
}));
await CameraPlatform.instance.initializeCamera(
_cameraId,
imageFormatGroup: imageFormatGroup ?? ImageFormatGroup.unknown,
);
value = value.copyWith(
isInitialized: true,
description: description,
previewSize: await initializeCompleter.future
.then((CameraInitializedEvent event) => Size(
event.previewWidth,
event.previewHeight,
)),
exposureMode: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.exposureMode),
focusMode: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.focusMode),
exposurePointSupported: await initializeCompleter.future.then(
(CameraInitializedEvent event) => event.exposurePointSupported),
focusPointSupported: await initializeCompleter.future
.then((CameraInitializedEvent event) => event.focusPointSupported),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
_initCalled = true;
}
/// Prepare the capture session for video recording.
///
/// Use of this method is optional, but it may be called for performance
/// reasons on iOS.
///
/// Preparing audio can cause a minor delay in the CameraPreview view on iOS.
/// If video recording is intended, calling this early eliminates this delay
/// that would otherwise be experienced when video recording is started.
/// This operation is a no-op on Android and Web.
///
/// Throws a [CameraException] if the prepare fails.
Future<void> prepareForVideoRecording() async {
await CameraPlatform.instance.prepareForVideoRecording();
}
/// Pauses the current camera preview
Future<void> pausePreview() async {
if (value.isPreviewPaused) {
return;
}
try {
await CameraPlatform.instance.pausePreview(_cameraId);
value = value.copyWith(
isPreviewPaused: true,
previewPauseOrientation: Optional<DeviceOrientation>.of(
value.lockedCaptureOrientation ?? value.deviceOrientation));
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Resumes the current camera preview
Future<void> resumePreview() async {
if (!value.isPreviewPaused) {
return;
}
try {
await CameraPlatform.instance.resumePreview(_cameraId);
value = value.copyWith(
isPreviewPaused: false,
previewPauseOrientation: const Optional<DeviceOrientation>.absent());
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the description of the camera.
///
/// Throws a [CameraException] if setting the description fails.
Future<void> setDescription(CameraDescription description) async {
if (value.isRecordingVideo) {
await CameraPlatform.instance.setDescriptionWhileRecording(description);
value = value.copyWith(description: description);
} else {
await _initializeWithDescription(description);
}
}
/// Captures an image and returns the file where it was saved.
///
/// Throws a [CameraException] if the capture fails.
Future<XFile> takePicture() async {
_throwIfNotInitialized('takePicture');
if (value.isTakingPicture) {
throw CameraException(
'Previous capture has not returned yet.',
'takePicture was called before the previous capture returned.',
);
}
try {
value = value.copyWith(isTakingPicture: true);
final XFile file = await CameraPlatform.instance.takePicture(_cameraId);
value = value.copyWith(isTakingPicture: false);
return file;
} on PlatformException catch (e) {
value = value.copyWith(isTakingPicture: false);
throw CameraException(e.code, e.message);
}
}
/// Start streaming images from platform camera.
///
/// Settings for capturing images on iOS and Android is set to always use the
/// latest image available from the camera and will drop all other images.
///
/// When running continuously with [CameraPreview] widget, this function runs
/// best with [ResolutionPreset.low]. Running on [ResolutionPreset.high] can
/// have significant frame rate drops for [CameraPreview] on lower end
/// devices.
///
/// Throws a [CameraException] if image streaming or video recording has
/// already started.
///
/// The `startImageStream` method is only available on Android and iOS (other
/// platforms won't be supported in current setup).
///
// TODO(bmparr): Add settings for resolution and fps.
Future<void> startImageStream(onLatestImageAvailable onAvailable) async {
assert(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
_throwIfNotInitialized('startImageStream');
if (value.isRecordingVideo) {
throw CameraException(
'A video recording is already started.',
'startImageStream was called while a video is being recorded.',
);
}
if (value.isStreamingImages) {
throw CameraException(
'A camera has started streaming images.',
'startImageStream was called while a camera was streaming images.',
);
}
try {
_imageStreamSubscription = CameraPlatform.instance
.onStreamedFrameAvailable(_cameraId)
.listen((CameraImageData imageData) {
onAvailable(CameraImage.fromPlatformInterface(imageData));
});
value = value.copyWith(isStreamingImages: true);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Stop streaming images from platform camera.
///
/// Throws a [CameraException] if image streaming was not started or video
/// recording was started.
///
/// The `stopImageStream` method is only available on Android and iOS (other
/// platforms won't be supported in current setup).
Future<void> stopImageStream() async {
assert(defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS);
_throwIfNotInitialized('stopImageStream');
if (!value.isStreamingImages) {
throw CameraException(
'No camera is streaming images',
'stopImageStream was called when no camera is streaming images.',
);
}
try {
value = value.copyWith(isStreamingImages: false);
await _imageStreamSubscription?.cancel();
_imageStreamSubscription = null;
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Start a video recording.
///
/// You may optionally pass an [onAvailable] callback to also have the
/// video frames streamed to this callback.
///
/// The video is returned as a [XFile] after calling [stopVideoRecording].
/// Throws a [CameraException] if the capture fails.
Future<void> startVideoRecording(
{onLatestImageAvailable? onAvailable}) async {
_throwIfNotInitialized('startVideoRecording');
if (value.isRecordingVideo) {
throw CameraException(
'A video recording is already started.',
'startVideoRecording was called when a recording is already started.',
);
}
Function(CameraImageData image)? streamCallback;
if (onAvailable != null) {
streamCallback = (CameraImageData imageData) {
onAvailable(CameraImage.fromPlatformInterface(imageData));
};
}
try {
await CameraPlatform.instance.startVideoCapturing(
VideoCaptureOptions(_cameraId, streamCallback: streamCallback));
value = value.copyWith(
isRecordingVideo: true,
isRecordingPaused: false,
recordingOrientation: Optional<DeviceOrientation>.of(
value.lockedCaptureOrientation ?? value.deviceOrientation),
isStreamingImages: onAvailable != null);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Stops the video recording and returns the file where it was saved.
///
/// Throws a [CameraException] if the capture failed.
Future<XFile> stopVideoRecording() async {
_throwIfNotInitialized('stopVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'stopVideoRecording was called when no video is recording.',
);
}
if (value.isStreamingImages) {
stopImageStream();
}
try {
final XFile file =
await CameraPlatform.instance.stopVideoRecording(_cameraId);
value = value.copyWith(
isRecordingVideo: false,
recordingOrientation: const Optional<DeviceOrientation>.absent(),
);
return file;
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Pause video recording.
///
/// This feature is only available on iOS and Android sdk 24+.
Future<void> pauseVideoRecording() async {
_throwIfNotInitialized('pauseVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'pauseVideoRecording was called when no video is recording.',
);
}
try {
await CameraPlatform.instance.pauseVideoRecording(_cameraId);
value = value.copyWith(isRecordingPaused: true);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Resume video recording after pausing.
///
/// This feature is only available on iOS and Android sdk 24+.
Future<void> resumeVideoRecording() async {
_throwIfNotInitialized('resumeVideoRecording');
if (!value.isRecordingVideo) {
throw CameraException(
'No video is recording',
'resumeVideoRecording was called when no video is recording.',
);
}
try {
await CameraPlatform.instance.resumeVideoRecording(_cameraId);
value = value.copyWith(isRecordingPaused: false);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Returns a widget showing a live camera preview.
Widget buildPreview() {
_throwIfNotInitialized('buildPreview');
try {
return CameraPlatform.instance.buildPreview(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the maximum supported zoom level for the selected camera.
Future<double> getMaxZoomLevel() {
_throwIfNotInitialized('getMaxZoomLevel');
try {
return CameraPlatform.instance.getMaxZoomLevel(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the minimum supported zoom level for the selected camera.
Future<double> getMinZoomLevel() {
_throwIfNotInitialized('getMinZoomLevel');
try {
return CameraPlatform.instance.getMinZoomLevel(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Set the zoom level for the selected camera.
///
/// The supplied [zoom] value should be between 1.0 and the maximum supported
/// zoom level returned by the `getMaxZoomLevel`. Throws an `CameraException`
/// when an illegal zoom level is suplied.
Future<void> setZoomLevel(double zoom) {
_throwIfNotInitialized('setZoomLevel');
try {
return CameraPlatform.instance.setZoomLevel(_cameraId, zoom);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the flash mode for taking pictures.
Future<void> setFlashMode(FlashMode mode) async {
try {
await CameraPlatform.instance.setFlashMode(_cameraId, mode);
value = value.copyWith(flashMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure mode for taking pictures.
Future<void> setExposureMode(ExposureMode mode) async {
try {
await CameraPlatform.instance.setExposureMode(_cameraId, mode);
value = value.copyWith(exposureMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure point for automatically determining the exposure value.
///
/// Supplying a `null` value will reset the exposure point to it's default
/// value.
Future<void> setExposurePoint(Offset? point) async {
if (point != null &&
(point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) {
throw ArgumentError(
'The values of point should be anywhere between (0,0) and (1,1).');
}
try {
await CameraPlatform.instance.setExposurePoint(
_cameraId,
point == null
? null
: Point<double>(
point.dx,
point.dy,
),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the minimum supported exposure offset for the selected camera in EV units.
Future<double> getMinExposureOffset() async {
_throwIfNotInitialized('getMinExposureOffset');
try {
return CameraPlatform.instance.getMinExposureOffset(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the maximum supported exposure offset for the selected camera in EV units.
Future<double> getMaxExposureOffset() async {
_throwIfNotInitialized('getMaxExposureOffset');
try {
return CameraPlatform.instance.getMaxExposureOffset(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Gets the supported step size for exposure offset for the selected camera in EV units.
///
/// Returns 0 when the camera supports using a free value without stepping.
Future<double> getExposureOffsetStepSize() async {
_throwIfNotInitialized('getExposureOffsetStepSize');
try {
return CameraPlatform.instance.getExposureOffsetStepSize(_cameraId);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the exposure offset for the selected camera.
///
/// The supplied [offset] value should be in EV units. 1 EV unit represents a
/// doubling in brightness. It should be between the minimum and maximum offsets
/// obtained through `getMinExposureOffset` and `getMaxExposureOffset` respectively.
/// Throws a `CameraException` when an illegal offset is supplied.
///
/// When the supplied [offset] value does not align with the step size obtained
/// through `getExposureStepSize`, it will automatically be rounded to the nearest step.
///
/// Returns the (rounded) offset value that was set.
Future<double> setExposureOffset(double offset) async {
_throwIfNotInitialized('setExposureOffset');
// Check if offset is in range
final List<double> range = await Future.wait(
<Future<double>>[getMinExposureOffset(), getMaxExposureOffset()]);
if (offset < range[0] || offset > range[1]) {
throw CameraException(
'exposureOffsetOutOfBounds',
'The provided exposure offset was outside the supported range for this device.',
);
}
// Round to the closest step if needed
final double stepSize = await getExposureOffsetStepSize();
if (stepSize > 0) {
final double inv = 1.0 / stepSize;
double roundedOffset = (offset * inv).roundToDouble() / inv;
if (roundedOffset > range[1]) {
roundedOffset = (offset * inv).floorToDouble() / inv;
} else if (roundedOffset < range[0]) {
roundedOffset = (offset * inv).ceilToDouble() / inv;
}
offset = roundedOffset;
}
try {
return CameraPlatform.instance.setExposureOffset(_cameraId, offset);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Locks the capture orientation.
///
/// If [orientation] is omitted, the current device orientation is used.
Future<void> lockCaptureOrientation([DeviceOrientation? orientation]) async {
try {
await CameraPlatform.instance.lockCaptureOrientation(
_cameraId, orientation ?? value.deviceOrientation);
value = value.copyWith(
lockedCaptureOrientation: Optional<DeviceOrientation>.of(
orientation ?? value.deviceOrientation));
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the focus mode for taking pictures.
Future<void> setFocusMode(FocusMode mode) async {
try {
await CameraPlatform.instance.setFocusMode(_cameraId, mode);
value = value.copyWith(focusMode: mode);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Unlocks the capture orientation.
Future<void> unlockCaptureOrientation() async {
try {
await CameraPlatform.instance.unlockCaptureOrientation(_cameraId);
value = value.copyWith(
lockedCaptureOrientation: const Optional<DeviceOrientation>.absent());
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Sets the focus point for automatically determining the focus value.
///
/// Supplying a `null` value will reset the focus point to it's default
/// value.
Future<void> setFocusPoint(Offset? point) async {
if (point != null &&
(point.dx < 0 || point.dx > 1 || point.dy < 0 || point.dy > 1)) {
throw ArgumentError(
'The values of point should be anywhere between (0,0) and (1,1).');
}
try {
await CameraPlatform.instance.setFocusPoint(
_cameraId,
point == null
? null
: Point<double>(
point.dx,
point.dy,
),
);
} on PlatformException catch (e) {
throw CameraException(e.code, e.message);
}
}
/// Releases the resources of this camera.
@override
Future<void> dispose() async {
if (_isDisposed) {
return;
}
_unawaited(_deviceOrientationSubscription?.cancel());
_isDisposed = true;
super.dispose();
if (_initCalled != null) {
await _initCalled;
await CameraPlatform.instance.dispose(_cameraId);
}
}
void _throwIfNotInitialized(String functionName) {
if (!value.isInitialized) {
throw CameraException(
'Uninitialized CameraController',
'$functionName() was called on an uninitialized CameraController.',
);
}
if (_isDisposed) {
throw CameraException(
'Disposed CameraController',
'$functionName() was called on a disposed CameraController.',
);
}
}
@override
void removeListener(VoidCallback listener) {
// Prevent ValueListenableBuilder in CameraPreview widget from causing an
// exception to be thrown by attempting to remove its own listener after
// the controller has already been disposed.
if (!_isDisposed) {
super.removeListener(listener);
}
}
}
/// A value that might be absent.
///
/// Used to represent [DeviceOrientation]s that are optional but also able
/// to be cleared.
@immutable
class Optional<T> extends IterableBase<T> {
/// Constructs an empty Optional.
const Optional.absent() : _value = null;
/// Constructs an Optional of the given [value].
///
/// Throws [ArgumentError] if [value] is null.
Optional.of(T value) : _value = value {
// TODO(cbracken): Delete and make this ctor const once mixed-mode
// execution is no longer around.
ArgumentError.checkNotNull(value);
}
/// Constructs an Optional of the given [value].
///
/// If [value] is null, returns [absent()].
const Optional.fromNullable(T? value) : _value = value;
final T? _value;
/// True when this optional contains a value.
bool get isPresent => _value != null;
/// True when this optional contains no value.
bool get isNotPresent => _value == null;
/// Gets the Optional value.
///
/// Throws [StateError] if [value] is null.
T get value {
if (_value == null) {
throw StateError('value called on absent Optional.');
}
return _value!;
}
/// Executes a function if the Optional value is present.
void ifPresent(void Function(T value) ifPresent) {
if (isPresent) {
ifPresent(_value as T);
}
}
/// Execution a function if the Optional value is absent.
void ifAbsent(void Function() ifAbsent) {
if (!isPresent) {
ifAbsent();
}
}
/// Gets the Optional value with a default.
///
/// The default is returned if the Optional is [absent()].
///
/// Throws [ArgumentError] if [defaultValue] is null.
T or(T defaultValue) {
return _value ?? defaultValue;
}
/// Gets the Optional value, or `null` if there is none.
T? get orNull => _value;
/// Transforms the Optional value.
///
/// If the Optional is [absent()], returns [absent()] without applying the transformer.
///
/// The transformer must not return `null`. If it does, an [ArgumentError] is thrown.
Optional<S> transform<S>(S Function(T value) transformer) {
return _value == null
? Optional<S>.absent()
: Optional<S>.of(transformer(_value as T));
}
/// Transforms the Optional value.
///
/// If the Optional is [absent()], returns [absent()] without applying the transformer.
///
/// Returns [absent()] if the transformer returns `null`.
Optional<S> transformNullable<S>(S? Function(T value) transformer) {
return _value == null
? Optional<S>.absent()
: Optional<S>.fromNullable(transformer(_value as T));
}
@override
Iterator<T> get iterator =>
isPresent ? <T>[_value as T].iterator : Iterable<T>.empty().iterator;
/// Delegates to the underlying [value] hashCode.
@override
int get hashCode => _value.hashCode;
/// Delegates to the underlying [value] operator==.
@override
bool operator ==(Object o) => o is Optional<T> && o._value == _value;
@override
String toString() {
return _value == null
? 'Optional { absent }'
: 'Optional { value: $_value }';
}
}
|
83c15fa2d55d2def9901d078e7c7fbe1
|
{
"intermediate": 0.40519875288009644,
"beginner": 0.4002436399459839,
"expert": 0.19455760717391968
}
|
9,561
|
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 = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
params = {
"symbol": symbol,
"interval": interval,
"startTime": int(dt.datetime.timestamp(dt.datetime.now() - dt.timedelta(minutes=lookback))),
"endTime": int(dt.datetime.timestamp(dt.datetime.now()))
}
try:
response = requests.get(url, params=params)
content = response.content
data = response.json()
print(f"Response content: {content}")
print(f"Response JSON: {data}")
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
if df.empty:
print('DataFrame is empty. Check API response.')
df.set_index('Open time', inplace=True)
return df
except Exception as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '1m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '1m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = 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)
while True:
df = get_klines('BTCUSDT', '1m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I still getting ERROR: Response content: b'[]'
Response JSON: [] ,please give me right code
|
0892ee5a32975cd1448edd0ced8ef4db
|
{
"intermediate": 0.45297425985336304,
"beginner": 0.4213167428970337,
"expert": 0.12570896744728088
}
|
9,562
|
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 = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
end_time = int(dt.datetime.timestamp(dt.datetime.now()))
start_time = int(dt.datetime.timestamp(dt.datetime.now() - dt.timedelta(minutes=lookback)))
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '15m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '15m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = 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)
while True:
df = get_klines('BTCUSDT', '15m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But terminal returns me :No data found for the given timeframe and symbol
What I need to do ?
|
f14fe5e79408ff49a591eee824c5dad0
|
{
"intermediate": 0.4116753041744232,
"beginner": 0.3850894272327423,
"expert": 0.2032352238893509
}
|
9,563
|
def transcribe_audio(path):
# use the audio file as the audio source
with sr.AudioFile(path) as source:
audio_listened = r.record(source)
# try converting it to text
text = r.recognize_google(audio_listened)
return text переменная r не объявлена, что здесь могло подразумеваться?
|
999dbe6951cbd692ec59af345470aafa
|
{
"intermediate": 0.3741142153739929,
"beginner": 0.31719768047332764,
"expert": 0.3086881637573242
}
|
9,564
|
now need to define new added edges position. I'm not sure how it should look. what if you add 3 small buttons after each "Vertex: <input", and if you press that button, then a new wireframe line appears from that corner that you can drag from its end and snap or auto-attach to any other vertices to construct a new model and update the overall 3d matrix arrays, which you can then use as a template through some textarea or something to apply and update the model?: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
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],
];
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],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
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];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
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 + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
cf9fd56111dd6802925dde5cbdf34983
|
{
"intermediate": 0.33571213483810425,
"beginner": 0.34339439868927,
"expert": 0.32089346647262573
}
|
9,565
|
now need to define new added edges position. I'm not sure how it should look. what if you add 3 small buttons after each "Vertex: <input", and if you press that button, then a new wireframe line appears from that corner that you can drag from its end and snap or auto-attach to any other vertices to construct a new model and update the overall 3d matrix arrays, which you can then use as a template through some textarea or something to apply and update the model?: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
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],
];
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],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
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];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
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 + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
0f922f300e56b0de67a6f68be01b4eb2
|
{
"intermediate": 0.33571213483810425,
"beginner": 0.34339439868927,
"expert": 0.32089346647262573
}
|
9,566
|
now need to define new added edges position. I'm not sure how it should look. what if you add 3 small buttons after each "Vertex: <input", and if you press that button, then a new wireframe line appears from that corner that you can drag from its end and snap or auto-attach to any other vertices to construct a new model and update the overall 3d matrix arrays, which you can then use as a template through some textarea or something to apply and update the model?: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
z-index:1;
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 5px;
height: 5px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
z-index:0;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
</div>
<div class="red-dot" id="red-dot"></div>
<script>
const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
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],
];
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],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
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];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 100 / 50;
const amplitude = maxDeviation / 10;
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 + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.2);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.2);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
bestIndex = -1;
bestDistance = Infinity;
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
} else {
vmcMenu.style.display = 'none';
redDot.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
</script>
</body>
</html>
|
5e121d913a8ff00a25b9c6a6322706ba
|
{
"intermediate": 0.33571213483810425,
"beginner": 0.34339439868927,
"expert": 0.32089346647262573
}
|
9,567
|
<svg id="eyeSvg" xmlns="http://www.w3.org/2000/svg" height="36px" viewBox="0 0 24 24" width="36px" fill="#000000"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M12 4C7 4 2.73 7.11 1 11.5 2.73 15.89 7 19 12 19s9.27-3.11 11-7.5C21.27 7.11 17 4 12 4zm0 12.5c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>
how would I be able to convert a svg to replace that?
|
188ca11cd2009531ba8cf4b206e959e6
|
{
"intermediate": 0.3109818398952484,
"beginner": 0.36882659792900085,
"expert": 0.32019153237342834
}
|
9,568
|
Create a simple user interface for a cyberpunk football game using java . This should be easy to navigate and understand.
|
61d6f5a2c57bbb4fabbc0998b1e09aff
|
{
"intermediate": 0.47438952326774597,
"beginner": 0.18894201517105103,
"expert": 0.336668461561203
}
|
9,569
|
“Disposed CameraController”
“StopImageStream() was called on a disposed CameraController”
Wie fixe ich das?
import 'dart:async';
import 'package:code_scan/code_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/patient_app_localizations.dart';
import 'package:patient_app/models/scan_result.dart';
import 'package:patient_app/theme/patient_app_colors.dart';
import 'package:patient_app/widgets/patient_app_back_button.dart';
typedef QrScanResultCallback = Future<bool> Function(ScanResult);
// see https://pub.dev/packages/code_scan/example
class QrScanner extends StatefulWidget {
const QrScanner(
{Key? key, required this.callback, required this.backButtonCallback})
: super(key: key);
final QrScanResultCallback callback;
final BackButtonCallback backButtonCallback;
@override
State<QrScanner> createState() => _QrScannerState();
}
class _QrScannerState extends State<QrScanner> with WidgetsBindingObserver {
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
late AppLocalizations _l10n;
// prevent over processing
bool processingInProgress = false;
@override
void didChangeDependencies() {
_l10n = AppLocalizations.of(context)!;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Container(
color: AppColors.opascaBlue,
child: _buildQrView(),
);
}
Widget _buildQrView() {
return CodeScanner(
key: qrKey,
formats: const [BarcodeFormat.qrCode],
scanInterval: const Duration(milliseconds: 500),
onScan: (code, _, listener) {
if (code != null) {
if (processingInProgress == false) {
processingInProgress = true;
widget.callback(ScanResult(code)).then((isValidCode) {
if (mounted && !isValidCode) {
processingInProgress = false;
}
});
}
}
},
onAccessDenied: (_, controller) {
_showPermissionNotGrantedDialog()
.then((_) => widget.backButtonCallback());
return false;
},
onError: (_, __) {
_showQrCodeReadErrorDialog();
},
overlay: Container(),
);
}
Future<dynamic> _showQrCodeReadErrorDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(_l10n.accountLinking_QrCodeScannerDialogTitle),
content: Text(_l10n.accountLinking_QrCodeScannerDialogDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
Future<dynamic> _showPermissionNotGrantedDialog() {
return showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(
_l10n.accountLinking_QrCodeScannerMissingCameraPermissionTitle),
content: Text(_l10n
.accountLinking_QrCodeScannerMissingCameraPermissionDescription),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(_l10n.accountLinking_QrCodeScannerDialogAction),
)
],
),
);
}
}
|
f2a3625aa152d7e203a54f4c18fced53
|
{
"intermediate": 0.32777103781700134,
"beginner": 0.3456094563007355,
"expert": 0.3266194462776184
}
|
9,570
|
Me gustaría que en este código, aparezca el temporizador en pantalla al mismo tiempo que las preguntas, y que cuando se termine el tiempo, el espacio donde está el texto de la pregunta aparezca ahora un texto que diga: Tiempo terminado, tu puntaje es: import json
import random
import os
import googletrans
from googletrans import Translator
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.clock import Clock
from kivy.metrics import dp
from kivy.properties import NumericProperty, StringProperty, ObjectProperty
# ... (mantén las funciones cargar_preguntas, mostrar_menu, mostrar_mensaje_porcentaje, jugar, jugar_de_nuevo, seleccionar_idioma, guardar_puntuacion y ver_mejores_puntuaciones) ...
def cargar_preguntas():
with open("preguntas_es.json", "r", encoding="utf-8") as f:
preguntas = json.load(f)
return preguntas
def guardar_puntuacion(puntuacion):
archivo_puntuaciones = "mejores_puntuaciones.txt"
if not os.path.exists(archivo_puntuaciones):
with open(archivo_puntuaciones, "w") as f:
f.write(f"{puntuacion}\n")
else:
with open(archivo_puntuaciones, "r") as f:
puntuaciones = [int(linea.strip()) for linea in f.readlines()]
puntuaciones.append(puntuacion)
puntuaciones.sort(reverse=True)
puntajes = puntuaciones[:5]
with open(archivo_puntuaciones, "w") as f:
for puntuacion in puntajes:
f.write(f"{puntuacion}\n")
def cargar_puntuaciones():
archivo_puntuaciones = "mejores_puntuaciones.txt"
if os.path.exists(archivo_puntuaciones):
with open(archivo_puntuaciones, "r") as f:
puntuaciones = [int(linea.strip()) for linea in f.readlines()]
else:
puntuaciones = []
return puntuaciones
def traducir(texto, idioma):
translator = Translator()
traduccion = translator.translate(texto, dest=idioma)
return traduccion.text
class LanguageScreen(Screen):
def seleccionar_idioma(self, idioma):
self.manager.idioma = idioma
self.manager.current = "menu"
class MainMenu(Screen):
def __init__(self, **kwargs):
super(MainMenu, self).__init__(**kwargs)
self.layout = BoxLayout(orientation='vertical')
self.add_widget(Label(text='Menú principal'))
self.play_button = Button(text='Jugar')
self.play_button.bind(on_press=self.start_game)
self.layout.add_widget(self.play_button)
self.high_scores_button = Button(text='Ver mejores puntuaciones')
self.high_scores_button.bind(on_press=self.show_high_scores)
self.layout.add_widget(self.high_scores_button)
self.exit_button = Button(text='Salir')
self.exit_button.bind(on_press=self.exit_app)
self.layout.add_widget(self.exit_button)
self.add_widget(self.layout)
def start_game(self, instance):
self.manager.current = 'game'
def show_high_scores(self, instance):
self.manager.current = 'high_scores'
def exit_app(self, instance):
App.get_running_app().stop()
class GameScreen(Screen):
timer_value = NumericProperty(10)
def __init__(self, **kwargs):
super(GameScreen, self).__init__(**kwargs)
self.layout = BoxLayout(orientation='vertical')
self.score_label = Label(text='Puntuación: 0')
self.layout.add_widget(self.score_label)
self.question_label = Label(text='')
self.layout.add_widget(self.question_label)
self.timer_label = Label(text='')
self.layout.add_widget(self.timer_label)
# Agregar los botones de respuesta
self.options_layout = BoxLayout(orientation='vertical')
for i in range(4):
button = Button(text='', size_hint_y=None, height=dp(50))
button.bind(on_release=lambda button: self.submit_answer(button.text))
self.options_layout.add_widget(button)
self.layout.add_widget(self.options_layout)
self.back_button = Button(text='Volver al menú principal')
self.back_button.bind(on_press=self.go_back)
self.layout.add_widget(self.back_button)
self.add_widget(self.layout)
def on_enter(self):
self.start_game()
def on_leave(self):
self.score_label.text = "Puntuación: 0"
self.puntaje = 0 # Reiniciar el puntaje
self.timer_value = 10
self.timer_label.text = ""
def start_game(self):
global preguntas
self.puntaje = 0
self.total_preguntas = len(preguntas)
self.preguntas_respondidas = 0
self.preguntas = preguntas.copy()
self.mostrar_pregunta()
self.initial_timer_value = self.timer_value
Clock.schedule_interval(self.update_timer, 1)
def mostrar_pregunta(self):
if self.preguntas:
self.pregunta_actual = random.choice(self.preguntas)
self.preguntas.remove(self.pregunta_actual)
self.question_label.text = self.pregunta_actual["pregunta"]
# Actualizar los botones de respuesta
opciones = self.pregunta_actual["opciones"]
random.shuffle(opciones)
for i, opcion in enumerate(opciones):
self.options_layout.children[i].text = opcion
self.enable_buttons()
else:
self.question_label.text = "¡Felicidades, lo lograste!"
self.disable_buttons()
self.reset_timer()
def submit_answer(self, respuesta):
self.preguntas_respondidas += 1
Clock.unschedule(self.update_timer)
if respuesta == self.pregunta_actual["respuesta_correcta"]:
self.puntaje += 1
self.score_label.text = f'Puntuación: {self.puntaje}'
else:
mensaje_porcentaje = self.mostrar_mensaje_porcentaje()
self.question_label.text = f"Respuesta incorrecta. La respuesta correcta es: {self.pregunta_actual['respuesta_correcta']}. Tu puntaje final es: {self.puntaje}. {mensaje_porcentaje}"
self.disable_buttons()
guardar_puntuacion(self.puntaje)
self.puntaje = 0 # Reiniciar el puntaje
return
Clock.schedule_interval(self.update_timer, 1)
self.mostrar_pregunta()
def update_timer(self, dt):
self.timer_value -= 1
if self.timer_value < 0:
self.time_out()
self.question_label.text = f"Tiempo restante: 0"
def reset_timer(self):
self.timer_value = 10
def time_out(self):
self.timer_label.text = 'Se acabó el tiempo'
Clock.unschedule(self.update_timer)
self.disable_buttons()
def disable_buttons(self):
for button in self.options_layout.children:
button.disabled = True
def enable_buttons(self):
for button in self.options_layout.children:
button.disabled = False
def go_back(self, instance):
self.manager.current = 'menu'
def mostrar_mensaje_porcentaje(self):
porcentaje_aciertos = (self.puntaje / self.preguntas_respondidas) * 100
if porcentaje_aciertos >= 75:
mensaje = "¡Excelente trabajo!"
elif porcentaje_aciertos >= 50:
mensaje = "¡Buen trabajo!"
elif porcentaje_aciertos >= 25:
mensaje = "Puedes hacerlo mejor."
else:
mensaje = "Sigue practicando."
return mensaje
def go_back(self, instance):
self.manager.current = 'main_menu'
class HighScoresScreen(Screen):
def __init__(self, **kwargs):
super(HighScoresScreen, self).__init__(**kwargs)
self.layout = BoxLayout(orientation='vertical')
self.high_scores_label = Label(text='')
self.layout.add_widget(self.high_scores_label)
self.back_button = Button(text='Volver al menú principal')
self.back_button.bind(on_press=self.go_back)
self.layout.add_widget(self.back_button)
self.add_widget(self.layout)
def on_enter(self):
self.show_high_scores()
def show_high_scores(self):
archivo_puntuaciones = "mejores_puntuaciones.txt"
if os.path.exists(archivo_puntuaciones):
with open(archivo_puntuaciones, "r") as f:
puntuaciones = [int(linea.strip()) for linea in f.readlines()]
puntuaciones = puntuaciones[:5]
self.high_scores_label.text = "Mejores puntuaciones:\n" + "\n".join(str(puntuacion) for puntuacion in puntuaciones)
else:
self.high_scores_label.text = "No hay puntuaciones guardadas."
def go_back(self, instance):
self.manager.current = 'main_menu'
class TriviaApp(App):
def build(self):
sm = ScreenManager()
sm.add_widget(MainMenu(name='main_menu'))
sm.add_widget(GameScreen(name='game'))
sm.add_widget(HighScoresScreen(name='high_scores'))
return sm
if __name__ == "__main__":
preguntas = cargar_preguntas()
TriviaApp().run()
|
05509f4030f2ced002ae7aed5adad5e2
|
{
"intermediate": 0.29380956292152405,
"beginner": 0.511001467704773,
"expert": 0.195188969373703
}
|
9,571
|
need that menu to disappear while out of the model bounds or range, because it glitching the performance. maybe you can do that mousemove function even better? output full fixed mousemove function code. also, there is some problem with the reddot not appearing when hovering on vertices. need to make that reddot to be the point where you point the cursor and from that exact point you can add a new edge option. I have already some style for that reddot point as well.: const canvas = document.createElement('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
const vmcMenu = document.getElementById('vmc-menu');
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],
];
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],
];
const scale = 0.025;
const zoom = 1;
const offsetX = 0.5;
const offsetY = 0.5;
let angleX = 0;
let angleY = 0;
let angleZ = 0;
let bestIndex = -1;
let bestDistance = Infinity;
let startNewEdgeIndex = -1;
let isMouseDown = false;
let prevMousePos = null;
// Red Dot
const redDot = document.getElementById('red-dot');
// Add Edge
document.getElementById('add-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
if (startNewEdgeIndex === -1) {
startNewEdgeIndex = bestIndex;
} else {
edges.push([startNewEdgeIndex, bestIndex]);
startNewEdgeIndex = -1;
}
});
// Remove Edge
document.getElementById('remove-edge').addEventListener('click', () => {
if (bestIndex === -1) return;
edges.forEach((edge, index) => {
if (edge.includes(bestIndex)) {
edges.splice(index, 1);
}
});
});
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];
}
function getDeviation(maxDeviation) {
const t = Date.now() / 1000;
const frequency = 10 / 1;
const amplitude = maxDeviation / 1;
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.008;
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 + offsetX + angleY + offsetY) * 55 + ', 100%, 30%, 0.8)';
ctx.beginPath();
for (let edge of edges) {
const [a, b] = edge;
const [x1, y1] = projectedVertices[a];
const [x2, y2] = projectedVertices[b];
const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1));
const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1);
// Calculate control point for curved edge
const cpDist = 0.005 * dist;
const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(0.5);
const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(0.5);
ctx.moveTo(x1, y1, x2, y2);
ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1);
}
ctx.stroke();
canvas.addEventListener('mousedown', (event) => {
isMouseDown = true;
prevMousePos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
prevMousePos = null;
});
canvas.addEventListener('mousemove', (event) => {
const mousePos = {
x: event.clientX - canvas.getBoundingClientRect().left,
y: event.clientY - canvas.getBoundingClientRect().top
};
projectedVertices.forEach((currVertex, index) => {
const distance = Math.hypot(
currVertex[0] - mousePos.x,
currVertex[1] - mousePos.y
);
if (distance < bestDistance) {
bestIndex = index;
bestDistance = distance;
}
});
if (bestDistance < 10 && bestIndex !== -1) {
vmcMenu.style.display = 'block';
vmcMenu.style.left = mousePos.x + 'px';
vmcMenu.style.top = mousePos.y + 'px';
document.getElementById('vmc-vertex-x').value = vertices[bestIndex][0];
document.getElementById('vmc-vertex-y').value = vertices[bestIndex][1];
document.getElementById('vmc-vertex-z').value = vertices[bestIndex][2];
document.getElementById('vmc-vertex-x').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-y').dataset.vertexIndex = bestIndex;
document.getElementById('vmc-vertex-z').dataset.vertexIndex = bestIndex;
if (bestIndex === -1) {
redDot.style.display = 'none';
} else {
redDot.style.display = 'block';
redDot.style.left = projectedVertices[bestIndex][0] - 3 + 'px';
redDot.style.top = projectedVertices[bestIndex][1] - 3 + 'px';
}
}
else {
vmcMenu.style.display = 'none';
}
if (isMouseDown && prevMousePos) {
const deltaX = event.clientX - prevMousePos.x;
const deltaY = event.clientY - prevMousePos.y;
angleY += deltaX * 0.01;
angleX += deltaY * 0.01;
prevMousePos = { x: event.clientX, y: event.clientY };
}
});
function updateVertexValue(event, indexToUpdate) {
const newValue = parseFloat(event.target.value);
const vertexIndex = parseInt(event.target.dataset.vertexIndex);
if (!isNaN(newValue) && vertexIndex >= 0) {
vertices[vertexIndex][indexToUpdate] = newValue;
}
}
document.getElementById('vmc-vertex-x').addEventListener('input', (event) => {
updateVertexValue(event, 0);
});
document.getElementById('vmc-vertex-y').addEventListener('input', (event) => {
updateVertexValue(event, 1);
});
document.getElementById('vmc-vertex-z').addEventListener('input', (event) => {
updateVertexValue(event, 2);
});
angleX += +getDeviation(0.0005);
angleY += +getDeviation(0.0005);
angleZ += +getDeviation(0.0005);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
window.addEventListener("resize", () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}); here's style: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Visual Matrix Constructor</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
.vmc-menu {
display: none;
position: absolute;
background-color: rgba(0,0,0,0.1);
border-radius: 5px;
padding: 10px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
.vmc-menu label {
display: block;
margin-bottom: 10px;
}
.red-dot {
position: absolute;
width: 32px;
height: 32px;
background-color: red;
border-radius: 50%;
pointer-events: none;
color:red;
}
</style>
</head>
<body>
<div class="vmc-menu" id="vmc-menu">
<label>Vertex X: <input type="number" id="vmc-vertex-x" step="0.1"></label>
<label>Vertex Y: <input type="number" id="vmc-vertex-y" step="0.1"></label>
<label>Vertex Z: <input type="number" id="vmc-vertex-z" step="0.1"></label>
<button id="add-edge">Add Edge</button>
<button id="remove-edge">Remove Edge</button>
<div class="red-dot" id="red-dot"></div>
</div>
</body>
</html>
|
4ecde01a8396613699f480396cb03d75
|
{
"intermediate": 0.46562841534614563,
"beginner": 0.3070106506347656,
"expert": 0.2273610234260559
}
|
9,572
|
how can i write makarov matrix algorithm in matlab?
|
7bd0e0354ea15186da8e5aa05e97f9e6
|
{
"intermediate": 0.10638376325368881,
"beginner": 0.05467831715941429,
"expert": 0.8389379382133484
}
|
9,573
|
c# wpf live charts clear display
|
d237d6fb5cfaff0d684e3ba5528f3bff
|
{
"intermediate": 0.3974880576133728,
"beginner": 0.2800578474998474,
"expert": 0.32245415449142456
}
|
9,574
|
deviceElement = device.split('|') # ╨рёяръют√трхь фрээ√х юЄ фхтрщё ш чряюыэ хь ъюэёюы№ (с√ы ЇюЁьрЄ Hostname|IP|MAC|Ports)
AttributeError: 'int' object has no attribute 'split'
|
675001f675a6f2c6805f0c020dc62e75
|
{
"intermediate": 0.34963545203208923,
"beginner": 0.3390956223011017,
"expert": 0.3112688958644867
}
|
9,575
|
Assume the following code:
modify the code in order to calculate the average queuing delay during the simulation. (as a parameter of Measure class)
import simpy
import random
import matplotlib.pyplot as plt
# Parameters
num_edge_nodes = 1
edge_buffer_size = 15
cloud_buffer_size = 20
# service times
cloud_server_time = 10
A_edge_service_time = 4
A_cloud_service_time = 2
B_edge_sevice_time = 2
B_cloud_service_partialprocess = 4
B_cloud_service_fullprocess = 5
propagation_delay = 1
arrival_rate = .8
# 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
measurements = Measure(0, 0, 0)
def packet_arrivals(env, micro_data_center, cloud_data_center, data, edge_buffer, cloud_buffer):
packet_type_options = ['A', 'B']
packet_id = 1
while True:
packet_type = random.choices(packet_type_options, weights=(1 - f, f))[0]
# 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) < edge_buffer:
if packet_type == "A":
micro_data_center.put((packet_id, packet_type, A_edge_service_time))
elif packet_type == "B":
micro_data_center.put((packet_id, packet_type, B_edge_sevice_time))
else:
if len(cloud_data_center.items) < cloud_buffer:
if packet_type == "A":
cloud_data_center.put(
(packet_id, packet_type, A_cloud_service_time + propagation_delay))
elif packet_type == "B":
cloud_data_center.put(
(packet_id, packet_type, B_cloud_service_fullprocess + propagation_delay))
else:
data.drop = 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, B_cloud_service_partialprocess + 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
f = 0.5 # Fraction of packets of type B
simtime = 10000
# Recording data
# Run the simulation
env = simpy.Environment()
micro_data_center = simpy.Store(env)
cloud_data_center = simpy.Store(env)
env.process(packet_arrivals(env, micro_data_center, cloud_data_center, measurements, edge_buffer_size, cloud_buffer_size))
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))
env.run(until=simtime)
print ( 100* measurements.drop/ ( measurements.N_arr_A+ measurements.N_arr_B))
|
a91e67cee8393470e665868a554c3c2f
|
{
"intermediate": 0.33187994360923767,
"beginner": 0.4394994378089905,
"expert": 0.22862061858177185
}
|
9,576
|
import { Router } from “express”;
import User from “…/models/User”;
import CryptoJS from “crypto-js”;
import dotenv from “dotenv”;
const authRouter = Router();
dotenv.config();
authRouter.post(“/register”, async (req, res) => {
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: CryptoJS.AES.encrypt(
req.body.password,
process.env.PASSWORD_SECRET || “incorrect password”
),
});
try {
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json(err);
}
});
authRouter.post(“/login”, async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
!user && res.status(401).json(“Wrong credentials”);
let password;
if (user && process.env.PASSWORD_SECRET) {
const hashedPassword = CryptoJS.AES.decrypt(
user.password,
process.env.PASSWORD_SECRET
);
password = hashedPassword.toString(CryptoJS.enc.Utf8);
}
password !== req.body.password && res.status(401).json(“Wrong credentials”);
res.status(200).json(user);
} catch (err) {
res.status(500).json(err);
}
});
export default authRouter;
Cannot set headers after they are sent to the client
|
7868a7113bc6f5ca88c7b1e62456d33c
|
{
"intermediate": 0.4918089509010315,
"beginner": 0.2880063056945801,
"expert": 0.22018477320671082
}
|
9,577
|
I have this c# code how can I make it to use the combobox which get the events to use it as the parameter of the method?
private void ComboBoxH1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ColorearCombobox(ComboBoxH1);
}
|
ed241b1044901a847d9f986dd186818d
|
{
"intermediate": 0.7754436731338501,
"beginner": 0.13820482790470123,
"expert": 0.08635152131319046
}
|
9,578
|
Give me a short script to touch files in a directory recusively
|
3683745fc5c8b174e94a918e6b8539ac
|
{
"intermediate": 0.4493996500968933,
"beginner": 0.1761922389268875,
"expert": 0.37440812587738037
}
|
9,579
|
in c# is there a way to do this without using new?
articulos = new ObservableCollection<Articulo>(articulos.OrderBy(a => a.Clase));
|
55cddec043fa23fa81f2b7e2d7d8bac1
|
{
"intermediate": 0.5736086368560791,
"beginner": 0.23188741505146027,
"expert": 0.19450397789478302
}
|
9,580
|
I have a kotlin app. What would be the best way to implement a picture gallery - it would read images from a database (which is already implemented and working), add new pictures from internal storage and delete them?
|
783fba3161c79e802416395eb520ef94
|
{
"intermediate": 0.7076569199562073,
"beginner": 0.06210677698254585,
"expert": 0.23023639619350433
}
|
9,581
|
password !== req.body.password && res.status(401).json("Wrong credentials");
|
0736ff4ce7456106e97dba1a5c6b6210
|
{
"intermediate": 0.40048912167549133,
"beginner": 0.2758738696575165,
"expert": 0.3236369788646698
}
|
9,582
|
Zuora Postman API Error Required MultipartFile parameter 'file' is not present
|
4ddfc3711026e30d4e3cc76e5095c70b
|
{
"intermediate": 0.6903195977210999,
"beginner": 0.13958220183849335,
"expert": 0.1700981706380844
}
|
9,583
|
Добавь слева от надписи товары по акции иконку назад , а справа от надписи товараы а=по акции добавь иконку корзина : <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="900dp"
android:orientation="vertical">
<TextView
android:id="@+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginTop="5dp"
android:text="Товары по акции"
android:textColor="@color/black"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/viewPager"
android:layout_gravity="center"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="100dp"/>
</LinearLayout>
</FrameLayout>
</ScrollView>
|
006496d9d24bdda7be11d891de702fa8
|
{
"intermediate": 0.35300296545028687,
"beginner": 0.42912229895591736,
"expert": 0.21787475049495697
}
|
9,584
|
authRouter.post("/login", async (req, res) => {
try {
const user = await User.findOne({ username: req.body.username });
!user && res.status(401).json("Wrong credentials");
if (user && process.env.PASSWORD_SECRET) {
const hashedPassword = CryptoJS.AES.decrypt(
user.password,
process.env.PASSWORD_SECRET
);
const password = hashedPassword.toString(CryptoJS.enc.Utf8);
password !== req.body.password &&
res.status(401).json("Wrong credentials");
res.status(200).json(user);
}
} catch (err) {
res.status(500).json(err);
}
});
fix code
|
9c0e6e173961ef6f2c023b78b9d7a49d
|
{
"intermediate": 0.3934479355812073,
"beginner": 0.3377728760242462,
"expert": 0.2687792181968689
}
|
9,585
|
I used this code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
binance_futures = ccxt.binance({ 'option': { 'defaultMarket': 'futures' } })
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '15m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '15m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = client.futures_account_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
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)
while True:
df = get_klines('BTCUSDT', '15m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR in futures order execution : The signal time is: 2023-06-01 20:40:25 :sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 226, in <module>
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 103, in order_execution
account_balance = client.futures_account_balance()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'futures_account_balance'
|
d5053c78f144d58973210c5d9832d40a
|
{
"intermediate": 0.4590875506401062,
"beginner": 0.4009094536304474,
"expert": 0.1400030255317688
}
|
9,586
|
i have a kotlin app, in which i want to be able to add pictures from internal storage. i already have a database and a class prepared, and i want to be able to read a picture’s location in the internal storage, and store it in a string of the object. how do i do that?
|
3b738fd0d072eb3b42e40fef65886f49
|
{
"intermediate": 0.6683378219604492,
"beginner": 0.16861651837825775,
"expert": 0.16304564476013184
}
|
9,587
|
Write a python script following my instructions.
1) The program takes a path as an argument. It will check every subdirectory of that path (not recursive) for a file called `info.yaml`.
2) The script will show a report of every directory, showing whether there is a yaml file present or not, or if the `info.yaml` file is invalid. It will then ask whether to proceed or not.
The valid `info.yaml` file looks like this:
|
3aa60531ffe4b81c1db4056cdb3cd7d0
|
{
"intermediate": 0.503535807132721,
"beginner": 0.1729613095521927,
"expert": 0.3235028386116028
}
|
9,588
|
karaf check host port bundles
|
e85cb526288a5a50d2106b398fc3898a
|
{
"intermediate": 0.4674607217311859,
"beginner": 0.25533297657966614,
"expert": 0.27720633149147034
}
|
9,589
|
teach if else and elif statements to a highschooler with no coding experience using analogies and code examples
|
046242177b3d807abf75843ec1478b72
|
{
"intermediate": 0.2792695462703705,
"beginner": 0.3753582835197449,
"expert": 0.34537217020988464
}
|
9,590
|
i am creating a layout for a context menu in kotlin, and it says it cannot resolve class item
|
0f7781ac2cadb568873b0d57ed09d4d9
|
{
"intermediate": 0.5295552015304565,
"beginner": 0.3281240165233612,
"expert": 0.14232081174850464
}
|
9,591
|
How to use a class and have two different values stored in it java
|
2ba1d3f4d8eabc41f993bd97a8799b81
|
{
"intermediate": 0.39491236209869385,
"beginner": 0.45222461223602295,
"expert": 0.1528630405664444
}
|
9,592
|
i have a kotlin app. i want to be able to add and delete images, and see them. i have a database prepared, its named ImageDB. I also have an Images class, which holds information about an image. i have addImage and deleteImage methods. these already exist and work. In my activity, i have a button which adds an image from the gallery. i also have a recyclerview in which i want to show my images. when i hold an image, i want to show a context menu which allows me to delete it. how can i go around implementing that?
|
a6dfe19e0670202f77863cbe1686887c
|
{
"intermediate": 0.5709146857261658,
"beginner": 0.2544954717159271,
"expert": 0.1745898723602295
}
|
9,593
|
How to use gpu in a docker container
|
35d9cc155c0cf83bbda1ea41245bffd9
|
{
"intermediate": 0.4777218699455261,
"beginner": 0.19156786799430847,
"expert": 0.3307103216648102
}
|
9,594
|
How to use layers in docker
|
51b9ddbad7bbb1e08f741b9a5f63685a
|
{
"intermediate": 0.5729551911354065,
"beginner": 0.08169624954462051,
"expert": 0.345348596572876
}
|
9,595
|
authRouter.post("/login", async (req, res) => {
try {
const user = await User.findOne({
username: req.body.username,
});
if (!user) {
return res
.status(401)
.json({ message: "Incorrect username or password" });
}
let hashedPassword = CryptoJS.AES.decrypt(
user.password,
process.env.PASSWORD_SECRET || ""
);
let userPassword = hashedPassword.toString(CryptoJS.enc.Utf8);
if (userPassword !== req.body.password) {
return res
.status(401)
.json({ message: "Incorrect username or password" });
}
if (user && process.env.JWT_SECRET) {
const accessToken = jwt.sign(
{ id: user.id, isAdmin: user.isAdmin },
process.env.JWT_SECRET,
{ expiresIn: "3d" }
);
}
const { password, ...others } = user.toObject();
res.status(200).json({ others, accessToken });
} catch (err) {
console.error(err);
res.status(500).json({
message: "There was a problem logging in. Please try again later.",
});
}
});
export default authRouter;
No value exists in scope for the shorthand property 'accessToken'. Either declare one or provide an initializer.
|
2d4e3e445b71349395617241a73be3ec
|
{
"intermediate": 0.35575413703918457,
"beginner": 0.34122467041015625,
"expert": 0.3030211329460144
}
|
9,596
|
how to use (private move[] moves;) in java to store the same values multiple times for multiple other objects
|
04bc398fa1e0f7499cdbd1cf32fd6ff9
|
{
"intermediate": 0.5466845631599426,
"beginner": 0.17003273963928223,
"expert": 0.28328272700309753
}
|
9,597
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
binance_futures = ccxt.binance({ 'option': { 'defaultMarket': 'futures' } })
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '15m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '15m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
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)
while True:
df = get_klines('BTCUSDT', '15m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR in order execution : 06/01/2023 20:59:26
The signal time is: 2023-06-01 21:00:30 :sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 226, in <module>
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 103, in order_execution
account_balance = binance_futures.fetch_balance()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 2393, in fetch_balance
response = getattr(self, method)(self.extend(request, requestParams))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\types.py", line 25, in unbound_method
return _self.request(self.path, self.api, self.method, params, config=self.config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7274, in request
response = self.fetch2(path, api, method, params, headers, body, config)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 2861, in fetch2
request = self.sign(path, api, method, params, headers, body)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\binance.py", line 7162, in sign
self.check_required_credentials()
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\ccxt\base\exchange.py", line 3016, in check_required_credentials
raise AuthenticationError(self.id + ' requires "' + key + '" credential')
ccxt.base.errors.AuthenticationError: binance requires "apiKey" credential
What I need to do ?
|
70c381d1946b871ff5ae964371977e56
|
{
"intermediate": 0.45019787549972534,
"beginner": 0.4073549807071686,
"expert": 0.1424470990896225
}
|
9,598
|
i have a kotlin app. in my activity, i want to be able to add pictures from my phone gallery to a database. i want to store them as locations on the internal storage. the databases name is ImageDB, and it has an addImage method. it all works fine. i also have an Images class, which stores data about the image, if it has any use. i want to be able to open the gallery on a button press and add an images location to the database. how can i do that?
|
aa1ee927a0ac3c7a0d6a8943203c5413
|
{
"intermediate": 0.6732490062713623,
"beginner": 0.19738012552261353,
"expert": 0.12937094271183014
}
|
9,599
|
debug it:
import simpy
import random
import matplotlib.pyplot as plt
import numpy as np
# Parameters
num_edge_nodes = 1
edge_buffer_size = 10
cloud_buffer_size = 15
# service times
cloud_server_time = 10
A_edge_service_time = 4
A_cloud_service_time = 2
B_edge_sevice_time = 2
B_cloud_service_partialprocess = 4
B_cloud_service_fullprocess = 5
propagation_delay = 1
arrival_rate = 0.8
# Measurements
class Measure:
def init(self, N_arr_a, N_arr_b, drop, total_queuing_delay):
self.N_arr_A = N_arr_a
self.N_arr_B = N_arr_b
self.drop = drop
self.total_queuing_delay = total_queuing_delay
measurements = Measure(0, 0, 0, 0)
def packet_arrivals(env, micro_data_center, cloud_data_center, data, edge_buffer, cloud_buffer, f_value):
packet_type_options = [‘A’, ‘B’]
packet_id = 1
while True:
packet_type = random.choices(packet_type_options, weights=(1 - f_value, f_value))[0]
# 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
arrival_time = env.now # Adding current time stamp for calculating delay
if len(micro_data_center.items) < edge_buffer:
if packet_type == ‘A’:
micro_data_center.put((packet_id, packet_type, A_edge_service_time, arrival_time))
elif packet_type == ‘B’:
micro_data_center.put((packet_id, packet_type, B_edge_sevice_time, arrival_time))
else:
if len(cloud_data_center.items) < cloud_buffer:
if packet_type == “A”:
cloud_data_center.put((packet_id, packet_type, A_cloud_service_time + propagation_delay))
elif packet_type == “B”:
cloud_data_center.put((packet_id, packet_type, B_cloud_service_fullprocess + propagation_delay))
else:
data.drop = data.drop + 1
yield env.timeout(random.expovariate(arrival_rate))
packet_id += 1
def edge_node(env, micro_data_center, cloud_data_center, node_id, data):
while True:
packet_id, packet_type, packet_processing_time, arrival_time = yield micro_data_center.get()
queuing_delay = env.now - arrival_time # Calculating delay
data.total_queuing_delay += queuing_delay
print(f"Edge Node {node_id} processed packet {packet_id} of type {packet_type} at time {env.now}“)
yield env.timeout(packet_processing_time)
if packet_type == ‘B’:
yield cloud_data_center.put((packet_id, packet_type, B_cloud_service_partialprocess + propagation_delay))
def cloud_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
#f = 0.5 # Fraction of packets of type B
simtime = 100000
# Recording data
average_queuing_delays = []
f_list = np.linspace(0.001, 1, 20)
# Run the simulation
for f in f_list:
env = simpy.Environment()
micro_data_center = simpy.Store(env)
cloud_data_center = simpy.Store(env)
env.process(
packet_arrivals(env, micro_data_center, cloud_data_center, measurements, edge_buffer_size, cloud_buffer_size,f))
for node_id in range(num_edge_nodes):
env.process(edge_node(env, micro_data_center, cloud_data_center, node_id + 1, measurements))
env.process(cloud_server(env, cloud_data_center))
env.run(until=simtime)
average_queuing_delays.append(measurements.total_queuing_delay / (measurements.N_arr_A + measurements.N_arr_B))
plt.plot(f_list, average_queuing_delays)
#plt.axvline(x=2000, color=‘red’, linestyle=‘–’)
#plt.text(2000, max(losses), ‘Transition Period’, color=‘red’, va=‘bottom’, ha=‘center’)
plt.xlabel(‘Different f’)
plt.ylabel('Average queueing delay (time unit) ')
plt.title(‘Average queueing delay over Different f’)
plt.show()
|
64b0638a9dc47e537975277d52881185
|
{
"intermediate": 0.34310340881347656,
"beginner": 0.42063507437705994,
"expert": 0.2362615019083023
}
|
9,600
|
I used your code: import time
from binance.client import Client
from binance.enums import *
from binance.exceptions import BinanceAPIException
import pandas as pd
import requests
import json
import numpy as np
import pytz
import datetime as dt
import ccxt
binance_futures = ccxt.binance({ 'option': { 'defaultMarket': 'futures' } })
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
print(date)
url = "https://api.binance.com/api/v1/time"
t = time.time()*1000
r = requests.get(url)
result = json.loads(r.content)
# API keys and other configuration
API_KEY = ''
API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50
TAKE_PROFIT_PERCENTAGE = 100
MAX_TRADE_QUANTITY_PERCENTAGE = 100
POSITION_SIDE_SHORT = 'SELL'
POSITION_SIDE_LONG = 'BUY'
symbol = 'BTCUSDT'
quantity = 1
order_type = 'MARKET'
leverage = 100
max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def get_klines(symbol, interval, lookback):
url = "https://fapi.binance.com/fapi/v1/klines"
start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback))
end_time = dt.datetime.now()
query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
try:
response = requests.get(url + query_params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlc = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S')
ohlc.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlc)
df.set_index('Open time', inplace=True)
return df
except requests.exceptions.RequestException as e:
print(f'Error in get_klines: {e}')
return None
df = get_klines('BTCUSDT', '15m', 44640)
def signal_generator(df):
open = df.Open.iloc[-1]
close = df.Close.iloc[-1]
previous_open = df.Open.iloc[-2]
previous_close = df.Close.iloc[-2]
# Bearish pattern
if (open>close and
previous_open<previous_close and
close<previous_open and
open>=previous_close):
return 'sell'
# Bullish pattern
elif (open<close and
previous_open>previous_close and
close>previous_open and
open<=previous_close):
return 'buy'
# No clear pattern
else:
return ""
df = get_klines('BTCUSDT', '15m', 44640)
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage):
max_trade_quantity = None
account_balance = binance_futures.fetch_balance()
usdt_balance = 0
for b in account_balance['assets']:
if b['asset'] == 'USDT':
usdt_balance = float(b['balance'])
max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite
long_position = None
short_position = None
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)
while True:
df = get_klines('BTCUSDT', '15m', 44640)
if df is not None:
signal = signal_generator(df)
if signal:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}")
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
time.sleep(1)
But I getting ERROR in excution :The signal time is: 2023-06-01 21:00:30 :sell
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 226, in <module>
order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage)
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 103, in order_execution
account_balance = binance_futures.fetch_balance()
What I need to do ?
|
b25b2c4427810731235b3ee6374bca70
|
{
"intermediate": 0.45019787549972534,
"beginner": 0.4073549807071686,
"expert": 0.1424470990896225
}
|
9,601
|
who created you
|
976a5fdfa47d37cc402e25addb34746f
|
{
"intermediate": 0.38410279154777527,
"beginner": 0.3257874548435211,
"expert": 0.2901097536087036
}
|
9,602
|
Version "‘3.9’" in "./docker-compose.yml" is invalid.
|
a2945e00a14851b898c262f2aa78423a
|
{
"intermediate": 0.3858725130558014,
"beginner": 0.26124316453933716,
"expert": 0.35288429260253906
}
|
9,603
|
Here is a class written in Java:
package pieces;
import model.Action;
import model.Const;
import model.Piece;
public class Aramis extends Piece {
public Aramis(int owner) {
super.setOwner(owner);
super.setPieceType(ARAMIS);
super.loadSide1(actionMatrix1);
super.loadSide2(actionMatrix2);
}
int[][] actionMatrix1 =
{
{0,0,0,0,0},
{Action.JUMP,Action.MOVE,Action.MOVE,Action.MOVE,Action.JUMP},
{0,0,Action.REFERENCEPOINT,0,0},
{0,Action.MOVE,0,Action.MOVE,0},
{Action.MOVE,0,0,0,Action.MOVE}
};
int[][] actionMatrix2 =
{
{0,0,Action.JUMP,0,0},
{0,Action.STRIKE,Action.STRIKE,Action.STRIKE,0},
{0,0,Action.REFERENCEPOINT,0,0},
{0,0,Action.MOVE,0,0},
{0,0,Action.JUMP,0,0}
};
}
Please rewrite it in C#. Use the K&R curly braces standard.
|
d47f9c62eac751bb2918a6fc3cf37c4e
|
{
"intermediate": 0.3259449005126953,
"beginner": 0.42077070474624634,
"expert": 0.25328439474105835
}
|
9,604
|
if (user && process.env.JWT_SECRET) {
const accessToken = jwt.sign(
{ id: user.id, isAdmin: user.isAdmin },
process.env.JWT_SECRET,
{ expiresIn: "3d" }
);
}
const { password, ...others } = user.toObject();
res.status(200).json({ others, accessToken });
fix it
|
0acc2f93967f4074169c5cf3cb4a6358
|
{
"intermediate": 0.36488285660743713,
"beginner": 0.3888382911682129,
"expert": 0.24627885222434998
}
|
9,605
|
Write a java program that works as a small online shop. The program should use the concept of one-dimensional arrays to implement
this small project.
Take into consideration the following requirements:
1- The shop has 10 products.
2- Name the shop after your name and display your Academic ID as the first thing to be displayed when you run the program (For
example, Ali’s online shop 443811034).
3- Each product has a name, quantity, and price. (Each student should come up with different products names).
4- The program should initialize the shop with name of products, quantities, and prices (Hard coded).
5- The user can display the products in the shop, their quantities, and their prices.
6- The user has a cart.
7- The user can add products to cart as long as it is available in the shop.
8- The user can remove products from the cart.
9- The program should update the quantity in the shop and in the cart after adding a product to the cart or removing a product
from the cart.
10- The user can display the cart items and the total price.
11- If the quantity of a product in the shop is equal to zero, it should be displayed as “sold out”.
Grading Policy:
• displayShop() : source code & output screen shot → 1 mark
• addToCart() : source code & output screen shot → 1 mark
• removeFromCart() : source code & output screen shot → 1 mark
• displayCart() : source code & output screen shot → 1 mark
• Following format and rules of submission → 1 mark
|
1f08784be8291480cf30433bf6756f79
|
{
"intermediate": 0.43971508741378784,
"beginner": 0.24881774187088013,
"expert": 0.3114672303199768
}
|
9,606
|
Given the following description can please Define all necessary constraints to ensure correctness of the database. These include
integrity constraints, keys, referential integrity, domain integrity, and user-defined constraints and appropriate indexes for the tables and justify your choice based on their usefulness
for the queries they are used in • School operating the library. For each school, the following details should be registered: School name,
Address, City, Phone number, Email, Full name of the School Director, Full name of the responsible
School Library Operator. Each school unit (through the School Library Operator) is responsible for
registering the school’s library available books in the system.
• Books with their respective data (title, publisher, ISBN1
, authors, number of pages, summary, available
copies/ inventory, image, thematic category, language, keywords). Each book has one or more
authors and belongs to one or more categories.
• Application Users: For each user, the system must verify their identity when accessing the application
(via username/password) and each user can change his own password.
o Network School Library Administrator (Administrator): Registers Schools and
approves/appoints School Library Operators. They can create a backup copy of the entire
database and restore the system from it.
o School Library Operator. Operators are responsible for the operation of the School Library at
the school unit level. Operators have the ability to process all the information of the books
included in the system and to add new ones. They also supervise reservations and loans,
either collectively or by searching by user. (Delayed returns are displayed separately). They
can record the return of a borrowed title. They can record the loan of a copy when there is a
reservation for that particular title, provided that the user's loan limits are met and that no
returns are delayed. They also record loans without reservations, by searching for the user
and title, if the user meets the loan criteria mentioned above and if there are available copies.
o All school students, as well as the professors, can register and use the system. Approval from
Operator is required for registration. After approving each user, the Operator prints out the
borrower's card and delivers it to the user. Additionally, the Operator is authorized to delete
or disable user accounts in accordance with the library's policy. Educators have the ability to
modify their personal information, while students are only able to view it. • Book borrowing: Each user of the system, at the level of the school unit, can view available books,
evaluate them and request to borrow a copy. Each student user can borrow up to two books per week,
while professors can borrow one per week. Borrowing/returning of books is handled by the Operator.
In case a copy of the book is not available, the user's request (reservation) is put on hold and is served
upon the return of a copy.
• Reservations: Regarding reservations, the borrowing limits apply, e.g., two reservations per week for
students. A reservation cannot be made if a book has not been returned on time or if the same user
has already borrowed the title. Users have the option to cancel any current reservations. Additionally,
reservations have a time frame of one week and are automatically canceled once it expires.
• Reviews: Users can share their thoughts about a book in a written review and provide a rating using
the Likert2
scale. Reviews written by students will be published upon approval by the Operator.
In addition to inputting the aforementioned information, all users of the application must have the ability
to manage information, including a search mechanism and options for updating or deleting it (CRUD).
|
8855eae15ab21d1cbba2bd87afcb654e
|
{
"intermediate": 0.5139751434326172,
"beginner": 0.24458235502243042,
"expert": 0.24144253134727478
}
|
9,607
|
write a python script that interacts with an free chatbot api
|
f2f8f13cbaef251bf61f84f604b85df0
|
{
"intermediate": 0.5518206357955933,
"beginner": 0.15957753360271454,
"expert": 0.2886018455028534
}
|
9,608
|
how to make a pdf file using pdf printer with python 3 script?
|
6f1557e2bb23ab1618844d065c73a55e
|
{
"intermediate": 0.49392181634902954,
"beginner": 0.21809232234954834,
"expert": 0.2879858613014221
}
|
9,609
|
write a python program that interacts with a free chatbot api
|
999ece8d7dd00b171728b49ab6153587
|
{
"intermediate": 0.5546014308929443,
"beginner": 0.14661532640457153,
"expert": 0.29878315329551697
}
|
9,610
|
write an algorithm code for registration form
|
3764ed813bf5b2533d96a392128d6e9c
|
{
"intermediate": 0.1241096779704094,
"beginner": 0.13728275895118713,
"expert": 0.7386075258255005
}
|
9,611
|
give me few examples to convert pdf to jpeg with imagemagick
|
73d5bea6dd94d4a8b34323596bfd5b36
|
{
"intermediate": 0.4552229642868042,
"beginner": 0.14345280826091766,
"expert": 0.40132421255111694
}
|
9,612
|
I have a multi connectors microservice with rest, soap, grpc, graphql and I want to register it in the eureka discover server to be accessed from the cloud gateway of course I already added the dependency Eureka client and I added also the config spring.cloud.discovery.enabled=true in application.propreties but it still has not appeared in the Eureka interface (http://localhost:8761/)
|
46cdb2b23a5d9212915abac1b57479bb
|
{
"intermediate": 0.5808395743370056,
"beginner": 0.1773587018251419,
"expert": 0.24180181324481964
}
|
9,613
|
Write a C# layout and position class.
- The class should have an Update(OriginPosition, OriginSize, Padding, GrowthDirection, ElementSize, ElementCount) method which is called each frame, the update method checks if the layout is "dirty" or the ElementCount changed (needs a calculation refresh), this is set with a SetDirty(isDirty) method. The ElementCount is just a request, the class should never generate positions outside the OriginPosition + OriginSize.
- The class should have an iterator method, which returns an iterator which returns the position of the next element.
- The class needs to support a GrowthDirections enum with the following values: GrowthDirections.RightDown, GrowthDirections.RightUp, GrowthDirections.LeftDown, GrowthDirections.LeftUp, GrowthDirections.VerticalCentered, GrowthDirections.HorizontalCentered
- The GrowthDirections.*Centered is special, it uses the ElementCount to calculate the positions. GrowthDirections.VerticalCentered will grow upwards first, then create a second column, the GrowthDirections.HorizontalCentered will grow outwards first, then create a second row if no space is left. Example if we have three elements, the second elements center, will be in the center of OriginSize
- The class needs to support a Padding float, which indicates the space between each element, the padding should not applied to any sides and only between elements (both vertical and horizontal). The Positions and Size should have the type Vector2
- All calculations should be done in the Update method for all possible positions and should not be refreshed if the class is not marked as dirty or calculated during the iterator method.
- Example, if the OriginSize would be 128,128and the Element Size 56,56 and the padding 16, positions for 2 rows and 2 columns get generated, if the OriginPosition was 1000,1000 the positions generated would be 1000,1000 1072,1000 1000,1072 1072,1072 if the GrowthDirection was GrowthDirections.RightDown.
- The class should avoid duplicate code at all cost.
|
ca86dc14faaa27ae98700490a38a13b3
|
{
"intermediate": 0.4636070728302002,
"beginner": 0.22322112321853638,
"expert": 0.31317177414894104
}
|
9,614
|
Write a C# layout and position class.
- The class should have an Update(OriginPosition, OriginSize, Padding, GrowthDirection, ElementSize, ElementCount) method which is called each frame, the update method checks if the layout is "dirty" or the ElementCount changed (needs a calculation refresh), this is set with a SetDirty(isDirty) method. The ElementCount is just a request, the class should never generate positions outside the OriginPosition + OriginSize.
- The class should have an iterator method, which returns an iterator which returns the position of the next element.
- The class needs to support a GrowthDirections enum with the following values: GrowthDirections.RightDown, GrowthDirections.RightUp, GrowthDirections.LeftDown, GrowthDirections.LeftUp, GrowthDirections.VerticalCentered, GrowthDirections.HorizontalCentered
- The GrowthDirections.*Centered is special, it uses the ElementCount to calculate the positions. GrowthDirections.VerticalCentered will grow upwards first, then create a second column, the GrowthDirections.HorizontalCentered will grow outwards first, then create a second row if no space is left. Example if we have three elements, the second elements center, will be in the center of OriginSize
- The class needs to support a Padding float, which indicates the space between each element, the padding should not applied to any sides and only between elements (both vertical and horizontal). The Positions and Size should have the type Vector2
- All calculations should be done in the Update method for all possible positions and should not be refreshed if the class is not marked as dirty or calculated during the iterator method.
- Example, if the OriginSize would be 128,128and the Element Size 56,56 and the padding 16, positions for 2 rows and 2 columns get generated, if the OriginPosition was 1000,1000 the positions generated would be 1000,1000 1072,1000 1000,1072 1072,1072 if the GrowthDirection was GrowthDirections.RightDown.
- The class should avoid duplicate code at all cost.
|
1172e4b07a6dfd6134f36100a6d5322a
|
{
"intermediate": 0.4636070728302002,
"beginner": 0.22322112321853638,
"expert": 0.31317177414894104
}
|
9,615
|
I want you to act as a data scientist and code for me. I will give you some example of my dataset. Please build a machine learning model the prediction.
|
e84fa8a74d95d658282280cacdc6d8f0
|
{
"intermediate": 0.20642215013504028,
"beginner": 0.13400305807590485,
"expert": 0.6595748662948608
}
|
9,616
|
Create me a simple Unity game in 2D with a top view. The circle character should WASD in all directions, and food circles will spawn around him. The most important condition is to add ML Agents and then explain to me how to set everything up. If anything, I have Unity and ML Agents installed and imported. I only need the code and instructions on how to make the training of the neural network start, as well as how to switch to keyboard control. The code must be complete and working.
|
59b5b50a29b77db2d67311c1280ba311
|
{
"intermediate": 0.2356054186820984,
"beginner": 0.17129892110824585,
"expert": 0.5930956602096558
}
|
9,617
|
Create me a simple Unity game in 2D with a top view. The circle character should WASD in all directions, and food circles will spawn around him. The most important condition is to add ML Agents and then explain to me how to set everything up. If anything, I have Unity and ML Agents installed and imported. I only need the code and instructions on how to make the training of the neural network start, as well as how to switch to keyboard control. The code must be complete and working.
|
997d3209624524688312ae9731522262
|
{
"intermediate": 0.2356054186820984,
"beginner": 0.17129892110824585,
"expert": 0.5930956602096558
}
|
9,618
|
Hi, Chatty
|
b1099524e076bbc4d369023b3e2cae06
|
{
"intermediate": 0.3554985821247101,
"beginner": 0.30953460931777954,
"expert": 0.33496683835983276
}
|
9,619
|
Create me a simple Unity game in 2D with a top view. The circle character should WASD in all directions, and food circles will spawn around him. The most important condition is to add ML Agents and then explain to me how to set everything up. If anything, I have Unity and ML Agents installed and imported. I only need the code and instructions on how to make the training of the neural network start, as well as how to switch to keyboard control. The code must be complete and working.
|
c7fb25176294fbc348cc1619f190b6be
|
{
"intermediate": 0.2356054186820984,
"beginner": 0.17129892110824585,
"expert": 0.5930956602096558
}
|
9,620
|
Create me a simple Unity game in 2D with a top view. The circle character should WASD in all directions, and food circles will spawn around him. The most important condition is to add ML Agents and then explain to me how to set everything up. If anything, I have Unity and ML Agents installed and imported. I only need the code and instructions on how to make the training of the neural network start, as well as how to switch to keyboard control. The code must be complete and working.
|
7e1ae62a7e12b1da2a0bbc77d4d63d86
|
{
"intermediate": 0.2356054186820984,
"beginner": 0.17129892110824585,
"expert": 0.5930956602096558
}
|
9,621
|
microsoft scheduler run visual studio solution every day
|
94d21dd5f07dfc8e25cc3a6fc5c78dff
|
{
"intermediate": 0.3934648334980011,
"beginner": 0.23077096045017242,
"expert": 0.37576422095298767
}
|
9,622
|
import jwt from "jsonwebtoken";
const verifyToken = (req, res, next) => {
const authHeader = req.headers.token;
if (authHeader) {
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) res.status(403).json("Token is invalid");
req.user = user;
next();
});
} else {
return res.status(401).json("You are not authorized");
}
};
Cannot find name 'token'.
No overload matches this call.
The last overload gave the following error.
Argument of type 'string | undefined' is not assignable to parameter of type 'Secret | GetPublicKeyOrSecret'.
Type 'undefined' is not assignable to type 'Secret | GetPublicKeyOrSecret'.
|
cc4da89ba0242125202e95239d98b577
|
{
"intermediate": 0.3995126485824585,
"beginner": 0.3619089424610138,
"expert": 0.23857834935188293
}
|
9,623
|
import jwt from "jsonwebtoken";
const verifyToken = (req, res, next) => {
const authHeader = req.headers.token;
if (authHeader && process.env.JWT_SECRET !== undefined) {
jwt.verify(authHeader, process.env.JWT_SECRET, (err, user) => {
if (err) res.status(403).json("Token is invalid");
req.user = user;
next();
});
} else {
return res.status(401).json("You are not authorized");
}
};
export default verifyToken;
params are type any correct for typscript
|
90c3ea7d4403f6951ed8b855a06a58c7
|
{
"intermediate": 0.29443079233169556,
"beginner": 0.43282729387283325,
"expert": 0.2727418839931488
}
|
9,624
|
import { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
const verifyToken = (req: Request, res: Response, next: NextFunction): void => {
const authHeader: string | undefined = req.headers.token as
| string
| undefined;
if (authHeader && process.env.JWT_SECRET !== undefined) {
jwt.verify(authHeader, process.env.JWT_SECRET, (err: any, user: any) => {
if (err) res.status(403).json("Token is invalid");
req.user = user;
next();
});
} else {
res.status(401).json("You are not authorized");
}
};
export default verifyToken;
Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)
|
39bb0645ddf8a3fdff104527e37a2715
|
{
"intermediate": 0.3503504991531372,
"beginner": 0.3961409032344818,
"expert": 0.25350862741470337
}
|
9,625
|
I need an AHK code that loops left-click and releases every 150ms.
|
f6d9220c1ad89d1d4fe35113c8baad86
|
{
"intermediate": 0.263528048992157,
"beginner": 0.4551050066947937,
"expert": 0.2813669443130493
}
|
9,626
|
I need an AHK code that loops left-click and releases every 150ms.
|
76d24356a869c82b40ad9381853a246d
|
{
"intermediate": 0.263528048992157,
"beginner": 0.4551050066947937,
"expert": 0.2813669443130493
}
|
9,627
|
C# HttpClient use the same HttpClient and change AllowAutoRedirect per request
|
8f94a1fb8ac101e6c153e9ec18f2f30a
|
{
"intermediate": 0.4963623881340027,
"beginner": 0.19198021292686462,
"expert": 0.3116573691368103
}
|
9,628
|
Get the code below and convert it to a telegram bot based on “python-telegram-bot 3.17”, but change its funtion to like these explanation:
- It should review and analyze the files when someone forward it to the bot according the sample bashscript below.
- Only Device Overview, Config Overview and mining Overview are needed as first responses.
- If the user send /error it should shows last errors.
- if the user send /warn it should shows last warns.
#!/bin/sh
################################
# Project name: BOS+ Log Reader macOS version
# Description: Braiins OS+ Support Archive Parser/Reader
# Share your ideas to <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>
################################
version=1.2.0
######## Defining colors ########
RED='\033[0;31m'
GRN='\033[0;32m'
YEL='\033[0;33m'
PRL='\033[0;34m'
CYN='\033[0;35m'
BLU='\033[0;36m'
NC='\033[0m'
######## Usage #########
usage() {
if [ $# -eq 0 ]; then
echo " "
echo "Usage: ${GRN}sh $0 ${CYN}<flag>${NC}"
echo " "
echo "==================== Flags ===================="
echo "-d Deeper review for errors, warns and compressed bosminer.log.*.gz files"
echo "-c Open the bosminer.log in an app (default is VS Code)"
echo "-s Review for notable events e.g. shutdown"
echo "-v Show version"
echo "-h Show helps"
echo "=============================================="
exit 1
fi
}
######## Operation flags ########
code=0
deep=0
smart=0
while getopts "dvhsc" opt; do
case $opt in
d)
deep=1 ;;
v)
echo "Version $version"
exit 0 ;;
h)
echo " "
echo "==================== Flags ===================="
echo "-d Deeper review for errors, warns and compressed bosminer.log.*.gz files"
echo "-c Open the bosminer.log in an app (default is VS Code)"
echo "-s Review for notable events e.g. shutdown"
echo "-v Show version"
echo "-h Show helps"
echo "=============================================="
exit 0 ;;
s)
smart=1 ;;
c)
code=1 ;;
*)
usage ;;
esac
done
# Type the support_archive file name
read -p "Type archive name (Hit ENTER for default name 'support_archive.zip.enc')? " -e in_name
in_name=${in_name:-support_archive.zip.enc}
# Type the folder name that you want to decoded into it
read -p "Output folder name (Hit ENTER for default name 'support_archive')? " -e out_name
out_name=${out_name:-support_archive}
######## Check log version ########
if [[ $in_name == *.zip ]]; then
# unzip archive
unzip -q -P braiins "$in_name" -d "$out_name"
ver=2101
filepath="$out_name"
configpath="$out_name"/bosminer.toml
pingpath="$out_name"/ping
localip="$out_name"/ifconfig
metricspath="$out_name"/log/metrics.prom
logpath="$out_name"/log/syslog
loggzpath="$out_name"/log/syslog.*
profilepath="$out_name"/bosminer-autotune.json
hwidpah="$out_name"/miner_hwid
refidpath="$out_name"/bos_refid
elif [[ $in_name == *.zip*.enc ]]; then
# decrypt and unzip archive
openssl aes-128-cbc -d -md md5 -nosalt -pass pass:braiins -in "$in_name" -out "$out_name".zip
# Unzip decode zip file
unzip -q "$out_name".zip -d "$out_name"
# Remove decoded zip file
rm "$out_name".zip
bosver=$(cat "$out_name"/filesystem/etc/bos_version)
if [[ $bosver == *"22.05-plus"* ]]; then
ver=2205
filepath="$out_name"/filesystem/etc
configpath="$out_name"/filesystem/etc/bosminer.toml
pingpath="$out_name"/builtin/ping_report
metricspath="$out_name"/filesystem/var/log/metrics.prom
logpath="$out_name"/filesystem/var/log/syslog
loggzpath="$out_name"/log/syslog.*
uptimepath="$out_name"/filesystem/proc/uptime
ippath="$out_name"/builtin/public_ip
localip="$out_name"/command/ifconfig_-a
profilepath="$out_name"/filesystem/etc/bosminer-autotune.json
hwidpah="$out_name"/filesystem/tmp/miner_hwid
refidpath="$out_name"/filesystem/etc/bos_refid
platformpath="$out_name"/filesystem/etc/bos_platform
dmesgpath="$out_name"/command/dmesg
cpupath="$out_name"/filesystem/proc/cpuinfo
else
ver=latest
filepath="$out_name"/filesystem/etc
configpath="$out_name"/filesystem/etc/bosminer.toml
pingpath="$out_name"/builtin/ping_report
metricspath="$out_name"/filesystem/var/log/metrics/metrics.prom
logpath="$out_name"/filesystem/var/log/bosminer/bosminer.log
loggzpath="$out_name"/filesystem/var/log/bosminer/bosminer.log.*
uptimepath="$out_name"/filesystem/proc/uptime
ippath="$out_name"/builtin/public_ip
localip="$out_name"/command/ifconfig_-a
profilepath="$out_name"/filesystem/etc/bosminer-autotune.json
hwidpah="$out_name"/filesystem/tmp/miner_hwid
refidpath="$out_name"/filesystem/etc/bos_refid
platformpath="$out_name"/filesystem/etc/bos_platform
dmesgpath="$out_name"/command/dmesg
cpupath="$out_name"/filesystem/proc/cpuinfo
fi
else
echo "The file name is not recognized!"
fi
######## Collecting logs ########
echo " "
printf "${PRL}============================ Device Overview ============================ \n${NC}"
# board=$filepath/board.json
# if [[ -f "$board" ]]; then
# sed -e '4q;d' $filepath/board.json | xargs -L1 echo "Board"
# fi
grep -o 'BHB[0-9]*' $dmesgpath | xargs -L1 echo "Variant: "
grep -m1 'PSU: version' $logpath | cut -d\' -f2 | awk '{print $1}' | xargs -L1 echo "PSU type: "
if [[ -f $platformpath ]]; then
cat $filepath/bos_platform | xargs -L1 echo "Platform: "
fi
grep 'Hardware' $cpupath | cut -d':' -f2 | sed 's/Generic AM33XX/BeagleBone/' | xargs -L1 echo "CB Type: "
cat $filepath/bos_mode | xargs -L1 echo "BOS+ Mode: "
cat $filepath/bos_version | xargs -L1 echo "Version: "
printf "${BLU}"
cat $hwidpah | xargs -L1 echo "HW ID: "
printf "${NC}"
grep -m1 'inet addr' $localip | cut -d: -f2 | awk '{print $1}' | xargs -L1 echo "Local IP: "
if [[ -f $ippath ]]; then
cat $ippath | xargs -L1 echo "Public IP: "
else
echo "Public IP: Not found!"
fi
if [[ -f $uptimepath ]]; then
printf "Uptime: " && awk '{print int($1/3600)":"int(($1%3600)/60)":"int($1%60)}' $uptimepath
else
echo "Uptime: Not found!"
fi
if [[ ! -f $refidpath ]]; then
echo "Ref ID: Not found!"
else
cat $refidpath | xargs -L1 echo "Ref ID: "
fi
printf "${PRL}============================ Config Overview ============================ \n${NC}"
printf "${GRN}"
grep 'model_detection' -A1 $configpath | grep -v 'model_detection' | xargs -L1
printf "${NC}"
if grep -q 'Antminer X' $configpath; then
printf "EEPROM = ${RED}Model Detection Failed${NC}\n"
else
printf "EEPROM = ${GRN}Model Detection OK${NC}\n"
fi
echo " "
cat -s $configpath | xargs -L1
printf "${PRL}============================ Mining Overview ============================ \n${NC}"
if [[ -f "$profilepath" ]]; then
printf "${GRN}Saved Profiles found:\n${NC}"
json=$(cat $profilepath)
# Use jq to extract the "Power" values
powers=$(echo $json | jq '.boards[].profile_target.Power'
)
echo $powers
else
printf "${YEL}No saved profile\n${NC}"
fi
echo " "
if grep -q 'Antminer S\|Antminer T' $configpath; then
# Power limits
printf "${BLU}"
grep -Eo '^miner_power{socket="N/A",type="estimated"}\s(\d.*)\s\d.*' $metricspath | tail -n 1 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "Estimated(W): "
done <tmp && rm tmp
grep -Eo '^miner_power_target_w{active="1",type="current"}\s(\d.*)\s\d.*' $metricspath | tail -n 1 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "Current(W): "
done <tmp && rm tmp
printf "${NC}"
grep -Eo '^hashboard_power{hashboard=\".*\",type="estimated"}\s(\d.*)\s\d.*' $metricspath | tail -n 3 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "HBs Estimated(W): "
done <tmp && rm tmp
# Hashboards chips count
printf "${BLU}"
grep -Eo '^chips_discovered{hashboard=\".*\"}\s(\d.*)\s\d.*' $metricspath | tail -n 3 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "Hashboard Chips: "
done <tmp && rm tmp
# Fans RPM
printf "${NC}"
grep -Eo '^fan_speed_control\s(\d.*)\s\d.*' $metricspath | tail -n 1 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "Fans Speed % : "
done <tmp && rm tmp
grep -Eo '^fan_rpm_feedback{idx=\".*\"}\s(\d.*)\s\d.*' $metricspath | tail -n 4 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "Fans Speed RPM: "
done <tmp && rm tmp
# Hashboards temperature
printf "${BLU}"
grep -Eo '^hashboard_temperature{hashboard=\".*\",type="raw"}\s(\d.*)\s\d.*' $metricspath | head -n 3 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "Hashboard Temp: "
done <tmp && rm tmp
# Nominal Hashrate
# printf "${NC}"
# grep -Eo '^hashboard_nominal_hashrate_gigahashes_per_second{hashboard=\".*\"}\s(\d.*)\s\d.*' $metricspath | head -n 3 >tmp
# while read -r line; do
# echo $line | cut -d " " -f 2 | xargs -n1 echo "Nominal HR(GH/s): "
# done <tmp && rm tmp
# Tuenr Iteration
printf "${NC}"
grep -Eo '^tuner_iteration{hashboard=\".*\"}\s(\d.*)\s\d.*' $metricspath | tail -n 3 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "Tuner Iteration: "
done <tmp && rm tmp
printf "${BLU}"
grep -Eo '^tuner_stage{hashboard="3"}\s(\d.*)\s\d.*' $metricspath | tail -n 1 >tmp
while read -r line; do
echo $line | cut -d " " -f 2 | xargs -n1 echo "Tuner Stage: "
done <tmp && rm tmp
else
printf "${YEL}There is no metrics data due to failed model detection!${NC}\n"
fi
printf "${PRL}============================== Ping Report ============================== \n${NC}"
if [[ ver == 2101 ]]; then
sed -n 17,25p $pingpath
else
sed -n 5,9p $pingpath
fi
printf "${PRL}============================== Logs Report ============================== \n${NC}"
grep -c 'ERROR' $logpath | xargs -L1 echo "Errors: "
grep -c 'WARN' $logpath | xargs -L1 echo "Warns: "
printf "${RED}::Last ERROR: "
grep -m1 'ERROR' $logpath | xargs -L1
echo " "
printf "${YEL}::Last WARN: "
grep -m1 'WARN' $logpath | xargs -L1
echo " "
printf "${CYN}::Smart Search: "
grep -m1 'Shutdown' -e 'DANGEROUS' -e 'Init failed' -e 'panicked' -e 'NoChipsDetected' -e 'BUG' $logpath | xargs -L1
printf "${NC} \n"
printf "${PRL}===============================================================\n${NC}"
######## Flag -d Review logs ########
if [[ $deep == 1 ]]; then
read -p "Do you want to review ERROR logs [Default is (y)es]? " error_log
error_log=${error_log:-y}
if [[ $error_log == y ]]; then
printf "${RED}::ERROR:\n"
grep 'ERROR' $logpath | sort -u
fi
printf "${NC}========================================================================\n"
read -p "Do you want to review WARN logs [Default is (y)es]? " warn_log
warn_log=${warn_log:-y}
if [[ $warn_log == y ]]; then
printf "${YEL}\n::WARN:\n"
grep 'WARN' $logpath | sort -u
fi
printf "${NC}========================================================================\n"
read -p "Do you want to review 'compressed' ERROR logs [Default is (y)es]? " cerror_log
cerror_log=${cerror_log:-y}
if [[ $cerror_log == y ]]; then
printf "${RED}\n::ERROR:\n"
if ls $loggzpath 1> /dev/null 2>&1; then
zgrep -h "ERROR" $(ls -tr $loggzpath) | sort -u
else
echo "There is no compressed bosminer.log files"
fi
fi
printf "${NC}========================================================================\n"
read -p "Do you want to review 'compressed' WARN logs [Default is (y)es]? " cwarn_log
cwarn_log=${cwarn_log:-y}
if [[ $cwarn_log == y ]]; then
printf "${YEL}\n::WARN:\n"
if ls $loggzpath 1> /dev/null 2>&1; then
zgrep -h "WARN" $(ls -tr $loggzpath) | sort -u
else
echo "There is no compressed bosminer.log files"
fi
fi
printf "${NC}=======================================================================\n"
fi
######## Flag -s Detect notable events in the logs ########
if [[ $smart == 1 ]]; then
read -p "Do you want to show notable events [Default is (y)es]? " notable
notable=${notable:-y}
if [[ $notable == y ]]; then
printf "${CYN}"
grep -e 'Shutdown' -e 'shutdown' -e 'DANGEROUS' -e 'Init failed' -e 'panicked' -e 'NoChipsDetected' -e 'BUG' $logpath | sort -u
fi
printf "${NC}=======================================================================\n"
fi
####### Flag -c to open bosminer.log file in VScode ######
if [[ $code == 1 ]]; then
read -p "Do you want to open logs automatically on VSCode [Default is (y)es]? " open_auto
open_auto=${open_auto:-y}
if [[ $open_auto == y ]]; then
open -a "Visual Studio Code" $logpath && open -a "Visual Studio Code"
fi
fi
|
92fd6435aa734021cba27ae0b306d5a5
|
{
"intermediate": 0.3279199004173279,
"beginner": 0.3819957673549652,
"expert": 0.2900843918323517
}
|
9,629
|
In Australia, an address is made up of a number followed by a street name, then a street type (e.g. St, Ave, Cres, Rd, Pl), then a suburb or town and finally a 4 digit postcode. Describe an address using a railroad diagram.
|
1e7ed40ef5661ed9388b30be386716e9
|
{
"intermediate": 0.3424856960773468,
"beginner": 0.24468542635440826,
"expert": 0.4128289222717285
}
|
9,630
|
Create me a simple Unity game in 2D with a top view. The circle character should WASD in all directions, and food circles will spawn around him. The most important condition is to add ML Agents and then explain to me how to set everything up. If anything, I have Unity and ML Agents installed and imported. I only need the code and instructions on how to make the training of the neural network start, as well as how to switch to keyboard control. The code must be complete and working.
|
61926cf1d56dc9f04e6893b376ef72a0
|
{
"intermediate": 0.2356054186820984,
"beginner": 0.17129892110824585,
"expert": 0.5930956602096558
}
|
9,631
|
As a python developer, write a telegram bot with "python-telegram-bot" 3.17 to do the explanation below:
my token is: 1935475560:AAHwHnildfDXMxNw_XVJSt6J7cCIcyO_t9o
I have 3 zip files below with names beside the bot.py file which you will code it:
braiins-toolbox_aarch64-linux.zip
braiins-toolbox_armv7-linux.zip
braiins-toolbox_x86_64-linux.zip
all of the files above have a binary braiins-toolbox.
I want a telegram bot based on python-telegram-bot 3.17, It should get a referral ID(refid) and Company name(coname) from the user and unzip the zip files above one by one and add the referral ID(refid) to the braiins_toolbox like braiins_toolbox_"refid" and then compress it with "tar -pczvf" into the files with the company name added to them.
so the final files should be like this:
braiins-toolbox_aarch64-linux.zip should be braiins-toolbox_aarch64-linux_coname.tar.gz
braiins-toolbox_armv7-linux.zip should be braiins-toolbox_armv7-linux_coname.tar.gz
braiins-toolbox_x86_64-linux.zip should be braiins-toolbox_x86_64-linux_coname.tar.gz
at the last stage, these files should send to the user in telegram as files with this message:
=======
Referral ID "refid" is ready for "coname"
=======
|
fa0ccc7d0f1da1064f0179c5b94b4168
|
{
"intermediate": 0.3884311020374298,
"beginner": 0.2800529897212982,
"expert": 0.33151593804359436
}
|
9,632
|
i have an EmptyObject called "Training Area", in this object i have Player, Floor, WallTop, WallBottom, WallRight, WallLeft and all spawning foods.
when i have more than 1 "Training Area", all food from other Training Areas spawns in first Training Area
here's FoodSpawner.cs, which in "Training Area":
using System.Collections;
using UnityEngine;
using Unity.MLAgents;
public class FoodSpawner : MonoBehaviour
{
public GameObject foodPrefab;
public int numberOfFoods;
public float spawnRange;
public float maxEpisodeTime = 30f; // in seconds
private float episodeTimer;
private PlayerController player;
private void Start()
{
player = GetComponentInChildren<PlayerController>();
if (player != null)
{
player.SetFoodSpawner(this);
}
SpawnFood();
episodeTimer = maxEpisodeTime;
}
void Update()
{
ManageEpisode();
}
public void SpawnFood(int customNumberOfFoods = -1)
{
// Delete any remaining food
foreach (var food in GetComponentsInChildren<Food>())
{
Destroy(food.gameObject);
}
int foodCount = customNumberOfFoods != -1 ? customNumberOfFoods : numberOfFoods;
for (int i = 0; i < foodCount; i++)
{
Vector2 spawnPosition = new Vector2(Random.Range(-spawnRange, spawnRange), Random.Range(-spawnRange, spawnRange));
GameObject newFood = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform);
newFood.transform.localScale = Vector3.one;
}
}
void ManageEpisode()
{
episodeTimer -= Time.deltaTime;
int remainingFoodCount = GetComponentsInChildren<Food>().Length;
if (episodeTimer <= 0 || remainingFoodCount == 0)
{
player.ResetPlayerEpisode();
SpawnFood();
episodeTimer = maxEpisodeTime;
}
}
}
|
59e09723fb92571f0a9f7efd75b21ab1
|
{
"intermediate": 0.3473266065120697,
"beginner": 0.43868011236190796,
"expert": 0.21399325132369995
}
|
9,633
|
I need a telegram bot based on python-telegram-bot 3.17 to decrypt and unzip the files with extension ".zip.enc" that users forward them to it
decrypt command:
openssl aes-128-cbc -d -md md5 -nosalt -pass pass:braiins -in "forwarded_file" -out "random_name"
unzip command:
unzip -q "random_name".zip -d "random_name"
The path of files:
ver=latest
filepath="$out_name"/filesystem/etc
configpath="$out_name"/filesystem/etc/bosminer.toml
pingpath="$out_name"/builtin/ping_report
metricspath="$out_name"/filesystem/var/log/metrics/metrics.prom
logpath="$out_name"/filesystem/var/log/bosminer/bosminer.log
loggzpath="$out_name"/filesystem/var/log/bosminer/bosminer.log.*
uptimepath="$out_name"/filesystem/proc/uptime
ippath="$out_name"/builtin/public_ip
localip="$out_name"/command/ifconfig_-a
profilepath="$out_name"/filesystem/etc/bosminer-autotune.json
hwidpah="$out_name"/filesystem/tmp/miner_hwid
refidpath="$out_name"/filesystem/etc/bos_refid
platformpath="$out_name"/filesystem/etc/bos_platform
dmesgpath="$out_name"/command/dmesg
cpupath="$out_name"/filesystem/proc/cpuinfo
The sample analyze commands for Device Overview in bashscript which you can convert it to python:
============= Device Overview ===============
# board=$filepath/board.json
# if [[ -f "$board" ]]; then
# sed -e '4q;d' $filepath/board.json | xargs -L1 echo "Board"
# fi
grep -o 'BHB[0-9]*' $dmesgpath | xargs -L1 echo "Variant: "
grep -m1 'PSU: version' $logpath | cut -d\' -f2 | awk '{print $1}' | xargs -L1 echo "PSU type: "
if [[ -f $platformpath ]]; then
cat $filepath/bos_platform | xargs -L1 echo "Platform: "
fi
grep 'Hardware' $cpupath | cut -d':' -f2 | sed 's/Generic AM33XX/BeagleBone/' | xargs -L1 echo "CB Type: "
cat $filepath/bos_mode | xargs -L1 echo "BOS+ Mode: "
cat $filepath/bos_version | xargs -L1 echo "Version: "
printf "${BLU}"
cat $hwidpah | xargs -L1 echo "HW ID: "
printf "${NC}"
grep -m1 'inet addr' $localip | cut -d: -f2 | awk '{print $1}' | xargs -L1 echo "Local IP: "
if [[ -f $ippath ]]; then
cat $ippath | xargs -L1 echo "Public IP: "
else
echo "Public IP: Not found!"
fi
if [[ -f $uptimepath ]]; then
printf "Uptime: " && awk '{print int($1/3600)":"int(($1%3600)/60)":"int($1%60)}' $uptimepath
else
echo "Uptime: Not found!"
fi
if [[ ! -f $refidpath ]]; then
echo "Ref ID: Not found!"
else
cat $refidpath | xargs -L1 echo "Ref ID: "
fi
|
527dea3215212fb4ad45467597874737
|
{
"intermediate": 0.2931422293186188,
"beginner": 0.4942917823791504,
"expert": 0.21256597340106964
}
|
9,634
|
Flutter web platform. how to direct download file?
|
5a0cff9d127c654e9d9389897e5c71ec
|
{
"intermediate": 0.5772952437400818,
"beginner": 0.18191660940647125,
"expert": 0.24078813195228577
}
|
9,635
|
i have an EmptyObject called "Training Area", in this object i have Player, Floor, WallTop, WallBottom, WallRight, WallLeft and all spawning foods.
when i have more than 1 "Training Area", all food from other Training Areas spawns in first Training Area
here's FoodSpawner.cs, which in "Training Area":
using System.Collections;
using UnityEngine;
using Unity.MLAgents;
public class FoodSpawner : MonoBehaviour
{
public GameObject foodPrefab;
public int numberOfFoods;
public float spawnRange;
public float maxEpisodeTime = 30f; // in seconds
private float episodeTimer;
private PlayerController player;
private void Start()
{
player = GetComponentInChildren<PlayerController>();
if (player != null)
{
player.SetFoodSpawner(this);
}
SpawnFood();
episodeTimer = maxEpisodeTime;
}
void Update()
{
ManageEpisode();
}
public void SpawnFood(int customNumberOfFoods = -1)
{
// Delete any remaining food
foreach (var food in GetComponentsInChildren<Food>())
{
Destroy(food.gameObject);
}
int foodCount = customNumberOfFoods != -1 ? customNumberOfFoods : numberOfFoods;
for (int i = 0; i < foodCount; i++)
{
Vector2 spawnPosition = new Vector2(Random.Range(-spawnRange, spawnRange), Random.Range(-spawnRange, spawnRange));
GameObject newFood = Instantiate(foodPrefab, spawnPosition, Quaternion.identity, transform);
newFood.transform.localScale = Vector3.one;
}
}
void ManageEpisode()
{
episodeTimer -= Time.deltaTime;
int remainingFoodCount = GetComponentsInChildren<Food>().Length;
if (episodeTimer <= 0 || remainingFoodCount == 0)
{
player.ResetPlayerEpisode();
SpawnFood();
episodeTimer = maxEpisodeTime;
}
}
}
|
592284a2ed1b037b8cc5d4f61f0f28e4
|
{
"intermediate": 0.3473266065120697,
"beginner": 0.43868011236190796,
"expert": 0.21399325132369995
}
|
9,636
|
Flutter web platform. how to direct download file with authorization headers?
|
c5060e20af909adc4a690b3b0b7286e8
|
{
"intermediate": 0.622072696685791,
"beginner": 0.17533758282661438,
"expert": 0.2025897204875946
}
|
9,637
|
How to print user_chat_id in the welcome_text?
def start_command(update, context):
user_chat_id = update.message.chat_id
welcome_text = '''
Welcome to the 24/7 Support Branch!{user_chat_id}
If you would like to access forward this message to B.
'''
update.message.reply_text(welcome_text)
|
cd251d73d47757892bd9c724d2d47255
|
{
"intermediate": 0.38171353936195374,
"beginner": 0.35808438062667847,
"expert": 0.2602020800113678
}
|
9,638
|
Can you show me c++ code for ue5 that will let me move a UI window by the top border bar of an user widget
|
8c23381a2270802d475bc04b42771fef
|
{
"intermediate": 0.6353997588157654,
"beginner": 0.13461336493492126,
"expert": 0.22998689115047455
}
|
9,639
|
Event system for cpp
|
7cec0e6b24509a364688c375cbbfc3ab
|
{
"intermediate": 0.28913018107414246,
"beginner": 0.3480817675590515,
"expert": 0.36278802156448364
}
|
9,640
|
Flutter web platform. How to save binary data?
|
530d1b60f4c6db0256635fb094998372
|
{
"intermediate": 0.5359576344490051,
"beginner": 0.14512939751148224,
"expert": 0.31891295313835144
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.