row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
5,221
make me an executable program code in C. a program of a window consisting 60 to 60 square blocks each 20 pixels square big, that can turn black or white when i click on them, or click and drag them
8b7e613976a4d844793a41da5763e1bd
{ "intermediate": 0.4293473958969116, "beginner": 0.23671157658100128, "expert": 0.3339410126209259 }
5,222
who are you?
a151637a36d449a6c7c731143a962a59
{ "intermediate": 0.4095822274684906, "beginner": 0.25522953271865845, "expert": 0.33518823981285095 }
5,223
import logging from telegram import Update from telegram.ext import Updater, CommandHandler, MessageHandler, filters, CallbackContext # Enable logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) # Define the callback function for /start command def start(update: Update, context: CallbackContext) -> None: """Send a welcome message when the command /start is issued.""" update.message.reply_text('Hello! I\'m your friendly bot. How can I help you today?') # Define the callback function for handling messages def handle_message(update: Update, context: CallbackContext) -> None: """Echo the user's message back as a friendly reply.""" message = update.message.text update.message.reply_text(f"You said: {message}. That's great!") def main() -> None: """Start the bot.""" # Create the Updater and pass your bot's API token and use_context=True updater = Updater("6186986870:AAFMI-Vmq6fg7TC1pvJpq9wDpJxS8chRqM8", use_context=True) # Get the dispatcher to register handlers dispatcher = updater.dispatcher # Add handlers for /start command and messages dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_message)) # Start the bot updater.start_polling() # Run the bot until you press Ctrl-C to stop it updater.idle() if __name__ == '__main__': main() this code has an error
70a7f6c981ad40d1fdc608b252fe5646
{ "intermediate": 0.47176143527030945, "beginner": 0.3268417716026306, "expert": 0.2013968676328659 }
5,224
what program can you write
429d1e9cc7a20434bb59018759c5daca
{ "intermediate": 0.2349824607372284, "beginner": 0.23707903921604156, "expert": 0.5279384851455688 }
5,225
покажи классификацию текста с помощью PyTorch + LSTM
9394a0eb9d6b4ad0d7ca5fb6f0546cd9
{ "intermediate": 0.29654547572135925, "beginner": 0.11538586020469666, "expert": 0.5880687236785889 }
5,226
make me an executable program code in C++. a program of a window consisting 60 to 60 square blocks each 20 pixels square big, that can turn black or white when i click on them, or click and drag them
5295ab5f0ba7097bacf4d643327bba24
{ "intermediate": 0.4706505537033081, "beginner": 0.21127672493457794, "expert": 0.31807273626327515 }
5,227
Please remember the code below preprocessing of the image. Here I remove unnecessary part of the image -
5e0cfd136eeb3f2a94fab42ac4153cf0
{ "intermediate": 0.2776307165622711, "beginner": 0.18931794166564941, "expert": 0.5330513715744019 }
5,228
write a python code which simulate the floatbaility of a boat in water for which only mass varies
c1c41474c3667074794ae8c76171da01
{ "intermediate": 0.23410925269126892, "beginner": 0.1490972638130188, "expert": 0.6167935132980347 }
5,229
import torch import torch.nn as nn import torch.optim as optim from torchtext.legacy.data import Field, TabularDataset, BucketIterator, Iterator #from torchtext.data import BucketIterator import pandas as pd 2 import torch.nn as nn 3 import torch.optim as optim ----> 4 from torchtext.legacy.data import Field, TabularDataset, BucketIterator, Iterator 5 #from torchtext.data import BucketIterator 6 import pandas as pd ModuleNotFoundError: No module named 'torchtext.legacy'
bf6f1358dfe19607538f38d192990bdf
{ "intermediate": 0.38070935010910034, "beginner": 0.2855623662471771, "expert": 0.3337283432483673 }
5,230
@echo off color 0A :a Set /p comm=cmd~ %comm% Goto a
4e87ebfa844444974aaa02ce0e332ccc
{ "intermediate": 0.3305584192276001, "beginner": 0.3762845993041992, "expert": 0.29315701127052307 }
5,231
go?
0f736757b6b1776d2c6e1d6eb9041d0f
{ "intermediate": 0.3307446241378784, "beginner": 0.3497437834739685, "expert": 0.3195115625858307 }
5,232
Create a hacker themed batch file that is a menu that has a menu and 3 buttons, the menu says yellowstar520, the first button leads to a batch file and is labeled Commands, the next one is labeled Proxy and leads to https://navy.strangled.net, and the last one is labeled ... and plays a video.
0caf78298e2665be60dc9c283d10bb6b
{ "intermediate": 0.2946564853191376, "beginner": 0.27123451232910156, "expert": 0.4341089427471161 }
5,233
Can you add a restart option?
09273ff5beb0220d8388f56be4ad347a
{ "intermediate": 0.41391080617904663, "beginner": 0.18926458060741425, "expert": 0.3968246579170227 }
5,234
give me introduction about shell and tube heat exchanger
90bcfa255a46541770b99e9b15949861
{ "intermediate": 0.36876481771469116, "beginner": 0.36406612396240234, "expert": 0.2671690583229065 }
5,235
In this project, you will create a tool that will help a company print invoices and keep track of the total amount it has billed and the total amount it has discounted. Imagine the company has a regularly scheduled billing process. Perhaps every week, it prints invoices that it uses to communicate to the customer what the customer owes them for the purchases they made. Suppose that the company has two types of customers: retail and corporate. The discount schedules for these two types of customers differ. For retail customers,  If the bill is greater than or equal to $500, they get a 20% discount  If the bill is greater than or equal to $250 but less than $500 they get a 10 % discount  Otherwise, they don ’ t get a discount. For corporate customers,  If the bill exceeds or is equal to $1,000 they get a 30% discount  If the bill exceeds or is equal to $500 but is less than $1,000, they get a 20% discount  Otherwise, they don ’ t get a discount. Suppose further that the company only sells in the states of Illinois, Indiana, and Wisconsin. The company must assess the correct sales tax based on the state. If the customer is in Illinois (abbreviated IL), the sales tax is 8.75%. If the cust omer is in Wisconsin (WI), the sales tax is 8.25%. And if the customer is in Indiana (IN), the sales tax is 8.5%. Your program must repeatedly ask the user to enter invoice data. Specifically, your program will ask the user to enter the cost of the purchas e, the type of customer, and the state where the customer is located. Based on that, it will print a summary that shows the purchase cost, the sales tax collected, the amount of the discount, and the final price. Your program will continue doing this as lo ng as the user indicates they have more invoices to enter.
7ae9d0ba86173d0d5190ebfaeb254d43
{ "intermediate": 0.5003361701965332, "beginner": 0.223703533411026, "expert": 0.2759603261947632 }
5,236
can you code this project in C#: In this project, you will create a tool that will help a company print invoices and keep track of the total amount it has billed and the total amount it has discounted. Imagine the company has a regularly scheduled billing process. Perhaps every week, it prints invoices that it uses to communicate to the customer what the customer owes them for the purchases they made. Suppose that the company has two types of customers: retail and corporate. The discount schedules for these two types of customers differ. For retail customers,  If the bill is greater than or equal to $500, they get a 20% discount  If the bill is greater than or equal to $250 but less than $500 they get a 10 % discount  Otherwise, they don ’ t get a discount. For corporate customers,  If the bill exceeds or is equal to $1,000 they get a 30% discount  If the bill exceeds or is equal to $500 but is less than $1,000, they get a 20% discount  Otherwise, they don ’ t get a discount. Suppose further that the company only sells in the states of Illinois, Indiana, and Wisconsin. The company must assess the correct sales tax based on the state. If the customer is in Illinois (abbreviated IL), the sales tax is 8.75%. If the cust omer is in Wisconsin (WI), the sales tax is 8.25%. And if the customer is in Indiana (IN), the sales tax is 8.5%. Your program must repeatedly ask the user to enter invoice data. Specifically, your program will ask the user to enter the cost of the purchas e, the type of customer, and the state where the customer is located. Based on that, it will print a summary that shows the purchase cost, the sales tax collected, the amount of the discount, and the final price. Your program will continue doing this as lo ng as the user indicates they have more invoices to enter.
9ff1d412d5824f26ef0ffcacf89be4fa
{ "intermediate": 0.5823072791099548, "beginner": 0.1927027404308319, "expert": 0.22499001026153564 }
5,237
Evaluate the integral ∫10𝑥⎯⎯√𝑑𝑥=2/3 using Monte Carlo integration and 𝑃(𝑥)=1−𝑒−𝑎𝑥 . Find the value 𝑎 that minimizes the variance. Use Python.
8440d5bada73dd0c0ff1b0640c580835
{ "intermediate": 0.25649622082710266, "beginner": 0.22038862109184265, "expert": 0.5231151580810547 }
5,238
i have an interface CollegioVerbale { id: CollegioVerbaleID; idRicUdien: number; tipoMag: string; magistrato?: AnagraficaMagistratoCollegio; riserva: boolean; relatore: boolean; operatore: number; comparso: boolean; oggi: number; } write a function in typescript that cycles through an array of CollgeioVerbale and return true if there is on element with comparso value as true, else otherwise
b8f030edd1df25c27bfb7b5765b82ff5
{ "intermediate": 0.2924175262451172, "beginner": 0.5808377861976624, "expert": 0.12674464285373688 }
5,239
You are professional programming assistant. How to implement IAsyncDisposable and IDisposable at the same time for C# class that holds two manager resources: MySqlConnection and MySqlTransaction. Each of that resources also implements IAsyncDisposable and IDisposable at the same time.
3dd8bc832452adadf3ddc67b5f35978f
{ "intermediate": 0.7062664031982422, "beginner": 0.16997617483139038, "expert": 0.12375741451978683 }
5,240
в этом коде надо сделать так, чтобы переменные uniforms.light.value.x и uniforms.light.value.y передавались во фрагментный шейдер с отставанием в 1 секунду код: let scene; let camera; let renderer; function scene_setup() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); } scene_setup(); const shaderCode = document.getElementById('fragShader').innerHTML; const textureURL = 'aerial_rocks_02_diff_4k.jpg'; const normalURL = 'aerial_rocks_02_nor_gl_4k.png'; THREE.ImageUtils.crossOrigin = ''; const texture = THREE.ImageUtils.loadTexture(textureURL); const normal = THREE.ImageUtils.loadTexture(normalURL); let varX = 0.1; let varY = 0.1; let uniforms = { norm: { type: 't', value: normal }, light: { type: 'v3', value: new THREE.Vector3() }, tex: { type: 't', value: texture }, res: { type: 'v2', value: new THREE.Vector2(window.innerWidth, window.innerHeight) }, variable: { type: 'v2', value: new THREE.Vector2(varX, varY) }, }; let material = new THREE.ShaderMaterial({ uniforms: uniforms, fragmentShader: shaderCode }); let geometry = new THREE.PlaneGeometry(10, 10); let sprite = new THREE.Mesh(geometry, material); scene.add(sprite); camera.position.z = 2; uniforms.light.value.z = 0.05; function render() { uniforms.variable.value.x += 0.00000005; uniforms.variable.value.y += 0.00000005; requestAnimationFrame(render); renderer.render(scene, camera); } render(); document.onmousemove = function (event) { uniforms.light.value.x = event.clientX; uniforms.light.value.y = -event.clientY + window.innerHeight; };
eee78ef1bfddc7553495c5b066b1dde8
{ "intermediate": 0.37143605947494507, "beginner": 0.33228644728660583, "expert": 0.2962774336338043 }
5,241
Напиши код на pytorch +lstm, который классифицирует news_df = pd.DataFrame({ 'text': [ 'Американский депутат призвал запретить продажу трусов в красный цвет', 'В Москве откроется новый парк на месте автосалона Honda', 'Ожидается повышение температуры на 35 градусов в Техасе', 'Зарплаты в России вырастут в среднем на 10% в следующем году', 'Дональд Трамп заявил, что обладает силой, чтобы остановить ураган «Ирма»' ], 'label': [1, 1, 0, 0, 1] })
bd5c63b485c9b26afdf5a55f6f18db16
{ "intermediate": 0.3479423224925995, "beginner": 0.4520041346549988, "expert": 0.20005355775356293 }
5,242
Please explain this error: unresolved import `crate::bindings::flash_bots_uniswap_query` --> src/crossed_pair.rs:1:48 | 1 | use crate::{addresses::WETH_ADDRESS, bindings::flash_bots_uniswap_query::FlashBotsUniswapQuery}; | ^^^^^^^^^^^^^^^^^^^^^^^^ could not find `flash_bots_uniswap_query` in `bindings`
30942a0dcd4f000f6f2b5b92634b4b1c
{ "intermediate": 0.5393783450126648, "beginner": 0.28635990619659424, "expert": 0.17426173388957977 }
5,243
Can I have a vba code that checks if no cell in the sheet is selected and if so it then selcets the first empty cell in column b
d664b65eec102b503eccf378e251a142
{ "intermediate": 0.45816177129745483, "beginner": 0.10090263932943344, "expert": 0.4409356415271759 }
5,244
how to make div center
01091696adeafee2253cb4d4bf880d40
{ "intermediate": 0.27867788076400757, "beginner": 0.2775425910949707, "expert": 0.44377949833869934 }
5,245
can you dowload yt videos with python
1e840cbff752e2ddabf3374c98d78ba3
{ "intermediate": 0.3310321867465973, "beginner": 0.15846586227416992, "expert": 0.5105019807815552 }
5,246
Write my a Kafka client in Go
a4eeaaad4995ef9fb914c7cbd08fcc29
{ "intermediate": 0.5102180242538452, "beginner": 0.13786683976650238, "expert": 0.35191506147384644 }
5,247
Hello, lets create a antispam bot, using firebase as hosting, its ML as spam detector, db fore storing information. we will use dart language in android studio. my pubspec.yaml looks like this now: "name: ml_antispam_bot description: Antispam bot, that uses firebase ML to detect spam messages publish_to: 'none' version: 1.0.0+1 environment: sdk: '>=2.19.0 <3.0.0' dependencies: flutter: sdk: flutter dart_telegram_bot: ^1.0.0 firebase_core: ^1.3.0 firebase_database: ^7.1.0 google_ml_kit: ^0.14.0 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^2.0.0 flutter: uses-material-design: true"
28d134495588be3c3e58051602dae1db
{ "intermediate": 0.3732624351978302, "beginner": 0.2947898209095001, "expert": 0.3319476842880249 }
5,248
what does this mean Traceback (most recent call last): File “C:\Users\elias\PycharmProjects\pythonProject1\main.py”, line 27, in <module> .input(audio_filepath) ^^^^^ AttributeError: module ‘ffmpeg’ has no attribute ‘input’ Process finished with exit code 1 for this code import os import requests from pytube import YouTube import ffmpeg # Create object for the YouTube video yt = YouTube("https://www.youtube.com/watch?v=N_3j3gkY8JM&list=PLNFI79D7MYqPlOvLY1TqRKnZWCGKMIIGw&index=2") # Filter streams to get the audio and video streams, and select the first audio stream audio_stream = yt.streams.filter(only_audio=True).first() # Download the audio stream audio_filepath = os.path.join(r"C:\Users\elias\PycharmProjects", yt.title + ".mp3") audio_stream.download(output_path=audio_filepath) # Download the thumbnail thumbnail_url = yt.thumbnail_url thumbnail_path = os.path.join("C:/Users/elias/Pictures", yt.title + ".jpg") thumbnail_data = requests.get(thumbnail_url).content with open(thumbnail_path, 'wb') as f: f.write(thumbnail_data) # Use FFmpeg to combine the audio and thumbnail into a single video video_filepath = os.path.join(r"C:\Users\elias\PycharmProjects", yt.title + ".mp4") ( ffmpeg .input(audio_filepath) .overlay(thumbnail_path) .output(video_filepath, shortest=None, vcodec='libx264') .run() ) # Delete the audio and thumbnail files os.remove(audio_filepath) os.remove(thumbnail_path)
83dafb540742d47815e6e685b658e37c
{ "intermediate": 0.6329640746116638, "beginner": 0.2208189070224762, "expert": 0.14621703326702118 }
5,249
import os import requests from pytube import YouTube import ffmpeg # Create object for the YouTube video yt = YouTube("https://www.youtube.com/watch?v=N_3j3gkY8JM&list=PLNFI79D7MYqPlOvLY1TqRKnZWCGKMIIGw&index=2") # Filter streams to get the audio and video streams, and select the first audio stream audio_stream = yt.streams.filter(only_audio=True).first() # Download the audio stream audio_filepath = os.path.join(r"C:\Users\elias\PycharmProjects", yt.title + ".mp3") audio_stream.download(output_path=r"C:\Users\elias\PycharmProjects") # Download the thumbnail thumbnail_url = yt.thumbnail_url thumbnail_path = os.path.join("C:/Users/elias/Pictures", yt.title + ".jpg") thumbnail_data = requests.get(thumbnail_url).content with open(thumbnail_path, 'wb') as f: f.write(thumbnail_data) # Use FFmpeg to combine the audio and thumbnail into a single video video_filepath = os.path.join(r"C:\Users\elias\PycharmProjects", yt.title + ".mp4") ( ffmpeg .input(r"C:\Users\elias\PycharmProjects") .overlay(r"C:\Users\elias\PycharmProjects") .output(r"C:\Users\elias\PycharmProjects", shortest=None, vcodec='libx264') .run() ) # Delete the audio and thumbnail files os.remove(r"C:\Users\elias\PycharmProjects") os.remove(r"C:\Users\elias\PycharmProjects") why doesnt this work
c5e4a758991274608eda45d4f1fcfc91
{ "intermediate": 0.5385635495185852, "beginner": 0.22100546956062317, "expert": 0.24043095111846924 }
5,250
Please convert the following c# code into the equivalent dart code:
6186908f8428e50febed540249069f3e
{ "intermediate": 0.3328748345375061, "beginner": 0.41849178075790405, "expert": 0.24863342940807343 }
5,251
How should I memorize this?
6f2f943bad6d400edd327fa6624fe651
{ "intermediate": 0.3002264201641083, "beginner": 0.4426858723163605, "expert": 0.25708767771720886 }
5,252
I need help writing metatrader 5 indicator
c2fe3c7f098909f1a195cb002de104f2
{ "intermediate": 0.26072362065315247, "beginner": 0.31316521763801575, "expert": 0.4261111319065094 }
5,253
how do i get all instances of chrome webdriver selenium in python?
83c9f8b1504d3c381cba958a444ef9dd
{ "intermediate": 0.5768095254898071, "beginner": 0.09860552102327347, "expert": 0.3245849013328552 }
5,254
The following code has a select url, can you please make it so it is set automatically to the url I say?
156ee79bceb605873a316c22ebf46562
{ "intermediate": 0.4281897246837616, "beginner": 0.18031814694404602, "expert": 0.39149209856987 }
5,255
write for me a open cv script that sets the mouse to the middle of the page, emulates scrolldown each scroll he is taking screenshot and analizing the picture in opencv when found the both team names on roughly the same Hight on the screen emulate a click on the button with the button string string the function will look like so: def find_and_click_button_csgoroll(team_1, team_2, button_string): the script is for the website: https://www.csgoroll.com/en/e-sports feel free the add features that you see fit to the function
f5207c4562f664a819f7786599195f7f
{ "intermediate": 0.32028698921203613, "beginner": 0.3641490340232849, "expert": 0.31556394696235657 }
5,256
from pytube import YouTube #Create object for the YouTube video yt = YouTube("https://youtube.com/playlist?list=PLNFI79D7MYqPlOvLY1TqRKnZWCGKMIIGw") #Select the highest resolution video video = yt.streams.get_highest_resolution() #Download the video video.download (r"C:\Users\elias\PycharmProjects") how can i change the code it downloads playlists
90261c5e2952f785ee38acc756d009e5
{ "intermediate": 0.5160258412361145, "beginner": 0.218942329287529, "expert": 0.26503175497055054 }
5,257
generate the code for an ERC-20
2c2478d419c279f417a06bdfc9aa033e
{ "intermediate": 0.20627379417419434, "beginner": 0.16395911574363708, "expert": 0.6297670602798462 }
5,258
how can i make a music plailist downloaded based on the title of the album with python in the mp3 file type for example A DEMON IN 6LUE lil loaded music
bbc191a7db940a7bbbd36f301f377d66
{ "intermediate": 0.38964563608169556, "beginner": 0.09351503849029541, "expert": 0.516839325428009 }
5,259
Почему if (isset($_SESSION'logged')) Warning : Undefined array key "logged"
d940a191b16b0dc542bc3f91c4b44e17
{ "intermediate": 0.35802990198135376, "beginner": 0.3148961365222931, "expert": 0.32707396149635315 }
5,260
Compute the integral ∫10𝑥⎯⎯√𝑑𝑥=2/3 using Monte Carlo integration and 𝑃(𝑥)=1−𝑒−𝑎𝑥 . Find the value 𝑎 that minimizes the variance.
a29bee91aac9789ea659616eda28b3e3
{ "intermediate": 0.2047550082206726, "beginner": 0.14359252154827118, "expert": 0.651652455329895 }
5,261
please comment the lines of this code: please comment the lines of this rust code, and explain it: use itertools::Itertools; use std::sync::Arc; use crate::{ addresses::WETH_ADDRESS, bindings::{ flash_bots_uniswap_query::FlashBotsUniswapQuery, i_uniswap_v2_factory::IUniswapV2Factory, }, }; use ethers::prelude::*; pub async fn get_markets_by_token<M>( factory_addresses: Vec<Address>, flash_query_contract: &FlashBotsUniswapQuery<M>, client: Arc<M>, ) -> Vec<(H160, Vec<[H160; 3]>)> where M: Middleware, { let factories: Vec<DexFactory<M>> = factory_addresses .into_iter() .map(|address| DexFactory::new(address, flash_query_contract, client.clone())) .collect(); let weth_address = &WETH_ADDRESS.parse::<Address>().unwrap(); let mut pairs: Vec<[H160; 3]> = vec![]; for factory in factories { let market_pairs = factory .get_markets() .await .into_iter() .collect::<Vec<[H160; 3]>>(); for pair in market_pairs { pairs.push(pair.to_owned()); } } let grouped_pairs: Vec<(H160, Vec<[H160; 3]>)> = pairs .into_iter() .filter(|pair| { // println!("pair[0]: {}", pair[0]); pair[0].eq(weth_address) || pair[1].eq(weth_address) }) .sorted_by(|pair0, pair1| { let non_weth0 = if pair0[0].eq(weth_address) { pair0[1] } else { pair0[0] }; let non_weth1 = if pair1[0].eq(weth_address) { pair1[1] } else { pair1[0] }; non_weth1.cmp(&non_weth0) }) .group_by(|pair| { if pair[0].eq(weth_address) { pair[1] } else { pair[0] } }) .into_iter() .map(|(key, group)| { let pairs = group.collect::<Vec<[H160; 3]>>(); (key, pairs) }) .filter(|(_, pairs)| pairs.len() > (1_usize)) .collect::<Vec<(H160, Vec<[H160; 3]>)>>(); grouped_pairs } pub struct DexFactory<'a, M> { factory_contract: IUniswapV2Factory<M>, flash_query_contract: &'a FlashBotsUniswapQuery<M>, } // This should hold Factory of each Dex // and have a method to query pairs impl<'a, M> DexFactory<'a, M> where M: Middleware, { pub fn new( pair_address: Address, flash_query_contract: &'a FlashBotsUniswapQuery<M>, client: Arc<M>, ) -> Self { let contract = IUniswapV2Factory::new(pair_address, client); Self { factory_contract: contract, flash_query_contract, } } pub async fn get_markets(&self) -> Vec<[H160; 3]> { let batch_size = U256::from(1000u32); let mut start = U256::from(0u32); let batch_limit = 10; let mut count = 0; let mut markets: Vec<[H160; 3]> = vec![]; loop { let stop = start + batch_size; let pairs = self .flash_query_contract .get_pairs_by_index_range(self.factory_contract.address(), start, stop) .call() .await .unwrap(); count += 1; start = stop; let pair_length = pairs.len(); markets.extend(pairs); if pair_length < batch_size.as_usize() || count > batch_limit { dbg!(markets.len()); break; } } markets } }
9b808b3ab82cff8eb8c5ab8fedd443f1
{ "intermediate": 0.5011444687843323, "beginner": 0.3813750445842743, "expert": 0.11748041957616806 }
5,262
from pytube import Playlist #Create object for the YouTube playlist pl = Playlist("https://youtube.com/playlist?list=PLNFI79D7MYqPlOvLY1TqRKnZWCGKMIIGw") #Loop through all the videos in the playlist and download them for video in pl.videos: video.streams.filter(only_audio=True).first().download(r"C:\Users\elias\PycharmProjects") how ro change it so the file is mp3 type
20557403200db250c1e8dc4864ad2593
{ "intermediate": 0.3974079191684723, "beginner": 0.22769244015216827, "expert": 0.37489959597587585 }
5,263
Write me an example code of an sqlite database implementation in react native
8960669485fdfaabf7a7e007dca59422
{ "intermediate": 0.8451457619667053, "beginner": 0.09216072410345078, "expert": 0.06269354373216629 }
5,264
i get this error : C:\Users\elias\PycharmProjects\pythonProject1\venv\Scripts\python.exe C:\Users\elias\PycharmProjects\pythonProject1\main.py Traceback (most recent call last): File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\urllib\request.py", line 1348, in do_open h.request(req.get_method(), req.selector, req.data, headers, File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\http\client.py", line 1282, in request self._send_request(method, url, body, headers, encode_chunked) File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\http\client.py", line 1328, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\http\client.py", line 1277, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\http\client.py", line 1037, in _send_output self.send(msg) File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\http\client.py", line 975, in send self.connect() File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\http\client.py", line 1447, in connect super().connect() File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\http\client.py", line 941, in connect self.sock = self._create_connection( ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\socket.py", line 827, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\elias\AppData\Local\Programs\Python\Python311\Lib\socket.py", line 962, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ socket.gaierror: [Errno 11002] getaddrinfo failed During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\elias\PycharmProjects\pythonProject1\main.py", line 12, in <module> for video in pl.videos: File "C:\Users\elias\PycharmProjects\pythonProject1\venv\Lib\site-packages\pytube\helpers.py", line 71, in __iter__ curr_item = self[iter_index] ~~~~^^^^^^^^^^^^ File "C:\Users\elias\PycharmProjects\pythonProject1\venv\Lib\site-packages\pytube\helpers.py", line 57, in __getitem__ next_item = next(self.gen) ^^^^^^^^^^^^^^ from pytube import Playlist from moviepy.editor import * from mutagen.easyid3 import EasyID3 # Create object for the YouTube playlist pl = Playlist(“https://youtube.com/playlist?list=PLNFI79D7MYqPlOvLY1TqRKnZWCGKMIIGw”) # Set output directory path output_directory = r"C:\Users\elias\PycharmProjects" # Loop through all the videos in the playlist and download their audio streams for video in pl.videos: audio_stream = video.streams.filter(only_audio=True).first() audio_file_path = audio_stream.download(output_path=output_directory) # Convert audio file to mp3 format mp3_file_path = os.path.splitext(audio_file_path)[0] + “.mp3” AudioFileClip(audio_file_path).write_audiofile(mp3_file_path) os.remove(audio_file_path) # Delete the original audio file (mp4 format) # Set contributing artist tag to YouTube channel name audio = EasyID3(mp3_file_path) audio[‘artist’] = [video.author] audio.save() Process finished with exit code 1
c2fbf5b258c3834f3968a2a586576d03
{ "intermediate": 0.341301292181015, "beginner": 0.38153567910194397, "expert": 0.27716299891471863 }
5,265
how to download a yt playlist with python in mp3 format
5b3a6d42f4f5a4c914ef64710c125391
{ "intermediate": 0.3479502499103546, "beginner": 0.3078489303588867, "expert": 0.34420081973075867 }
5,266
make a python code that downloads yt music playlists with url
46e9b2df94d272331aad9786658bedb0
{ "intermediate": 0.44382205605506897, "beginner": 0.19911810755729675, "expert": 0.3570598065853119 }
5,267
do you have any mini project working on php?
ebbf415ced99e9efc90ba00f25749a7c
{ "intermediate": 0.40878748893737793, "beginner": 0.353767067193985, "expert": 0.23744545876979828 }
5,268
function [root, num_iterations] = bisection_method(f, xL, xU, tol) without any built in functions
a366637cab20470047fc1fa028d7e20e
{ "intermediate": 0.28268009424209595, "beginner": 0.44694551825523376, "expert": 0.2703743278980255 }
5,269
How to make chroot jail on mac os
e1ea23adcc67c3c1632b3e7a19566961
{ "intermediate": 0.3232930302619934, "beginner": 0.4117589592933655, "expert": 0.2649479806423187 }
5,270
в коде using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { public int health = 5; public ParticleSystem deathEffect; public SpawnEnemy spawner; private bool dead; private void Die() { if (deathEffect != null && !dead) { dead = true; // Создаем новый объект эффекта частиц в позиции объекта врага ParticleSystem playingEffect = Instantiate(deathEffect, transform.position, Quaternion.identity); // Запускаем проигрывание эффекта частиц playingEffect.Play(); // Удаляем объект врага с задержкой в 1 секунду после проигрывания эффекта частиц spawner.DestroyObject(gameObject); } } public void TakeDamage(int damage) { health -= damage; if (health <= 0 && !dead) { health = 0; Die(); } } } ошибка Assets\Enemy.cs(23,13): error CS0176: Member 'Object.Destroy(Object)' cannot be accessed with an instance reference; qualify it with a type name instead
f7f5ba9b4716eb28f7050417b96738a1
{ "intermediate": 0.35525307059288025, "beginner": 0.4536287486553192, "expert": 0.19111819565296173 }
5,271
Given three vectors A , B and C of dimension n with elements of real numbers. Write an algorithm which finds if there are three numbers, one from each of the matrices (vectors) A , B and C , which sum to 0. a) Can you find an O(n^3) algorithm? b) Can you find an O(n^2*logn) algorithm? c)Can you find an O(n^2) algorithm? d)Can you find an algorithm faster than O(n^2)?
77e027768a38c37fe2c7ea8f8812b364
{ "intermediate": 0.09087301790714264, "beginner": 0.07080163806676865, "expert": 0.8383253812789917 }
5,272
void Update() { if (!isEnabled) return; if (objectsList.Count < maxCount && Time.time >= nextSpawnTime) { if (totalCount < maxTotalCount) { Vector3 spawnPosition = transform.position + Random.onUnitSphere * spawnRadius; RaycastHit hit; if (Physics.Raycast(spawnPosition, Vector3.down, out hit, Mathf.Infinity, terrainLayer)) { GameObject obj = Instantiate(objectPrefab, hit.point, Quaternion.identity); obj.layer = LayerMask.NameToLayer("Terrain"); objectsList.Add(obj); totalCount++; } } else { isEnabled = false; Debug.Log("Максимальное количество объектов достигнуто"); return; } nextSpawnTime = Time.time + Random.Range(0, maxSpawnTime); } for (int i = objectsList.Count - 1; i >= 0; i-) { if (objectsList[i] == null) { objectsList.RemoveAt(i); } } } ошибка Assets\Mimic\Scripts\SpawnEnemy.cs(56,55): error CS1525: Invalid expression term ')'
29a7f8ebba3a6a61149559dbd5fa1340
{ "intermediate": 0.3820856213569641, "beginner": 0.4030095338821411, "expert": 0.2149048000574112 }
5,273
HI
f72d0eb5129a1f8f6076743b10b3fec0
{ "intermediate": 0.32988452911376953, "beginner": 0.2611807882785797, "expert": 0.40893468260765076 }
5,274
what is dc in assembly
c2c6b720ce281f2a6f3d5cd0737438ce
{ "intermediate": 0.330405592918396, "beginner": 0.4960739314556122, "expert": 0.17352047562599182 }
5,275
My assignment is - "given 2 images , you have to classify that is written by same person or not if it is same person then output will be 1 else output will be 0". For that problem I have one folder of dataset . In that folder(dataset) I have 1352 of subfolders, each subfolder define different person's handwritting. each folder have 4 or 5 or 6 handwritting of that person. so make a model from scratch , how to read folder and how to make the model . okay ? Is that problem is clear for you , if you have any question tell me?
6fd14172632cd5ad2e7cc5837c36be79
{ "intermediate": 0.3354300558567047, "beginner": 0.2023051530122757, "expert": 0.4622648060321808 }
5,276
Is it possible to create a RPG leveling system in MCreator
48cf3e2e08770f3266de57c7becc0f24
{ "intermediate": 0.3933103382587433, "beginner": 0.38577237725257874, "expert": 0.22091734409332275 }
5,277
Simulate Assembly:
8552d182bf485bfddb460adc17c633c0
{ "intermediate": 0.3135735094547272, "beginner": 0.3988647758960724, "expert": 0.2875617444515228 }
5,278
could you write a program in c# that takes a file with a list of words and puts it in a string array?
6c6217e01af72e79e52406f0f8f1f359
{ "intermediate": 0.5920731425285339, "beginner": 0.1928253471851349, "expert": 0.21510151028633118 }
5,279
i have a code of visualization of neural network, but part of pygame is not full. there is not bullet, there is not bullet range, bullet speed etc. import numpy as np import random import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # Constants GAME_AREA_WIDTH = 1000 GAME_AREA_HEIGHT = 1000 # Random enemy movement def update_enemy_position(enemy_pos, enemy_vel): new_pos_x = enemy_pos[0] + enemy_vel[0] new_pos_y = enemy_pos[1] + enemy_vel[1] return new_pos_x, new_pos_y def random_velocity(): speed = random.uniform(3, 10) angle = random.uniform(0, 2 * np.pi) vel_x = speed * np.cos(angle) vel_y = speed * np.sin(angle) return vel_x, vel_y # Neural network input_neurons = 9 # Including the enemy velocities (2 additional inputs) output_neurons = 2 model = Sequential() model.add(Dense(32, activation='relu', input_dim=input_neurons)) model.add(Dense(64, activation='relu')) model.add(Dense(output_neurons)) model.compile(optimizer='adam', loss='mse', metrics=['accuracy']) # Input: bullet speed, bullet range, player x, player y, enemy x, enemy y, enemy velocity x, enemy velocity y def desired_joystick_coords(player_pos, enemy_pos, enemy_vel, bullet_speed, bullet_range): time_to_hit = bullet_range / bullet_speed future_enemy_pos = enemy_pos for _ in range(int(time_to_hit)): future_enemy_pos = update_enemy_position(future_enemy_pos, enemy_vel) enemy_vel = random_velocity() # Update enemy velocity to create unpredictable movements joystick_x = future_enemy_pos[0] - player_pos[0] joystick_y = future_enemy_pos[1] - player_pos[1] return joystick_x, joystick_y def generate_training_data(num_samples): training_data = [] for _ in range(num_samples): bullet_speed = random.uniform(50, 200) bullet_range = random.uniform(100, 500) player_pos = (random.randint(0, GAME_AREA_WIDTH), random.randint(0, GAME_AREA_HEIGHT)) enemy_pos = (random.randint(0, GAME_AREA_WIDTH), random.randint(0, GAME_AREA_HEIGHT)) enemy_vel = random_velocity() step = random.randint(0, 100) desired_coords = desired_joystick_coords(player_pos, enemy_pos, enemy_vel, bullet_speed, bullet_range) input_data = (bullet_speed, bullet_range, player_pos[0], player_pos[1], enemy_pos[0], enemy_pos[1], enemy_vel[0], enemy_vel[1], step) output_data = desired_coords training_data.append((input_data, output_data)) return training_data ''' # Generate and prepare training data num_samples = 10000 raw_training_data = generate_training_data(num_samples) X, y = zip(*raw_training_data) # Train the neural network model.fit(np.array(X), np.array(y), epochs=10000, validation_split=0.2) model.save('my_model3.h5')''' import pygame from tensorflow.keras.models import load_model # Load the trained model model = load_model('my_model3.h5') # Pygame setup pygame.init() screen = pygame.display.set_mode((GAME_AREA_WIDTH, GAME_AREA_HEIGHT)) pygame.display.set_caption('Pygame Visualization') clock = pygame.time.Clock() # Colors WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) # Player and enemy positions player_pos = (GAME_AREA_WIDTH // 2, GAME_AREA_HEIGHT // 2) enemy_pos = (random.randint(0, GAME_AREA_WIDTH), random.randint(0, GAME_AREA_HEIGHT)) enemy_vel = random_velocity() # Bullet properties bullet_speed = 50 bullet_range = 100 running = True while running: screen.fill(WHITE) # Draw player and enemy pygame.draw.circle(screen, RED, player_pos, 10) pygame.draw.circle(screen, GREEN, enemy_pos, 10) # Get joystick coordinates from the neural network input_data = np.array([bullet_speed, bullet_range, player_pos[0], player_pos[1], enemy_pos[0], enemy_pos[1], enemy_vel[0], enemy_vel[1], 0]).reshape(1, -1) joystick_coords = model.predict(input_data)[0] # Draw bullet trajectory pygame.draw.line(screen, (0, 0, 255), player_pos, (player_pos[0] + joystick_coords[0], player_pos[1] + joystick_coords[1]), 2) # Update enemy position enemy_pos = update_enemy_position(enemy_pos, enemy_vel) enemy_vel = random_velocity() # Check for quit event for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.display.flip() clock.tick(60) pygame.quit()
5881a2fc7062ea348f68ee5d441c1a3a
{ "intermediate": 0.28499868512153625, "beginner": 0.26747313141822815, "expert": 0.44752809405326843 }
5,280
Compute the integral ∫10𝑥⎯⎯√𝑑𝑥=2/3 using Monte Carlo integration and 𝑃(𝑥)=1−𝑒−𝑎𝑥 . Find the value 𝑎 that minimizes the variance. Use Python. Print integral and optimal a.
dd3cc7b580c86056d1dbe80db61b44ae
{ "intermediate": 0.30376550555229187, "beginner": 0.17339903116226196, "expert": 0.5228354334831238 }
5,281
Selenium Java code to login to gmail.com
a3573835293910172878905851954cbb
{ "intermediate": 0.5772976279258728, "beginner": 0.1670435070991516, "expert": 0.2556588649749756 }
5,282
hi
c11f8bf5c141b570b6f6c62196820bc2
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,283
hi
7511474a81f89c67d476808af05b8110
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,284
Imagine that you are the founder of a new ambitious startup "Social Network: Friends", which proposes to organize the search for new friends by comparing tastes in the field of cinema. Each user registering on the portal is asked to complete a very simple questionnaire. It consists of N films, for each of which one of two ratings is required: 1 if the user can say that he likes the specified film, and 0 otherwise (if he does not like it or the user has not watched it). After filling out the questionnaire, the user receives a list of the most suitable for him in terms of cinematic compatibility. Your task is to write the friendadviser class, within which to implement the following methods: The fit(self, R) method, which takes as input a matrix R of dimension 𝑀×𝑁 , where 𝑀 is the number of registered users of your social network, and 𝑁 is the number of films in the questionnaire. Matrix element 𝑟𝑖𝑗 is a mark put by the user 𝑖 in the questionnaire opposite the movie 𝑗 . _sim(u1, u2) - a function that calculates the similarity (frequency score based on the PMI metric) of users 𝑢1 and 𝑢2 by their rating vectors. We recommend using a "truncated" version of PMI, which is called score in the lecture. U_idx(u0, alpha) - a function to find a set of registered users (namely, their indexes) whose tastes are similar to the new user 𝑢0 at least as high as alpha. find_friends(u0, how_many) is a function that finds new friends for user 𝑢0 in the number specified by the how_many argument. At the output, we expect to get an array with the indices of such friends. For the sake of convenience, return the indexes in descending order of similarity of interests. import numpy as np class friendadviser(object): def fit(self, R: np.array): self.R = R self.n_users = R.shape[0] self.n_items = R.shape[1] def_sim(self, u1: np.array, u2: np.array): #PMI freq = (np.dot(u1, u2.T) + 1) / (np.sum(u1) + np.sum(u2) - np.dot(u1, u2.T) + 1) pmi = np.log2(freq) - np.log2(np.sum(freq)) score = np.sum(pmi[pmi > 0]) return score def U_idx(self, u0: np.array, alpha: float): sim_scores = [] for i in range(self.n_users): if i != 0: sim_score = self._sim(u0, self.R[i]) if sim_score >= alpha: sim_scores.append((i, sim_score)) sim_scores.sort(key=lambda x: x[1], reverse=True) return [x[0] for x in sim_scores] def find_friends(self, u0: np.array, how_many: int): similar_users = self.U_idx(u0, 0) return np.array(similar_users[:how_many]) Notes: Return the result as np.array. If list is used, validation errors may occur. In this task, it is forbidden to use the pandas and sklearn libraries.
7736204c676c20fb2ef51b7edb3cf839
{ "intermediate": 0.3579883873462677, "beginner": 0.3743467926979065, "expert": 0.2676648199558258 }
5,285
ERROR TypeError: Cannot convert null value to object This error is located at: in Teszt (created by SceneView) in StaticContainer in EnsureSingleNavigator (created by SceneView) in SceneView (created by SceneView) in RCTView (created by View) in View (created by DebugContainer) in DebugContainer (created by MaybeNestedStack) in MaybeNestedStack (created by SceneView) in RCTView (created by View) in View (created by SceneView) in RNSScreen (created by AnimatedComponent) in AnimatedComponent in AnimatedComponentWrapper (created by InnerScreen) in Suspender (created by Freeze) in Suspense (created by Freeze) in Freeze (created by DelayedFreeze) in DelayedFreeze (created by InnerScreen) in InnerScreen (created by Screen) in Screen (created by SceneView) in SceneView (created by NativeStackViewInner) in Suspender (created by Freeze) in Suspense (created by Freeze) in Freeze (created by DelayedFreeze) in DelayedFreeze (created by ScreenStack) in RNSScreenStack (created by ScreenStack) in ScreenStack (created by NativeStackViewInner) in NativeStackViewInner (created by NativeStackView) in RNCSafeAreaProvider (created by SafeAreaProvider) in SafeAreaProvider (created by SafeAreaInsetsContext) in SafeAreaProviderCompat (created by NativeStackView) in NativeStackView (created by NativeStackNavigator) in PreventRemoveProvider (created by NavigationContent) in NavigationContent in Unknown (created by NativeStackNavigator) in NativeStackNavigator (created by Page) in EnsureSingleNavigator in BaseNavigationContainer in ThemeProvider in NavigationContainerInner (created by Page) in Page (created by withDevTools(Page)) in withDevTools(Page) in RCTView (created by View) in View (created by AppContainer) in RCTView (created by View) in View (created by AppContainer) in AppContainer in main(RootComponent), js engine: hermes ERROR TypeError: Cannot convert null value to object const TipusButton = ({tipus, tantargy}) => { const navigation = useNavigation(); const onPressHandler = () => { navigation.navigate('Teszt', {tantargy: tantargy}); } import React, {useState, useEffect} from 'react'; import {View, Text, Button} from 'react-native'; import SQLite from 'react-native-sqlite-storage'; const Teszt = () => { const [people, setPeople] = useState([]); useEffect(() => { // Initialize the SQLite database const db = SQLite.openDatabase( { name: 'myDatabase.db', location: 'default', }, () => console.log('Database opened successfully'), (error) => console.log('Error opening database:', error), ); // Create a table called people with id as primary key, name, and age db.transaction((txn) => { txn.executeSql('CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),age INT'); }); }, []); const addPerson = () => { const db = SQLite.openDatabase({name: 'myDatabase.db', location: 'default'}); // Insert a person into the people table db.transaction((txn) => { txn.executeSql( 'INSERT INTO people (name, age) VALUES (?, ?)', ['John Doe', 30], ); }); }; const getAllPeople = () => { const db = SQLite.openDatabase({name: 'myDatabase.db', location: 'default'}); // Query all data from the people table db.transaction((txn) => { txn.executeSql('SELECT * FROM people', [], (tx, results) => { const rows = results.rows.raw(); setPeople(rows); }); }); }; return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <Text style={{fontSize: 20, marginBottom: 20}}> SQLite Example in React Native </Text> <Button title="Add Person" onPress={addPerson} /> <Button title="Get All People" onPress={getAllPeople} /> <View style={{marginTop: 20}}> {people.map((person, index) => ( <Text key={index}> {person.id}: {person.name}, {person.age} </Text> ))} </View> </View> ); }; export default Teszt; const Stack = createNativeStackNavigator(); export default function Page() { //const router = useRouter(); return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="TantargyValaszto" component={TantargyValaszto} options={{ headerStyle: { backgroundColor: COLORS.primary}, headerLeft: () => ( <Menu /> ), headerTitle: "" }} /> <Stack.Screen name="TipusValaszto" component={TipusValaszto} options={{ headerStyle: { backgroundColor: COLORS.primary}, headerTintColor: 'white', }} /> <Stack.Screen name="TesztValaszto" component={TesztValaszto} options={{ headerStyle: { backgroundColor: COLORS.primary}, headerTintColor: 'white', }} /> <Stack.Screen name="Teszt" component={Teszt} options={{ headerTitle: "", headerShadowVisible: false, }} /> </Stack.Navigator> </NavigationContainer> ); }
49b1df82ce2259031b50d999eb8af734
{ "intermediate": 0.3112517297267914, "beginner": 0.47824475169181824, "expert": 0.210503488779068 }
5,286
write a code in assembler to blink a LED for Atmel mega64
3e55a748ed7276d58817083adaf83c9f
{ "intermediate": 0.23077718913555145, "beginner": 0.4111289978027344, "expert": 0.358093798160553 }
5,287
please debug and answer in markdown: # Import necessary libraries from flask import Flask from flask_ask import Ask, statement, question, session import openai import json # Configure OpenAI API openai.api_key = “#Your OpenAI API Key#” # Initialize Flask and Ask app = Flask(name) ask = Ask(app, ‘/’) # Define the Alexa skill @ask.launch def launch(): return question(“Welcome to ChatGPT. What do you want to ask?”) @ask.intent(“ChatGPTIntent”, mapping={‘Prompt’: ‘Prompt’}) def chat_gpt(prompt): if prompt is None or prompt == “”: return question(“Please provide the message you want to send to ChatGPT.”) return get_chatgpt_response(prompt) def get_chatgpt_response(prompt): # Make a ChatGPT request response = openai.Completion.create( engine=“text-davinci-codex”, prompt=prompt, max_tokens=100, n=1, stop=None, temperature=0.5, ) # Extract the generated response chat_gpt_response = response.choices[0].text.strip() return statement(chat_gpt_response) # Run the Flask app if name == ‘main’: app.run(host=‘0.0.0.0’, port=5000) Replace #Your OpenAI API Key# with your ChatGPT-Plus account API key.
685af46c01fa14a930f966463f3d0758
{ "intermediate": 0.854825496673584, "beginner": 0.06560108065605164, "expert": 0.07957343012094498 }
5,288
hi
ca198a592fa4f1d8a7631f62c2d78c5d
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,289
Please make me a simple game of chess in C++ use basic concept of C++, don’t use concept of object oriented programming. Don’t use any library . You can use arrays and functions.
e14e5f8e1154eda843123c5bdb2845a6
{ "intermediate": 0.32649168372154236, "beginner": 0.5618063807487488, "expert": 0.11170197278261185 }
5,290
hi
67cef8172c0efd797839586a909491ce
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,291
write me a python program to convert the text in the file into voice speech
a8aa1527bd394bf9d4538e4ffa1fcd0f
{ "intermediate": 0.360514760017395, "beginner": 0.1709415763616562, "expert": 0.46854367852211 }
5,292
Write pseudocode for a version of the Fast Fourier Transform (fft) for the case where n is a power of 3, dividing the input vector into three subvectors, solving the problem recursively on them, and combining the solutions of the subproblems. Write the recursive relation for the execution time of the program and solve the recursive relation by the central theorem.
5ddf9d6f1de15fefa72d6cb12ba01da5
{ "intermediate": 0.15317538380622864, "beginner": 0.09436627477407455, "expert": 0.7524582743644714 }
5,293
Given a list of numbers, find and print all its elements with even indices (i.e. A[0], A[2], A[4], ...).
22a286760968268645d499204271f78b
{ "intermediate": 0.42670881748199463, "beginner": 0.1575016975402832, "expert": 0.41578948497772217 }
5,294
hI!Please, does exist a wpf c# component that use data in format mm/aaaa?
549eb4e1fc7e4cd97fe668f5917b99c7
{ "intermediate": 0.6437197327613831, "beginner": 0.13934701681137085, "expert": 0.2169332057237625 }
5,295
How to Customize the format "mm/yyyy" in a datepickertextbox wpf control using c#?
4ee51e7c12ab865136c63aee3648ea83
{ "intermediate": 0.5562246441841125, "beginner": 0.2019248753786087, "expert": 0.24185048043727875 }
5,296
Given a list of numbers, find and print all its elements with even indices (i.e. A[0], A[2], A[4], …).
88be2339086ebdf40944d7f217978623
{ "intermediate": 0.42800167202949524, "beginner": 0.15641775727272034, "expert": 0.4155805706977844 }
5,297
Please make me a simple game of chess in C++ use basic concept of C++, don’t use concept of object oriented programming. Don’t use any library . You can use arrays and functions. Also code the movements of the pieces of king , pawns , bishop , knight etc for my team (white ) and opponent team (red).
2f06540ce455ce5b945e3e5f2229937e
{ "intermediate": 0.37907230854034424, "beginner": 0.4101320803165436, "expert": 0.210795596241951 }
5,298
Make me a script. The script needs to perform the following functions: It needs to solve simple ONE letter captcha. 1. Open a browser, in my case chrome. 2. Access the site "narutoplayers.com.br/np2/?p=login", but DO NOT LOGIN, WAIT UNTIL THE USER LOGINS. 3. Wait until the user is on the "https://www.narutoplayers.com.br/np2/?p=news" page. 4. Once logged in, click on the text "Hunts" to be redirected to another page. 5. Search for a specific field to make a select. 6. Select the text containing the word "Student". 7. Click to search. 8. Read the image that has a text and write the letter that the text contains in a specific field just below the image. 10. Click to search again. 11. The program should have a timer of 300s. 12. The program should repeat all actions, except for opening the browser and logging in. 13. The browser should not be closed in this process. Divide the code into 10 or more parts as needed for the desired solution.
0d64dd5f74fb62747bf467b4f8a9236b
{ "intermediate": 0.36146238446235657, "beginner": 0.3221980035305023, "expert": 0.3163396418094635 }
5,299
write me a google apps script that finds all instances of a variable with a google slides file and replaces it with whatever text is input into a form
387110ba331c5639c8e422358215ceca
{ "intermediate": 0.5337247252464294, "beginner": 0.23855872452259064, "expert": 0.22771655023097992 }
5,300
Make this script. The script needs to perform the following functions: It needs to solve simple ONE letter captcha. 1. Open a browser, in my case chrome. 2. Access the site "narutoplayers.com.br/np2/?p=login", but DO NOT LOGIN, WAIT UNTIL THE USER LOGINS. 3. Wait until the user is on the "https://www.narutoplayers.com.br/np2/?p=news" page. 4. Once logged in, click on the text "Hunts" to be redirected to another page. 5. Search for a specific field to make a select. 6. Select the text containing the word "Student". 7. Click to search. 8. Read the image that has a text and write the letter that the text contains in a specific field just below the image. 10. Click to search again. 11. The program should have a timer of 300s. 12. The program should repeat all actions, except for opening the browser and logging in. 13. The browser should not be closed in this process. Thanks
c0acd310766a3e2f42226ce8f6133442
{ "intermediate": 0.35526564717292786, "beginner": 0.2290404886007309, "expert": 0.41569387912750244 }
5,301
#include <iostream> #include<string> #include <vector> using namespace std; // Define the chess board char board[8][8] = { {'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'}, {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'}, {' ', '.', ' ', '.', ' ', '.', ' ', '.'}, {'.', ' ', '.', ' ', '.', ' ', '.', ' '}, {' ', '.', ' ', '.', ' ', '.', ' ', '.'}, {'.', ' ', '.', ' ', '.', ' ', '.', ' '}, {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}, {'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'} }; bool is_check(char board[8][8], bool white_to_move); bool is_checkmate(char board[8][8], bool white_to_move); bool is_check(char board[8][8], bool white_to_move); // Function to display the chess board void print_board() { cout << endl << " a b c d e f g h" << endl; for (int i = 0; i < 8; i++) { cout << i + 1 << " "; for (int j = 0; j < 8; j++) { cout << board[i][j] << " "; } cout << i + 1 << endl; } cout << " a b c d e f g h" << endl << endl; } // Function to check if a move is valid bool is_valid_move(int from_x, int from_y, int to_x, int to_y) { // Check if the move is within the board limits if (from_x < 0 || from_x > 7 || from_y < 0 || from_y > 7 || to_x < 0 || to_x > 7 || to_y < 0 || to_y > 7) { return false; } // Check if the piece at the starting position is the player's own piece if (board[from_x][from_y] >= 'A' && board[from_x][from_y] <= 'Z') { return false; } // Check if the piece at the starting position is not an empty space if (board[from_x][from_y] == ' ' || board[from_x][from_y] == '.') { return false; } // Check if the piece at the destination position is the player's own piece if (board[to_x][to_y] >= 'a' && board[to_x][to_y] <= 'z') { return false; } // Check if the move is legal for the piece char piece = board[from_x][from_y]; if (piece == 'P') { if (to_x != from_x - 1) { return false; } if (to_y != from_y) { if (to_y != from_y - 1 && to_y != from_y + 1) { return false; } if (board[to_x][to_y] == ' ') { return false; } } else { if (to_x == 0) { // Promotion to Queen board[to_x][to_y] = 'Q'; } } } else if (piece == 'p') { if (to_x != from_x + 1) { return false; } if (to_y != from_y) { if (to_y != from_y - 1 && to_y != from_y + 1) { return false; } if (board[to_x][to_y] == ' ') { return false; } } else { if (to_x == 7) { // Promotion to Queen board[to_x][to_y] = 'q'; } } } else if (piece == 'R' || piece == 'r') { if (from_x != to_x && from_y != to_y) { return false; } if (from_x == to_x) { int start = min(from_y, to_y); int end = max(from_y, to_y); for (int i = start + 1; i < end; i++) { if (board[from_x][i] != ' ' && board[from_x][i] != '.') { return false; } } } else { int start = min(from_x, to_x); int end = max(from_x, to_x); for (int i = start + 1; i < end; i++) { if (board[i][from_y] != ' ' && board[i][from_y] != '.') { return false; } } } } else if (piece == 'N' || piece == 'n') { if ((to_x == from_x - 1 && to_y == from_y - 2) || (to_x == from_x - 2 && to_y == from_y - 1) || (to_x == from_x - 2 && to_y == from_y + 1) || (to_x == from_x - 1 && to_y == from_y + 2) || (to_x == from_x + 1 && to_y == from_y + 2) || (to_x == from_x + 2 && to_y == from_y + 1) || (to_x == from_x + 2 && to_y == from_y - 1) || (to_x == from_x + 1 && to_y == from_y - 2)) { // Valid move } else { return false; } } else if (piece == 'B' || piece == 'b') { if (abs(to_x - from_x) != abs(to_y - from_y)) { return false; } int x_dir = (to_x > from_x) ? 1 : -1; int y_dir = (to_y > from_y) ? 1 : -1; for (int i = from_x + x_dir, j = from_y + y_dir; i != to_x; i += x_dir, j += y_dir) { if (board[i][j] != ' ' && board[i][j] != '.') { return false; } } } else if (piece == 'Q' || piece == 'q') { if (from_x == to_x || from_y == to_y) { int start = min(from_y, to_y); int end = max(from_y, to_y); if (from_x == to_x) { for (int i = start + 1; i < end; i++) { if (board[from_x][i] != ' ' && board[from_x][i] != '.') { return false; } } } else { for (int i = start + 1; i < end; i++) { if (board[i][from_y] != ' ' && board[i][from_y] != '.') { return false; } } } } else if (abs(to_x - from_x) == abs(to_y - from_y)) { int x_dir = (to_x > from_x) ? 1 : -1; int y_dir = (to_y > from_y) ? 1 : -1; for (int i = from_x + x_dir, j = from_y + y_dir; i != to_x; i += x_dir, j += y_dir) { if (board[i][j] != ' ' && board[i][j] != '.') { return false; } } } else { return false; } } else if (piece == 'K' || piece == 'k') { if (abs(to_x - from_x) <= 1 && abs(to_y - from_y) <= 1) { // valid move for king } else { return false; } } else { return false; } return true; } vector<string> getPossibleMoves(char board[][8], bool white_to_move) { vector<string> moves; char piece; string move; // Iterate through each square on the board for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { // Check if the piece on this square belongs to the current player piece = board[i][j]; if ((white_to_move && isupper(piece)) || (!white_to_move && islower(piece))) { // Check all possible moves for this piece and add them to the vector for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { move = ""; if (is_valid_move(i, j, x, y)) { move += 'a' + j; move += '8' - i; move += 'a' + y; move += '8' - x; moves.push_back(move); } } } } } } return moves; } bool is_checkmate(char board[8][8], bool white_to_move) { vector<pair<int, int>> moves = getPossibleMoves(board, white_to_move); for (auto move : moves) { char copy[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { copy[i][j] = board[i][j]; } } make_move(copy, move.first / 10, move.first % 10, move.second / 10, move.second % 10); if (!is_check(copy, white_to_move)) { return false; } } return true; } bool is_stalemate(char board[8][8], bool white_to_move) { vector<pair<int, int>> moves = get_possible_moves(board, white_to_move); for (auto move : moves) { char copy[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { copy[i][j] = board[i][j]; } } make_move(copy, move.first / 10, move.first % 10, move.second / 10, move.second % 10); if (!is_check(copy, white_to_move)) { return false; } } return true; } bool is_check(char board[8][8], bool white_to_move) { int king_x, king_y; char king = (white_to_move) ? 'K' : 'k'; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board[i][j] == king) { king_x = i; king_y = j; break; } } } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if ((isupper(board[i][j]) == white_to_move)) { if (is_valid_move(i, j, i, j)) { return true; } } } } return false; } bool is_gameover(char board[8][8], bool white_to_move) { if (is_checkmate(board, white_to_move) || is_stalemate(board, white_to_move)) { return true; } return false; } int main() { char board[8][8] = { {'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'}, {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}, {' ', '.', ' ', '.', ' ', '.', 'p', ' '}, {' ', '.', ' ', '.', ' ', '.', ' ', ' '}, {' ', '.', ' ', '.', ' ', '.', ' ', ' '}, {' ', '.', ' ', '.', ' ', '.', ' ', ' '}, {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'}, {'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'} }; bool white_to_move = true; while (!is_gameover(board, white_to_move)) { print_board(); cout << "It is " << ((white_to_move) ? "white" : "black") << "'s turn" << endl; bool valid_move = false; while (!valid_move) { string move; cout << "Enter your move: "; getline(cin, move); if (move.size() == 4) { int from_x = move[0] - 'a', from_y = move[1] - '1', to_x = move[2] - 'a', to_y = move[3] - '1'; if (is_valid_move(from_x, from_y, to_x, to_y) && ((isupper(board[from_x][from_y]) == white_to_move))) { make_move(board, from_x, from_y, to_x, to_y); valid_move = true; } } if (!valid_move) { cout << "Invalid move. Try again." << endl; } } white_to_move = !white_to_move; } print_board(); if (is_checkmate(board, white_to_move)) { cout << ((white_to_move) ? "Black" : "White") << " wins by checkmate!" << endl; } else if (is_stalemate(board, white_to_move)) { cout << "The game is a draw by stalemate." << endl; } return 0; } This is a code for a chess game , it has some unknown error, can you correct it and give me the corrected code.
13a9adbc00dbaa34e4219c4a70c8275e
{ "intermediate": 0.29520177841186523, "beginner": 0.5134644508361816, "expert": 0.19133375585079193 }
5,302
Write a version of the Fast Fourier Transform (fft) for the case where n is a power of 3, dividing the input vector into three subvectors, solving the problem recursively on them, and combining the solutions of the subproblems. Write the recursive relation for the execution time of the program and solve the recursive relation by the central theorem.
7d98e7cf7007dec007fe1669f175c807
{ "intermediate": 0.15003353357315063, "beginner": 0.0730472058057785, "expert": 0.7769193053245544 }
5,303
In vba , only if there is an error with this line of code, ActiveSheet.Range(selectedCellAddress).Select , I want ignore the error and select the first empty cell in column B
ad191d8e309d3b55173e1ffb1a68e8cb
{ "intermediate": 0.4891013503074646, "beginner": 0.2149459421634674, "expert": 0.2959526777267456 }
5,304
Make this script. The script needs to perform the following functions: It needs to solve simple ONE letter captcha. 1. Open a browser, in my case chrome. 2. Access the site “narutoplayers.com.br/np2/?p=login”, but DO NOT LOGIN, WAIT UNTIL THE USER LOGINS. 3. Wait until the user is on the “https://www.narutoplayers.com.br/np2/?p=news” page. 4. Once logged in, click on the text “Hunts” to be redirected to another page. 5. Search for a specific field to make a select. 6. Select the text containing the word “Student”. 7. Click to search. 8. Read the image that has a text and write the letter that the text contains in a specific field just below the image(THE CAPTCHA IS IN THE CAPTCHA.PHP). 10. Click to search again. 11. The program should have a timer of 300s. 12. The program should repeat all actions, except for opening the browser. 13. The browser should not be closed in this process. Thanks
b829620b7568f432360306e8206e15fa
{ "intermediate": 0.33348867297172546, "beginner": 0.25963908433914185, "expert": 0.4068722724914551 }
5,305
There is a problem with this code, if the problem is that the db file could not be found, how can I fix it? ERROR TypeError: Cannot convert null value to object This error is located at: in Teszt (created by SceneView) in StaticContainer in EnsureSingleNavigator (created by SceneView) in SceneView (created by SceneView) in RCTView (created by View) in View (created by DebugContainer) in DebugContainer (created by MaybeNestedStack) in MaybeNestedStack (created by SceneView) in RCTView (created by View) in View (created by SceneView) in RNSScreen (created by AnimatedComponent) in AnimatedComponent in AnimatedComponentWrapper (created by InnerScreen) in Suspender (created by Freeze) in Suspense (created by Freeze) in Freeze (created by DelayedFreeze) in DelayedFreeze (created by InnerScreen) in InnerScreen (created by Screen) in Screen (created by SceneView) in SceneView (created by NativeStackViewInner) in Suspender (created by Freeze) in Suspense (created by Freeze) in Freeze (created by DelayedFreeze) in DelayedFreeze (created by ScreenStack) in RNSScreenStack (created by ScreenStack) in ScreenStack (created by NativeStackViewInner) in NativeStackViewInner (created by NativeStackView) in RNCSafeAreaProvider (created by SafeAreaProvider) in SafeAreaProvider (created by SafeAreaInsetsContext) in SafeAreaProviderCompat (created by NativeStackView) in NativeStackView (created by NativeStackNavigator) in PreventRemoveProvider (created by NavigationContent) in NavigationContent in Unknown (created by NativeStackNavigator) in NativeStackNavigator (created by Page) in EnsureSingleNavigator in BaseNavigationContainer in ThemeProvider in NavigationContainerInner (created by Page) in Page (created by withDevTools(Page)) in withDevTools(Page) in RCTView (created by View) in View (created by AppContainer) in RCTView (created by View) in View (created by AppContainer) in AppContainer in main(RootComponent), js engine: hermes const Teszt = () => { const [people, setPeople] = useState([]); const db = SQLite.openDatabase({name: 'myDatabase.db', location: 'default'}); useEffect(() => { // Create a table called people with id as primary key, name, and age db.transaction((txn) => { txn.executeSql( "CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20), age INT)", ); }); }, []);
59bc36c7b78b45debc090ffb7aa84545
{ "intermediate": 0.29828447103500366, "beginner": 0.5719805955886841, "expert": 0.12973491847515106 }
5,306
#include <iostream> #include<string> #include <vector> using namespace std; // Define the chess board char board[8][8] = { {'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'}, {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'}, {' ', '.', ' ', '.', ' ', '.', ' ', '.'}, {'.', ' ', '.', ' ', '.', ' ', '.', ' '}, {' ', '.', ' ', '.', ' ', '.', ' ', '.'}, {'.', ' ', '.', ' ', '.', ' ', '.', ' '}, {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}, {'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'} }; bool is_check(char board[8][8], bool white_to_move); bool is_checkmate(char board[8][8], bool white_to_move); bool is_check(char board[8][8], bool white_to_move); // Function to display the chess board void print_board() { cout << endl << " a b c d e f g h" << endl; for (int i = 0; i < 8; i++) { cout << i + 1 << " "; for (int j = 0; j < 8; j++) { cout << board[i][j] << " "; } cout << i + 1 << endl; } cout << " a b c d e f g h" << endl << endl; } // Function to check if a move is valid bool is_valid_move(int from_x, int from_y, int to_x, int to_y) { // Check if the move is within the board limits if (from_x < 0 || from_x > 7 || from_y < 0 || from_y > 7 || to_x < 0 || to_x > 7 || to_y < 0 || to_y > 7) { return false; } // Check if the piece at the starting position is the player's own piece if (board[from_x][from_y] >= 'A' && board[from_x][from_y] <= 'Z') { return false; } // Check if the piece at the starting position is not an empty space if (board[from_x][from_y] == ' ' || board[from_x][from_y] == '.') { return false; } // Check if the piece at the destination position is the player's own piece if (board[to_x][to_y] >= 'a' && board[to_x][to_y] <= 'z') { return false; } // Check if the move is legal for the piece char piece = board[from_x][from_y]; if (piece == 'P') { if (to_x != from_x - 1) { return false; } if (to_y != from_y) { if (to_y != from_y - 1 && to_y != from_y + 1) { return false; } if (board[to_x][to_y] == ' ') { return false; } } else { if (to_x == 0) { // Promotion to Queen board[to_x][to_y] = 'Q'; } } } else if (piece == 'p') { if (to_x != from_x + 1) { return false; } if (to_y != from_y) { if (to_y != from_y - 1 && to_y != from_y + 1) { return false; } if (board[to_x][to_y] == ' ') { return false; } } else { if (to_x == 7) { // Promotion to Queen board[to_x][to_y] = 'q'; } } } else if (piece == 'R' || piece == 'r') { if (from_x != to_x && from_y != to_y) { return false; } if (from_x == to_x) { int start = min(from_y, to_y); int end = max(from_y, to_y); for (int i = start + 1; i < end; i++) { if (board[from_x][i] != ' ' && board[from_x][i] != '.') { return false; } } } else { int start = min(from_x, to_x); int end = max(from_x, to_x); for (int i = start + 1; i < end; i++) { if (board[i][from_y] != ' ' && board[i][from_y] != '.') { return false; } } } } else if (piece == 'N' || piece == 'n') { if ((to_x == from_x - 1 && to_y == from_y - 2) || (to_x == from_x - 2 && to_y == from_y - 1) || (to_x == from_x - 2 && to_y == from_y + 1) || (to_x == from_x - 1 && to_y == from_y + 2) || (to_x == from_x + 1 && to_y == from_y + 2) || (to_x == from_x + 2 && to_y == from_y + 1) || (to_x == from_x + 2 && to_y == from_y - 1) || (to_x == from_x + 1 && to_y == from_y - 2)) { // Valid move } else { return false; } } else if (piece == 'B' || piece == 'b') { if (abs(to_x - from_x) != abs(to_y - from_y)) { return false; } int x_dir = (to_x > from_x) ? 1 : -1; int y_dir = (to_y > from_y) ? 1 : -1; for (int i = from_x + x_dir, j = from_y + y_dir; i != to_x; i += x_dir, j += y_dir) { if (board[i][j] != ' ' && board[i][j] != '.') { return false; } } } else if (piece == 'Q' || piece == 'q') { if (from_x == to_x || from_y == to_y) { int start = min(from_y, to_y); int end = max(from_y, to_y); if (from_x == to_x) { for (int i = start + 1; i < end; i++) { if (board[from_x][i] != ' ' && board[from_x][i] != '.') { return false; } } } else { for (int i = start + 1; i < end; i++) { if (board[i][from_y] != ' ' && board[i][from_y] != '.') { return false; } } } } else if (abs(to_x - from_x) == abs(to_y - from_y)) { int x_dir = (to_x > from_x) ? 1 : -1; int y_dir = (to_y > from_y) ? 1 : -1; for (int i = from_x + x_dir, j = from_y + y_dir; i != to_x; i += x_dir, j += y_dir) { if (board[i][j] != ' ' && board[i][j] != '.') { return false; } } } else { return false; } } else if (piece == 'K' || piece == 'k') { if (abs(to_x - from_x) <= 1 && abs(to_y - from_y) <= 1) { // valid move for king } else { return false; } } else { return false; } return true; } vector<string> getPossibleMoves(char board[][8], bool white_to_move) { vector<string> moves; char piece; string move; // Iterate through each square on the board for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { // Check if the piece on this square belongs to the current player piece = board[i][j]; if ((white_to_move && isupper(piece)) || (!white_to_move && islower(piece))) { // Check all possible moves for this piece and add them to the vector for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { move = ""; if (is_valid_move(i, j, x, y)) { move += 'a' + j; move += '8' - i; move += 'a' + y; move += '8' - x; moves.push_back(move); } } } } } } return moves; } bool is_checkmate(char board[8][8], bool white_to_move) { vector<pair<int, int>> moves = getPossibleMoves(board, white_to_move); for (auto move : moves) { char copy[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { copy[i][j] = board[i][j]; } } make_move(copy, move.first / 10, move.first % 10, move.second / 10, move.second % 10); if (!is_check(copy, white_to_move)) { return false; } } return true; } bool is_stalemate(char board[8][8], bool white_to_move) { vector<pair<int, int>> moves = get_possible_moves(board, white_to_move); for (auto move : moves) { char copy[8][8]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { copy[i][j] = board[i][j]; } } make_move(copy, move.first / 10, move.first % 10, move.second / 10, move.second % 10); if (!is_check(copy, white_to_move)) { return false; } } return true; } bool is_check(char board[8][8], bool white_to_move) { int king_x, king_y; char king = (white_to_move) ? 'K' : 'k'; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if (board[i][j] == king) { king_x = i; king_y = j; break; } } } for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { if ((isupper(board[i][j]) == white_to_move)) { if (is_valid_move(i, j, i, j)) { return true; } } } } return false; } bool is_gameover(char board[8][8], bool white_to_move) { if (is_checkmate(board, white_to_move) || is_stalemate(board, white_to_move)) { return true; } return false; } int main() { char board[8][8] = { {'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'}, {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'}, {' ', '.', ' ', '.', ' ', '.', 'p', ' '}, {' ', '.', ' ', '.', ' ', '.', ' ', ' '}, {' ', '.', ' ', '.', ' ', '.', ' ', ' '}, {' ', '.', ' ', '.', ' ', '.', ' ', ' '}, {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'}, {'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'} }; bool white_to_move = true; while (!is_gameover(board, white_to_move)) { print_board(); cout << "It is " << ((white_to_move) ? "white" : "black") << "'s turn" << endl; bool valid_move = false; while (!valid_move) { string move; cout << "Enter your move: "; getline(cin, move); if (move.size() == 4) { int from_x = move[0] - 'a', from_y = move[1] - '1', to_x = move[2] - 'a', to_y = move[3] - '1'; if (is_valid_move(from_x, from_y, to_x, to_y) && ((isupper(board[from_x][from_y]) == white_to_move))) { make_move(board, from_x, from_y, to_x, to_y); valid_move = true; } } if (!valid_move) { cout << "Invalid move. Try again." << endl; } } white_to_move = !white_to_move; } print_board(); if (is_checkmate(board, white_to_move)) { cout << ((white_to_move) ? "Black" : "White") << " wins by checkmate!" << endl; } else if (is_stalemate(board, white_to_move)) { cout << "The game is a draw by stalemate." << endl; } return 0; } This is my code for a chess game. As you can see it uses the library of vector which is object oriented programming. Can you remove this vector and all the concepts of object oriented programming in the code and provide me with a new code.
a94a23677b1088f2b988058387f45dd1
{ "intermediate": 0.29520177841186523, "beginner": 0.5134644508361816, "expert": 0.19133375585079193 }
5,307
In some applications we want to find minimum spanning trees with specific properties. The next problem is an example. Input: undirected graph G = (V, E), edge weights we, and a subset U of nodes. Output: the minimum spanning tree in which the nodes of the set U are leaves. (The tree may have leaves from nodes of the set V - U as well). Write pseudocode for an algorithm for the above problem which runs in time O( |E| log|V| ). How can we find a maximum spanning tree instead of minimum spanning tree?
6d0a5e0f8ea8ee2ecb681f2a6d651273
{ "intermediate": 0.1412784308195114, "beginner": 0.23536960780620575, "expert": 0.6233519315719604 }
5,308
The purpose of this program is to retrieve, format, and print the shell environmental variables for the user running the program. The program will: only execute commands if execution occurred as a result of this program name being called and not when imported when imported, functions will only execute when called create a function called main that will call the other functions to perform the required actions create a function called retrieve_env_variables retrieve the environmental variables with associated values return the variable name with associated value create a function called format_env_variables formats the key/value pairs environmental variable name left justified within a 30 character string value formatting does not change create a function called print_env_variables prints the formatted environmental variable followed directly by a colon and a space followed directly by the value that the environmental variable holds end the line with one new line
70ef8d67be23f6608000aa57e119e649
{ "intermediate": 0.33096566796302795, "beginner": 0.31660592555999756, "expert": 0.3524283170700073 }
5,309
Write a user-defined MATLAB function that calculates the determinant of a square (𝑛 x 𝑛) matrix, where 𝑛 can be 2, 3, or 4. For function name and arguments, use D = Determinant(A). The input argument 𝐴 is the matrix whose determinant is calculated. The function Determinant should first check if the matrix is square. If it is not, the output 𝐷 should be the message “The matrix must be square.”
27ee90b18ba091d095e8c120101c6e76
{ "intermediate": 0.33826300501823425, "beginner": 0.288085013628006, "expert": 0.37365198135375977 }
5,310
я передал сообщение из одного приложение в другое твоя задача вывести это приложение на экран второго приложения , которое приняло это сообщение в виде toast , вот код :package com.example.myapp_2.UI.view.fragments; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import com.example.myapp_2.List_1.Product; import com.example.myapp_2.List_1.ProductAdapter; import com.example.myapp_2.R; import com.example.myapp_2.UI.view.adapters.SliderAdapter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; public class FirstFragment extends Fragment implements View.OnClickListener ,RatingBar.OnRatingBarChangeListener { private Button mShareButton; private RecyclerView recyclerView; private ProductAdapter productAdapter; private RatingBar ratingBar; private TextView ratingAverageTextView; private ViewPager viewPager; private int[] imageUrls = {R.drawable.first_1, R.drawable.first_2, R.drawable.first_3, R.drawable.first_4, R.drawable.first_5}; private List<Product> products = getProducts(); private static final String MY_PREFS_NAME = "MyPrefs"; private float rating1 = 0.0f; private float rating2 = 0.0f; private float rating3 = 0.0f; private float rating4 = 0.0f; private float rating5 = 0.0f; private float rating6 = 0.0f; private float rating7 = 0.0f; private float rating8 = 0.0f; private float rating9 = 0.0f; private float rating10 = 0.0f; EditText mEditText; private static final String TAG = "FirstFragment"; private long noteId; public FirstFragment(long noteId) { this.noteId = noteId; } public FirstFragment() { } // private ViewPager viewPager; // EditText mEditText; public void createFile(String fileName, String fileContent) {//Реализовать создание текстового файла в app-specific storage. try { FileOutputStream fos = requireContext().openFileOutput(fileName, Context.MODE_PRIVATE); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos); outputStreamWriter.write(fileContent); outputStreamWriter.close(); String filePath = new File(requireContext().getFilesDir(), fileName).getAbsolutePath(); // получаем абсолютный путь Log.d(TAG, "File " + fileName + " created successfully at path:" + filePath); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "Failed to create file " + fileName + ": " + e.getMessage()); } } public void createTextFileInDirectory(String fileName) { File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File textFile = new File(directory, fileName); try { FileOutputStream fileOutputStream = new FileOutputStream(textFile); fileOutputStream.write("Hello World".getBytes()); fileOutputStream.close(); Toast.makeText(getActivity(), "File created at: " + textFile.getAbsolutePath(), Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getActivity(), "Error creating file", Toast.LENGTH_SHORT).show(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_first, container, false); mShareButton = v.findViewById(R.id.btn_3); mShareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { shareText(); } }); recyclerView = v.findViewById(R.id.recycler_view_products); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); productAdapter = new ProductAdapter(getContext(), products); recyclerView.setAdapter(productAdapter); productAdapter.setOnAddToCartClickListener(new ProductAdapter.OnAddToCartClickListener() { @Override public void onAddToCartClick(Product product) { Toast.makeText(getActivity(),"Товар успешно добавлен!",Toast.LENGTH_SHORT).show(); } }); viewPager = v.findViewById(R.id.view_pager); SliderAdapter adapter = new SliderAdapter(getActivity(), imageUrls); viewPager.setAdapter(adapter); // Получаем оценки из SharedPreferences SharedPreferences prefs = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); rating1 = prefs.getFloat("rating1", 0.0f); rating2 = prefs.getFloat("rating2", 0.0f); rating3 = prefs.getFloat("rating3", 0.0f); rating4 = prefs.getFloat("rating4", 0.0f); rating5 = prefs.getFloat("rating5", 0.0f); rating6 = prefs.getFloat("rating6", 0.0f); rating7 = prefs.getFloat("rating7", 0.0f); rating8 = prefs.getFloat("rating8", 0.0f); rating9 = prefs.getFloat("rating9", 0.0f); rating10 = prefs.getFloat("rating10", 0.0f); // Устанавливаем оценки в соответствующие товары products.get(0).setRating(rating1); products.get(1).setRating(rating2); products.get(2).setRating(rating3); products.get(3).setRating(rating4); products.get(4).setRating(rating5); products.get(5).setRating(rating6); products.get(6).setRating(rating7); products.get(7).setRating(rating8); products.get(8).setRating(rating9); products.get(9).setRating(rating10); products.get(0).setPrice(300.99); products.get(1).setPrice(120.99); products.get(2).setPrice(140.99); products.get(3).setPrice(420.99); products.get(4).setPrice(380.99); products.get(5).setPrice(105.99); products.get(6).setPrice(200.99); products.get(7).setPrice(150.99); products.get(8).setPrice(190.99); products.get(9).setPrice(299.99); final Handler handler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { int currentItem = viewPager.getCurrentItem(); int totalItems = viewPager.getAdapter().getCount(); int nextItem = currentItem == totalItems - 1 ? 0 : currentItem + 1; viewPager.setCurrentItem(nextItem); handler.postDelayed(this, 3000); } }; handler.postDelayed(runnable, 3000); return v; } private List<Product> getProducts() { List<Product> products = new ArrayList<>(); Product product1 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f); products.add(product1); Product product2 = new Product("Product 2", "Description 2", R.drawable.food_1_1, 0.0f); products.add(product2); Product product3 = new Product("Product 3", "Description 3", R.drawable.food_1_4, 0.0f); products.add(product3); Product product4 = new Product("Product 4", "Description 4", R.drawable.food_1_1, 0.0f); products.add(product4); Product product5 = new Product("Product 5", "Description 5", R.drawable.food_1_1, 0.0f); products.add(product5); Product product6 = new Product("Product 6", "Description 6", R.drawable.food_1_1,0.0f); products.add(product6); Product product7 = new Product("Product 7", "Description 7", R.drawable.food_3_2,0.0f); products.add(product7); Product product8 = new Product("Product 8", "Description 8", R.drawable.food_3_3,0.0f); products.add(product8); Product product9 = new Product("Product 9", "Description 9", R.drawable.food_1_1,0.0f); products.add(product9); Product product10 = new Product("Product 10", "Description 10", R.drawable.food_1_1,0.0f); products.add(product10); return products; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {//После того как отрисовались лементы super.onViewCreated(view,savedInstanceState); initView(view); } private void initView(View view){ Button btnClick = (Button) view.findViewById(R.id.btn_2); Button btnClick2 = (Button) view.findViewById(R.id.btn_3); btnClick.setOnClickListener(this); btnClick2.setOnClickListener(this); Button btnClick3 = (Button) view.findViewById(R.id.button); btnClick3.setOnClickListener(this); Button btnClick4 = (Button) view.findViewById(R.id.change_btn); btnClick4.setOnClickListener(this); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = this.getArguments(); if (bundle != null) { int myInt = bundle.getInt("hello world", 123); String strI = Integer.toString(myInt); Toast.makeText(getActivity(),strI,Toast.LENGTH_SHORT).show(); } } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); } @Override public void onPause(){ super.onPause(); // Сохраняем оценки в SharedPreferences SharedPreferences.Editor editor = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit(); editor.putFloat("rating1", products.get(0).getRating()); editor.putFloat("rating2", products.get(1).getRating()); editor.putFloat("rating3", products.get(2).getRating()); editor.putFloat("rating4", products.get(3).getRating()); editor.putFloat("rating5", products.get(4).getRating()); editor.putFloat("rating6", products.get(5).getRating()); editor.putFloat("rating7", products.get(6).getRating()); editor.putFloat("rating8", products.get(7).getRating()); editor.putFloat("rating9", products.get(8).getRating()); editor.putFloat("rating10", products.get(9).getRating()); editor.apply(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { super.onDestroy(); } private void changeFragment(){ getFragmentManager().beginTransaction().replace(R.id.nav_container,new SecondFragment()).addToBackStack(null).commit(); } private void changeFragment2(){ getFragmentManager().beginTransaction().replace(R.id.nav_container,new ThirdFragment()).addToBackStack(null).commit(); } private void changeFragment3(){ getFragmentManager().beginTransaction().replace(R.id.nav_container,new ListFragment()).addToBackStack(null).commit(); } private void changeFragment4(){ getFragmentManager().beginTransaction().replace(R.id.nav_container,new RecycleFragment()).addToBackStack(null).commit(); } Context context; @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_2: changeFragment4(); break; case R.id.btn_3: shareText(); //createFile("test4.txt", "Мой финальный текстовый документ"); //createTextFileInDirectory("test1.txt"); break; case R.id.button: changeFragment3(); break; case R.id.change_btn: changeFragment4(); break; } } @Override public void onRatingChanged(RatingBar ratingBar, float v, boolean b) { } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); // Сохраняем оценки в Bundle outState.putFloat("rating1", rating1); outState.putFloat("rating2", rating2); outState.putFloat("rating3", rating3); outState.putFloat("rating4", rating4); outState.putFloat("rating5", rating5); outState.putFloat("rating6", rating6); outState.putFloat("rating7", rating7); outState.putFloat("rating8", rating8); outState.putFloat("rating9", rating9); outState.putFloat("rating10", rating10); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { // Восстанавливаем оценки из Bundle rating1 = savedInstanceState.getFloat("rating1"); rating2 = savedInstanceState.getFloat("rating2"); rating3 = savedInstanceState.getFloat("rating3"); rating4 = savedInstanceState.getFloat("rating4"); rating5 = savedInstanceState.getFloat("rating5"); rating6 = savedInstanceState.getFloat("rating6"); rating7 = savedInstanceState.getFloat("rating7"); rating8 = savedInstanceState.getFloat("rating8"); rating9 = savedInstanceState.getFloat("rating9"); rating10 = savedInstanceState.getFloat("rating10"); // Устанавливаем оценки в соответствующие товары products.get(0).setRating(rating1); products.get(1).setRating(rating2); products.get(2).setRating(rating3); products.get(3).setRating(rating4); products.get(4).setRating(rating5); products.get(5).setRating(rating6); products.get(6).setRating(rating7); products.get(7).setRating(rating8); products.get(8).setRating(rating9); products.get(9).setRating(rating10); } } private void shareText() { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "Hello, world!"); sendIntent.setType("text/plain"); Intent shareIntent = Intent.createChooser(sendIntent, null); startActivity(shareIntent); } // Метод, который создает список товаров }
a5774f43641e550ea4a03801b816a7ba
{ "intermediate": 0.3363786041736603, "beginner": 0.44724395871162415, "expert": 0.21637745201587677 }
5,311
Donne moi la réponse de comment intégrer le forEach dans : let imgArrows = document.getElementById('arrow'); let showAnswer = document.getElementById("answer"); imgArrows.addEventListener("click",()=>{ if (showAnswer.style.display == 'none') { showAnswer.style.display = 'block'; imgArrows.style.rotate = "-180deg"; } else { showAnswer.style.display = 'none'; imgArrows.style.rotate = "-360deg"; } })
9ceaad173d5d4c573621edc28f5357c5
{ "intermediate": 0.39056819677352905, "beginner": 0.3758069574832916, "expert": 0.2336249053478241 }
5,312
Analisis sentimen data berita berbahasa indonesia berjumlah 16669 baris dengan kode CNN-LSTM berikut masih menghasilkan hasil yang jelek. Tolong perbaiki kode agar akurasi naik dan tidak stuck di angka akurasi 0.51 ! import numpy as np import pandas as pd import pickle from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.metrics import confusion_matrix, classification_report, accuracy_score from keras.preprocessing.text import Tokenizer from keras.utils import pad_sequences from keras.models import Sequential from keras.layers import Embedding, Conv1D, MaxPooling1D, LSTM, Dense from keras.callbacks import EarlyStopping, ModelCheckpoint import gensim from gensim.models import Word2Vec # Membaca dataset data_list = pickle.load(open('pre_processed_beritaFIX_joined.pkl', 'rb')) data = pd.DataFrame(data_list, columns=['judul', 'isi', 'pre_processed', 'Label']) data['Isi Berita'] = data['pre_processed'] # Konversi label ke angka encoder = LabelEncoder() data['label_encoded'] = encoder.fit_transform(data['Label']) # Memisahkan data menjadi data latih dan data uji X_train, X_test, y_train, y_test = train_test_split(data['Isi Berita'], data['label_encoded'], test_size=0.25, random_state=42) # Tokenisasi teks dan padding max_words = 10000 sequence_length = 500 tokenizer = Tokenizer(num_words=max_words) tokenizer.fit_on_texts(data['Isi Berita']) X_train_seq = tokenizer.texts_to_sequences(X_train) X_test_seq = tokenizer.texts_to_sequences(X_test) X_train_padded = pad_sequences(X_train_seq, maxlen=sequence_length, padding='post', truncating='post') X_test_padded = pad_sequences(X_test_seq, maxlen=sequence_length, padding='post', truncating='post') # Membuka model word2vec path = 'idwiki_word2vec_300.model' id_w2v = gensim.models.word2vec.Word2Vec.load(path) wv = id_w2v.wv # Membuat embeding matrix embedding_dim = id_w2v.vector_size embedding_matrix = np.zeros((max_words, embedding_dim)) for word, i in tokenizer.word_index.items(): if i < max_words: try: embedding_vector = wv[word] embedding_matrix[i] = embedding_vector except KeyError: pass # Membangun model CNN-LSTM dengan pre-trained Word2Vec num_filters = 64 lstm_units = 64 model = Sequential([ Embedding(input_dim=max_words, output_dim=embedding_dim, input_length=sequence_length, weights=[embedding_matrix], # Menggunakan pre-trained Word2Vec trainable=False), Conv1D(num_filters, 5, activation='relu', kernel_regularizer=l2(l2_coeff)), MaxPooling1D(pool_size=4), LSTM(lstm_units, return_sequences=False, kernel_regularizer=l2(l2_coeff), recurrent_regularizer=l2(0.01)), # Menambahkan regularisasi L2 Dropout(0.5), # Menambahkan Dropout Dense(3, activation='softmax', kernel_regularizer=l2(l2_coeff)) # Menambahkan regularisasi L2 ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Melatih model dengan early stopping dan model checkpoint checkpoint = ModelCheckpoint('model_cnn_lstm.h5', save_best_only=True, monitor='val_accuracy', mode='max') early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1) history = model.fit(X_train_padded, y_train, validation_split=0.2, epochs=50, batch_size=128) # Evaluasi model pada data uji y_pred = np.argmax(model.predict(X_test_padded), axis=-1) # Hitung akurasi accuracy = accuracy_score(y_test, y_pred) print('Akurasi: {:.2f}%'.format(accuracy * 100)) # Print classification report print(classification_report(y_test, y_pred, target_names=encoder.classes_)) Hasilnya adalah sebagai berikut Epoch 1/100 79/79 [==============================] - 18s 204ms/step - loss: 1.8177 - accuracy: 0.5304 - val_loss: 1.2715 - val_accuracy: 0.5186 Epoch 2/100 79/79 [==============================] - 16s 207ms/step - loss: 1.1284 - accuracy: 0.5312 - val_loss: 1.0541 - val_accuracy: 0.5174 Epoch 3/100 79/79 [==============================] - 16s 202ms/step - loss: 1.0284 - accuracy: 0.5320 - val_loss: 1.0240 - val_accuracy: 0.5174 Epoch 4/100 79/79 [==============================] - 16s 205ms/step - loss: 1.0137 - accuracy: 0.5317 - val_loss: 1.0142 - val_accuracy: 0.5174 Epoch 5/100 79/79 [==============================] - 16s 203ms/step - loss: 1.0067 - accuracy: 0.5339 - val_loss: 1.0117 - val_accuracy: 0.5174 Epoch 6/100 79/79 [==============================] - 16s 197ms/step - loss: 1.0029 - accuracy: 0.5343 - val_loss: 1.0111 - val_accuracy: 0.5174 Epoch 7/100 79/79 [==============================] - 16s 203ms/step - loss: 1.0015 - accuracy: 0.5351 - val_loss: 1.0083 - val_accuracy: 0.5186 Epoch 8/100 79/79 [==============================] - 16s 202ms/step - loss: 1.0003 - accuracy: 0.5348 - val_loss: 1.0079 - val_accuracy: 0.5182 Epoch 9/100 79/79 [==============================] - 16s 205ms/step - loss: 0.9982 - accuracy: 0.5351 - val_loss: 1.0071 - val_accuracy: 0.5174 Epoch 10/100 79/79 [==============================] - 16s 207ms/step - loss: 0.9970 - accuracy: 0.5358 - val_loss: 1.0071 - val_accuracy: 0.5174 Epoch 11/100 79/79 [==============================] - 16s 199ms/step - loss: 0.9974 - accuracy: 0.5350 - val_loss: 1.0068 - val_accuracy: 0.5186 Epoch 12/100 79/79 [==============================] - 16s 204ms/step - loss: 0.9966 - accuracy: 0.5360 - val_loss: 1.0059 - val_accuracy: 0.5178 Epoch 13/100 79/79 [==============================] - 16s 205ms/step - loss: 0.9950 - accuracy: 0.5362 - val_loss: 1.0069 - val_accuracy: 0.5174 Epoch 14/100 79/79 [==============================] - 16s 204ms/step - loss: 0.9932 - accuracy: 0.5366 - val_loss: 1.0071 - val_accuracy: 0.5182 Epoch 15/100 79/79 [==============================] - 16s 200ms/step - loss: 0.9945 - accuracy: 0.5364 - val_loss: 1.0048 - val_accuracy: 0.5182 Epoch 16/100 79/79 [==============================] - 16s 209ms/step - loss: 0.9936 - accuracy: 0.5366 - val_loss: 1.0054 - val_accuracy: 0.5186 Epoch 17/100 79/79 [==============================] - 16s 207ms/step - loss: 0.9929 - accuracy: 0.5366 - val_loss: 1.0052 - val_accuracy: 0.5182 Epoch 18/100 79/79 [==============================] - 16s 204ms/step - loss: 0.9932 - accuracy: 0.5366 - val_loss: 1.0052 - val_accuracy: 0.5178 Epoch 19/100 79/79 [==============================] - 16s 203ms/step - loss: 0.9933 - accuracy: 0.5367 - val_loss: 1.0069 - val_accuracy: 0.5170 Epoch 20/100 79/79 [==============================] - 16s 197ms/step - loss: 0.9925 - accuracy: 0.5368 - val_loss: 1.0049 - val_accuracy: 0.5186 Epoch 21/100 79/79 [==============================] - 16s 201ms/step - loss: 0.9921 - accuracy: 0.5369 - val_loss: 1.0054 - val_accuracy: 0.5178 Epoch 22/100 79/79 [==============================] - 16s 203ms/step - loss: 0.9934 - accuracy: 0.5365 - val_loss: 1.0084 - val_accuracy: 0.5166 Epoch 23/100 79/79 [==============================] - 16s 206ms/step - loss: 0.9934 - accuracy: 0.5367 - val_loss: 1.0055 - val_accuracy: 0.5174 Epoch 24/100 79/79 [==============================] - 16s 205ms/step - loss: 0.9905 - accuracy: 0.5370 - val_loss: 1.0048 - val_accuracy: 0.5178 Epoch 25/100 79/79 [==============================] - 16s 199ms/step - loss: 0.9929 - accuracy: 0.5369 - val_loss: 1.0046 - val_accuracy: 0.5174 Epoch 26/100 79/79 [==============================] - 16s 208ms/step - loss: 0.9920 - accuracy: 0.5371 - val_loss: 1.0052 - val_accuracy: 0.5166 Epoch 27/100 79/79 [==============================] - 17s 211ms/step - loss: 0.9909 - accuracy: 0.5372 - val_loss: 1.0054 - val_accuracy: 0.5178 Epoch 28/100 79/79 [==============================] - 17s 212ms/step - loss: 0.9912 - accuracy: 0.5371 - val_loss: 1.0042 - val_accuracy: 0.5178 Epoch 29/100 79/79 [==============================] - 17s 214ms/step - loss: 0.9906 - accuracy: 0.5369 - val_loss: 1.0049 - val_accuracy: 0.5174 Epoch 30/100 79/79 [==============================] - 16s 205ms/step - loss: 0.9901 - accuracy: 0.5371 - val_loss: 1.0048 - val_accuracy: 0.5174 Epoch 31/100 79/79 [==============================] - 16s 207ms/step - loss: 0.9910 - accuracy: 0.5373 - val_loss: 1.0053 - val_accuracy: 0.5182 Epoch 32/100 79/79 [==============================] - 16s 204ms/step - loss: 0.9909 - accuracy: 0.5371 - val_loss: 1.0047 - val_accuracy: 0.5178 Epoch 33/100 79/79 [==============================] - 16s 209ms/step - loss: 0.9900 - accuracy: 0.5369 - val_loss: 1.0076 - val_accuracy: 0.5170 Epoch 34/100 79/79 [==============================] - 17s 211ms/step - loss: 0.9904 - accuracy: 0.5373 - val_loss: 1.0060 - val_accuracy: 0.5182 Epoch 35/100 79/79 [==============================] - 14s 180ms/step - loss: 0.9904 - accuracy: 0.5371 - val_loss: 1.0042 - val_accuracy: 0.5170 Epoch 36/100 79/79 [==============================] - 12s 149ms/step - loss: 0.9891 - accuracy: 0.5374 - val_loss: 1.0052 - val_accuracy: 0.5174 Epoch 37/100 79/79 [==============================] - 12s 150ms/step - loss: 0.9900 - accuracy: 0.5376 - val_loss: 1.0069 - val_accuracy: 0.5170 Epoch 38/100 79/79 [==============================] - 15s 187ms/step - loss: 0.9886 - accuracy: 0.5380 - val_loss: 1.0042 - val_accuracy: 0.5178 Epoch 39/100 79/79 [==============================] - 12s 153ms/step - loss: 0.9907 - accuracy: 0.5378 - val_loss: 1.0074 - val_accuracy: 0.5166 Epoch 40/100 79/79 [==============================] - 12s 151ms/step - loss: 0.9898 - accuracy: 0.5375 - val_loss: 1.0048 - val_accuracy: 0.5170 Epoch 41/100 79/79 [==============================] - 12s 151ms/step - loss: 0.9912 - accuracy: 0.5375 - val_loss: 1.0044 - val_accuracy: 0.5174 Epoch 42/100 79/79 [==============================] - 15s 185ms/step - loss: 0.9901 - accuracy: 0.5374 - val_loss: 1.0055 - val_accuracy: 0.5166 Epoch 43/100 79/79 [==============================] - 14s 171ms/step - loss: 0.9908 - accuracy: 0.5375 - val_loss: 1.0049 - val_accuracy: 0.5170 Epoch 44/100 79/79 [==============================] - 12s 153ms/step - loss: 0.9899 - accuracy: 0.5381 - val_loss: 1.0058 - val_accuracy: 0.5170 Epoch 45/100 79/79 [==============================] - 12s 154ms/step - loss: 0.9895 - accuracy: 0.5378 - val_loss: 1.0064 - val_accuracy: 0.5166 Epoch 46/100 79/79 [==============================] - 14s 172ms/step - loss: 0.9887 - accuracy: 0.5380 - val_loss: 1.0066 - val_accuracy: 0.5170 Epoch 47/100 79/79 [==============================] - 18s 231ms/step - loss: 0.9885 - accuracy: 0.5381 - val_loss: 1.0047 - val_accuracy: 0.5170 Epoch 48/100 79/79 [==============================] - 18s 226ms/step - loss: 0.9894 - accuracy: 0.5379 - val_loss: 1.0080 - val_accuracy: 0.5170 Epoch 49/100 79/79 [==============================] - 18s 228ms/step - loss: 0.9902 - accuracy: 0.5380 - val_loss: 1.0074 - val_accuracy: 0.5166 Epoch 50/100 79/79 [==============================] - 18s 227ms/step - loss: 0.9889 - accuracy: 0.5381 - val_loss: 1.0051 - val_accuracy: 0.5174 Epoch 51/100 79/79 [==============================] - 18s 228ms/step - loss: 0.9895 - accuracy: 0.5381 - val_loss: 1.0052 - val_accuracy: 0.5174 Epoch 52/100 79/79 [==============================] - 18s 232ms/step - loss: 0.9882 - accuracy: 0.5381 - val_loss: 1.0058 - val_accuracy: 0.5166 Epoch 53/100 79/79 [==============================] - 19s 235ms/step - loss: 0.9883 - accuracy: 0.5382 - val_loss: 1.0048 - val_accuracy: 0.5166 Epoch 54/100 79/79 [==============================] - 18s 231ms/step - loss: 0.9901 - accuracy: 0.5380 - val_loss: 1.0048 - val_accuracy: 0.5174 Epoch 55/100 79/79 [==============================] - 18s 231ms/step - loss: 0.9901 - accuracy: 0.5381 - val_loss: 1.0070 - val_accuracy: 0.5174 Epoch 56/100 79/79 [==============================] - 18s 230ms/step - loss: 0.9879 - accuracy: 0.5381 - val_loss: 1.0071 - val_accuracy: 0.5162 Epoch 57/100 79/79 [==============================] - 18s 226ms/step - loss: 0.9895 - accuracy: 0.5385 - val_loss: 1.0060 - val_accuracy: 0.5178 Epoch 58/100 79/79 [==============================] - 18s 228ms/step - loss: 0.9886 - accuracy: 0.5383 - val_loss: 1.0066 - val_accuracy: 0.5158 Epoch 59/100 79/79 [==============================] - 18s 229ms/step - loss: 0.9884 - accuracy: 0.5385 - val_loss: 1.0079 - val_accuracy: 0.5166 Epoch 60/100 79/79 [==============================] - 18s 228ms/step - loss: 0.9896 - accuracy: 0.5384 - val_loss: 1.0069 - val_accuracy: 0.5162 Epoch 61/100 79/79 [==============================] - 18s 230ms/step - loss: 0.9900 - accuracy: 0.5387 - val_loss: 1.0066 - val_accuracy: 0.5174 Epoch 62/100 79/79 [==============================] - 18s 227ms/step - loss: 0.9886 - accuracy: 0.5384 - val_loss: 1.0102 - val_accuracy: 0.5170 Epoch 63/100 79/79 [==============================] - 12s 157ms/step - loss: 0.9890 - accuracy: 0.5387 - val_loss: 1.0068 - val_accuracy: 0.5170 Epoch 64/100 79/79 [==============================] - 12s 146ms/step - loss: 0.9880 - accuracy: 0.5386 - val_loss: 1.0063 - val_accuracy: 0.5170 Epoch 65/100 79/79 [==============================] - 12s 147ms/step - loss: 0.9891 - accuracy: 0.5383 - val_loss: 1.0084 - val_accuracy: 0.5174 Epoch 66/100 79/79 [==============================] - 12s 146ms/step - loss: 0.9885 - accuracy: 0.5389 - val_loss: 1.0085 - val_accuracy: 0.5190 Epoch 67/100 79/79 [==============================] - 12s 155ms/step - loss: 0.9891 - accuracy: 0.5394 - val_loss: 1.0193 - val_accuracy: 0.5198 Epoch 68/100 79/79 [==============================] - 12s 155ms/step - loss: 1.0157 - accuracy: 0.5293 - val_loss: 1.0112 - val_accuracy: 0.5170 Epoch 69/100 79/79 [==============================] - 12s 150ms/step - loss: 0.9965 - accuracy: 0.5374 - val_loss: 1.0070 - val_accuracy: 0.5166 Epoch 70/100 79/79 [==============================] - 12s 153ms/step - loss: 0.9922 - accuracy: 0.5382 - val_loss: 1.0055 - val_accuracy: 0.5174 Epoch 71/100 79/79 [==============================] - 12s 154ms/step - loss: 0.9914 - accuracy: 0.5385 - val_loss: 1.0052 - val_accuracy: 0.5190 Epoch 72/100 79/79 [==============================] - 12s 152ms/step - loss: 0.9905 - accuracy: 0.5383 - val_loss: 1.0060 - val_accuracy: 0.5170 Epoch 73/100 79/79 [==============================] - 13s 159ms/step - loss: 0.9903 - accuracy: 0.5383 - val_loss: 1.0062 - val_accuracy: 0.5170 Epoch 74/100 79/79 [==============================] - 12s 152ms/step - loss: 0.9886 - accuracy: 0.5389 - val_loss: 1.0056 - val_accuracy: 0.5186 Epoch 75/100 79/79 [==============================] - 12s 154ms/step - loss: 0.9888 - accuracy: 0.5386 - val_loss: 1.0054 - val_accuracy: 0.5178 Epoch 76/100 79/79 [==============================] - 12s 155ms/step - loss: 0.9994 - accuracy: 0.5350 - val_loss: 1.0121 - val_accuracy: 0.5182 Epoch 77/100 79/79 [==============================] - 13s 160ms/step - loss: 0.9956 - accuracy: 0.5372 - val_loss: 1.0064 - val_accuracy: 0.5174 Epoch 78/100 79/79 [==============================] - 12s 158ms/step - loss: 0.9907 - accuracy: 0.5383 - val_loss: 1.0057 - val_accuracy: 0.5166 Epoch 79/100 79/79 [==============================] - 12s 156ms/step - loss: 0.9887 - accuracy: 0.5387 - val_loss: 1.0065 - val_accuracy: 0.5170
7d6aa7b28e95bc8ccbea73d40bbed8ed
{ "intermediate": 0.41500890254974365, "beginner": 0.2839066982269287, "expert": 0.30108436942100525 }
5,313
Вот код мне нужно передать сообщение из FirstFragment в Myapplication2 и вывести его там на экран , но текст не выводится укажи мне на ошибки :package com.example.myapplication_2; import androidx.appcompat.app.AppCompatActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initBroadcastReceiver(); } private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String message = intent.getStringExtra("message"); Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } }; private void initBroadcastReceiver() { IntentFilter filter = new IntentFilter("com.example.myapp_1.ACTION_SEND_MESSAGE"); registerReceiver(receiver, filter); } }package com.example.myapp_2.UI.view.fragments; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import com.example.myapp_2.List_1.Product; import com.example.myapp_2.List_1.ProductAdapter; import com.example.myapp_2.R; import com.example.myapp_2.UI.view.adapters.SliderAdapter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; public class FirstFragment extends Fragment implements View.OnClickListener ,RatingBar.OnRatingBarChangeListener { private Button mShareButton; private RecyclerView recyclerView; private ProductAdapter productAdapter; private RatingBar ratingBar; private TextView ratingAverageTextView; private ViewPager viewPager; private int[] imageUrls = {R.drawable.first_1, R.drawable.first_2, R.drawable.first_3, R.drawable.first_4, R.drawable.first_5}; private List<Product> products = getProducts(); private static final String MY_PREFS_NAME = "MyPrefs"; private float rating1 = 0.0f; private float rating2 = 0.0f; private float rating3 = 0.0f; private float rating4 = 0.0f; private float rating5 = 0.0f; private float rating6 = 0.0f; private float rating7 = 0.0f; private float rating8 = 0.0f; private float rating9 = 0.0f; private float rating10 = 0.0f; EditText mEditText; private static final String TAG = "FirstFragment"; private long noteId; public FirstFragment(long noteId) { this.noteId = noteId; } public FirstFragment() { } // private ViewPager viewPager; // EditText mEditText; public void createFile(String fileName, String fileContent) {//Реализовать создание текстового файла в app-specific storage. try { FileOutputStream fos = requireContext().openFileOutput(fileName, Context.MODE_PRIVATE); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos); outputStreamWriter.write(fileContent); outputStreamWriter.close(); String filePath = new File(requireContext().getFilesDir(), fileName).getAbsolutePath(); // получаем абсолютный путь Log.d(TAG, "File " + fileName + " created successfully at path:" + filePath); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "Failed to create file " + fileName + ": " + e.getMessage()); } } public void createTextFileInDirectory(String fileName) { File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); File textFile = new File(directory, fileName); try { FileOutputStream fileOutputStream = new FileOutputStream(textFile); fileOutputStream.write("Hello World".getBytes()); fileOutputStream.close(); Toast.makeText(getActivity(), "File created at: " + textFile.getAbsolutePath(), Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getActivity(), "Error creating file", Toast.LENGTH_SHORT).show(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_first, container, false); mShareButton = v.findViewById(R.id.btn_3); mShareButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { shareText(); } }); recyclerView = v.findViewById(R.id.recycler_view_products); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); productAdapter = new ProductAdapter(getContext(), products); recyclerView.setAdapter(productAdapter); productAdapter.setOnAddToCartClickListener(new ProductAdapter.OnAddToCartClickListener() { @Override public void onAddToCartClick(Product product) { Toast.makeText(getActivity(),"Товар успешно добавлен!",Toast.LENGTH_SHORT).show(); } }); viewPager = v.findViewById(R.id.view_pager); SliderAdapter adapter = new SliderAdapter(getActivity(), imageUrls); viewPager.setAdapter(adapter); // Получаем оценки из SharedPreferences SharedPreferences prefs = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE); rating1 = prefs.getFloat("rating1", 0.0f); rating2 = prefs.getFloat("rating2", 0.0f); rating3 = prefs.getFloat("rating3", 0.0f); rating4 = prefs.getFloat("rating4", 0.0f); rating5 = prefs.getFloat("rating5", 0.0f); rating6 = prefs.getFloat("rating6", 0.0f); rating7 = prefs.getFloat("rating7", 0.0f); rating8 = prefs.getFloat("rating8", 0.0f); rating9 = prefs.getFloat("rating9", 0.0f); rating10 = prefs.getFloat("rating10", 0.0f); // Устанавливаем оценки в соответствующие товары products.get(0).setRating(rating1); products.get(1).setRating(rating2); products.get(2).setRating(rating3); products.get(3).setRating(rating4); products.get(4).setRating(rating5); products.get(5).setRating(rating6); products.get(6).setRating(rating7); products.get(7).setRating(rating8); products.get(8).setRating(rating9); products.get(9).setRating(rating10); products.get(0).setPrice(300.99); products.get(1).setPrice(120.99); products.get(2).setPrice(140.99); products.get(3).setPrice(420.99); products.get(4).setPrice(380.99); products.get(5).setPrice(105.99); products.get(6).setPrice(200.99); products.get(7).setPrice(150.99); products.get(8).setPrice(190.99); products.get(9).setPrice(299.99); final Handler handler = new Handler(); final Runnable runnable = new Runnable() { @Override public void run() { int currentItem = viewPager.getCurrentItem(); int totalItems = viewPager.getAdapter().getCount(); int nextItem = currentItem == totalItems - 1 ? 0 : currentItem + 1; viewPager.setCurrentItem(nextItem); handler.postDelayed(this, 3000); } }; handler.postDelayed(runnable, 3000); return v; } private List<Product> getProducts() { List<Product> products = new ArrayList<>(); Product product1 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f); products.add(product1); Product product2 = new Product("Product 2", "Description 2", R.drawable.food_1_1, 0.0f); products.add(product2); Product product3 = new Product("Product 3", "Description 3", R.drawable.food_1_4, 0.0f); products.add(product3); Product product4 = new Product("Product 4", "Description 4", R.drawable.food_1_1, 0.0f); products.add(product4); Product product5 = new Product("Product 5", "Description 5", R.drawable.food_1_1, 0.0f); products.add(product5); Product product6 = new Product("Product 6", "Description 6", R.drawable.food_1_1,0.0f); products.add(product6); Product product7 = new Product("Product 7", "Description 7", R.drawable.food_3_2,0.0f); products.add(product7); Product product8 = new Product("Product 8", "Description 8", R.drawable.food_3_3,0.0f); products.add(product8); Product product9 = new Product("Product 9", "Description 9", R.drawable.food_1_1,0.0f); products.add(product9); Product product10 = new Product("Product 10", "Description 10", R.drawable.food_1_1,0.0f); products.add(product10); return products; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {//После того как отрисовались лементы super.onViewCreated(view,savedInstanceState); initView(view); } private void initView(View view){ Button btnClick = (Button) view.findViewById(R.id.btn_2); Button btnClick2 = (Button) view.findViewById(R.id.btn_3); btnClick.setOnClickListener(this); btnClick2.setOnClickListener(this); Button btnClick3 = (Button) view.findViewById(R.id.button); btnClick3.setOnClickListener(this); Button btnClick4 = (Button) view.findViewById(R.id.change_btn); btnClick4.setOnClickListener(this); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = this.getArguments(); if (bundle != null) { int myInt = bundle.getInt("hello world", 123); String strI = Integer.toString(myInt); Toast.makeText(getActivity(),strI,Toast.LENGTH_SHORT).show(); } } @Override public void onStart() { super.onStart(); } @Override public void onResume() { super.onResume(); } @Override public void onPause(){ super.onPause(); // Сохраняем оценки в SharedPreferences SharedPreferences.Editor editor = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit(); editor.putFloat("rating1", products.get(0).getRating()); editor.putFloat("rating2", products.get(1).getRating()); editor.putFloat("rating3", products.get(2).getRating()); editor.putFloat("rating4", products.get(3).getRating()); editor.putFloat("rating5", products.get(4).getRating()); editor.putFloat("rating6", products.get(5).getRating()); editor.putFloat("rating7", products.get(6).getRating()); editor.putFloat("rating8", products.get(7).getRating()); editor.putFloat("rating9", products.get(8).getRating()); editor.putFloat("rating10", products.get(9).getRating()); editor.apply(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { super.onDestroy(); } private void changeFragment(){ getFragmentManager().beginTransaction().replace(R.id.nav_container,new SecondFragment()).addToBackStack(null).commit(); } private void changeFragment2(){ getFragmentManager().beginTransaction().replace(R.id.nav_container,new ThirdFragment()).addToBackStack(null).commit(); } private void changeFragment3(){ getFragmentManager().beginTransaction().replace(R.id.nav_container,new ListFragment()).addToBackStack(null).commit(); } private void changeFragment4(){ getFragmentManager().beginTransaction().replace(R.id.nav_container,new RecycleFragment()).addToBackStack(null).commit(); } Context context; @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn_2: changeFragment4(); break; case R.id.btn_3: sendBroadcast(); //shareText(); //createFile("test4.txt", "Мой финальный текстовый документ"); //createTextFileInDirectory("test1.txt"); break; case R.id.button: changeFragment3(); break; case R.id.change_btn: changeFragment4(); break; } } @Override public void onRatingChanged(RatingBar ratingBar, float v, boolean b) { } @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); // Сохраняем оценки в Bundle outState.putFloat("rating1", rating1); outState.putFloat("rating2", rating2); outState.putFloat("rating3", rating3); outState.putFloat("rating4", rating4); outState.putFloat("rating5", rating5); outState.putFloat("rating6", rating6); outState.putFloat("rating7", rating7); outState.putFloat("rating8", rating8); outState.putFloat("rating9", rating9); outState.putFloat("rating10", rating10); } @Override public void onViewStateRestored(@Nullable Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (savedInstanceState != null) { // Восстанавливаем оценки из Bundle rating1 = savedInstanceState.getFloat("rating1"); rating2 = savedInstanceState.getFloat("rating2"); rating3 = savedInstanceState.getFloat("rating3"); rating4 = savedInstanceState.getFloat("rating4"); rating5 = savedInstanceState.getFloat("rating5"); rating6 = savedInstanceState.getFloat("rating6"); rating7 = savedInstanceState.getFloat("rating7"); rating8 = savedInstanceState.getFloat("rating8"); rating9 = savedInstanceState.getFloat("rating9"); rating10 = savedInstanceState.getFloat("rating10"); // Устанавливаем оценки в соответствующие товары products.get(0).setRating(rating1); products.get(1).setRating(rating2); products.get(2).setRating(rating3); products.get(3).setRating(rating4); products.get(4).setRating(rating5); products.get(5).setRating(rating6); products.get(6).setRating(rating7); products.get(7).setRating(rating8); products.get(8).setRating(rating9); products.get(9).setRating(rating10); } } private void shareText() { Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "Hello, world!"); sendIntent.setType("text/plain"); Intent shareIntent = Intent.createChooser(sendIntent, null); startActivity(shareIntent); } private void sendBroadcast() { Intent intent = new Intent("com.example.myapp_1.ACTION_SEND_MESSAGE"); intent.putExtra("message", "Hello, world!"); sendBroadcast(); } // Метод, который создает список товаров }
2ab5f1615a8a91679fc54c96ca1abe89
{ "intermediate": 0.35228389501571655, "beginner": 0.4468109607696533, "expert": 0.20090514421463013 }
5,314
Write a Python program which solves a system of linear equations using the numpy package. The program prompts the user for a square matrix and a column vector. Then the program solves the linear matrix equation using both the `numpy.linalg.solve` function and the Cramer's rule
3596d5e44b407eb3515c9155045fc317
{ "intermediate": 0.42674365639686584, "beginner": 0.17926910519599915, "expert": 0.393987238407135 }
5,315
hello
ce38b818f0b15c56d4a73e6c51b383ea
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
5,316
The infinite series 𝑓(𝑛) = ∑ (1 /𝑖^4) 𝑖=1 converges to the value of 𝜋^4/90 as 𝑛 approaches infinity. You are provided with two files: one of them contains 10,000 16-digit (or double) precision values, and the other contains the same values but now in 8-digit (or single) precision. Note that the values are needed for computing the given summation for 𝑛 = 10,000, but they have been randomly shuffled. a) Write a MATLAB script to compute the summation of the 10,000 shuffled values using single precision floating point numbers. b) Repeat the computations in a) but first sort the values in ascending order. c) Repeat a) and b) except now using the double precision floating point values. d) Compute the true percent relative errors of the four different results against the theoretical true value for the infinite series. e) Repeat a, b, c, d, but now using in-built sum()MATLAB function and investigate the results. f) What type of numerical error does this question illustrate? What is a viable remedy (or what are viable remedies) to this type of numerical error?
f6bc9125ffb37ce41c268f591bbc5cc3
{ "intermediate": 0.3997454345226288, "beginner": 0.20472507178783417, "expert": 0.39552953839302063 }
5,317
In some applications we want to find minimum spanning trees with specific properties. The next problem is an example. Input: undirected graph G = (V, E), edge weights we, and a subset U of nodes. Output: the minimum spanning tree in which the nodes of the set U are leaves. (The tree may have leaves from nodes of the set V - U as well). Write pseudocode for the above problem which runs in time O( |E| log|V| ). How can we find a maximum spanning tree instead of minimum spanning tree?
f3215bd4d9542fc1980950ee55ebcc39
{ "intermediate": 0.24479176104068756, "beginner": 0.40950360894203186, "expert": 0.345704585313797 }
5,318
Структурируй пожалуйста { "info": { "_postman_id": "eee8828b-a866-4e2d-bb71-960d7c810c5c", "name": "MOLS", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", "_exporter_id": "4519176" }, "item": [ { "name": "add Remains", "request": { "method": "POST", "header": [], "body": { "mode": "raw", "raw": "{\r\n \"IMNNAME\":\"бюджет\",\r\n \"TORG\":\"Траватан\",\r\n \"FGRLEVEL1\":\"Травопрост\",\r\n \"IMN\":\"Траватан глазные капли 0,04мг\/мл 2,5мл флакон-капельница №1\",\r\n \"FGRLEVEL2\":\"Симпатомиметики исключая препараты для лечения глаукомы\",\r\n \"FGRLEVEL3\":\"Средства для лечения глаукомы и миотики\",\r\n \"FGRLEVEL4\":\"Средства, применяемые в офтальмологии\",\r\n \"LEKFORM\":\"глазные капли\",\r\n \"KOLDV1\":\".04000000\",\r\n \"EDIZM1\":\"мг/мл\",\r\n \"KOLPR\":\"2.50000000\",\r\n \"EDIZMPR\":\"мл\",\r\n \"VIDUP\":\"флак.-кап.\",\r\n \"IMF\":\"Alcon-Couvreur n.v. s.a. Бельгия\",\r\n \"KPR\":\"33 132\",\r\n \"KODN\":\"1150002\",\r\n \"KOLUP\":\"1.00000000\",\r\n \"CKOL\":\"10.00000000\",\r\n \"KOL\":\"10.00000000\"\r\n}, {\r\n \"IMNNAME\":\"бюджет\",\r\n \"TORG\":\"ДуоТрав\",\r\n \"FGRLEVEL1\":\"Травопрост+Тимолол\",\r\n \"IMN\":\"ДуоТрав глазные капли 40мкг\/мл 5мг\/мл 2,5мл флакон-капельница №1\",\r\n \"FGRLEVEL2\":\"Бета-адреноблокаторы\",\r\n \"FGRLEVEL3\":\"Средства для лечения глаукомы и миотики\",\r\n \"FGRLEVEL4\":\"Средства, применяемые в офтальмологии\",\r\n \"LEKFORM\":\"глазные капли\",\r\n \"KOLDV1\":\"40.00000000\",\r\n \"EDIZM1\":\"мкг/мл\",\r\n \"KOLPR\":\"2.50000000\",\r\n \"EDIZMPR\":\"мл\",\r\n \"VIDUP\":\"флак.-кап.\",\r\n \"IMF\":\"Alcon-Couvreur n.v. s.a. Бельгия\",\r\n \"KPR\":\"39 746\",\r\n \"KODN\":\"7039746\",\r\n \"KOLUP\":\"1.00000000\",\r\n \"CKOL\":\"10.00000000\",\r\n \"KOL\":\"10.00000000\"\r\n}", "options": { "raw": { "language": "json" } } }, "url": { "raw": "https://mols.mapsoft.by/service/app/mols/api.php/api/addRemains?guid=eDuciFmSRmAxYflv", "protocol": "https", "host": "mols", "mapsoft", "by" , "path": "service", "app", "mols", "api.php", "api", "addRemains" , "query": { "key": "guid", "value": "eDuciFmSRmAxYflv" } } }, "response": [] } ] }
59cc309802ff6741e8d3586230defdb6
{ "intermediate": 0.249267578125, "beginner": 0.47213542461395264, "expert": 0.27859699726104736 }
5,319
write a s-order Markov chain for numerical sequences with a transition matrix
ee76e03165f5929fc37c826b334f8b35
{ "intermediate": 0.22718486189842224, "beginner": 0.1372515857219696, "expert": 0.6355635523796082 }
5,320
can you debug this code? //Let G = (V,E) be a directed graph with n nodes and m edges. Two nodes u, v are said to be incomparable if there are no paths from u to v and from v to u. //(a) Write code in C that constructs a struct that can answer in constant time if there is a path between two nodes u and v. #include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct node { int data; struct node *next; } node; typedef struct graph { int numVertices; node **adjLists; } graph; node *createNode(int v) { node *newNode = malloc(sizeof(node)); newNode->data = v; newNode->next = NULL; return newNode; } graph *createGraph(int vertices) { graph *graph = malloc(sizeof(graph)); graph->numVertices = vertices; graph->adjLists = malloc(vertices * sizeof(node *)); int i; for (i = 0; i < vertices; i++) graph->adjLists[i] = NULL; return graph; } void addEdge(graph *graph, int src, int dest) { node *newNode = createNode(dest); newNode->next = graph->adjLists[src]; graph->adjLists[src] = newNode; } void printGraph(graph *graph) { int v; for (v = 0; v < graph->numVertices; v++) { node *temp = graph->adjLists[v]; printf("\n Adjacency list of vertex %d\n ", v); while (temp) { printf("%d -> ", temp->data); temp = temp->next; } printf("\n"); } } bool isPath(graph *graph, int src, int dest) { node *temp = graph->adjLists[src]; while (temp) { if (temp->data == dest) { return true; } temp = temp->next; } return false; } int main() { graph *graph = createGraph(4); addEdge(graph, 0, 1); addEdge(graph, 0, 2); addEdge(graph, 1, 2); addEdge(graph, 2, 0); addEdge(graph, 2, 3); addEdge(graph, 3, 3); printGraph(graph); printf("\n%d", isPath(graph, 1, 3)); printf("\n%d", isPath(graph, 3, 1)); return 0; }
0526b294663bf689bb14ebce68b0ae5a
{ "intermediate": 0.46459001302719116, "beginner": 0.33679062128067017, "expert": 0.19861936569213867 }