row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
5,421
$(".btn.btn-danger").on('click', function() { var checked = jQuery('input:checkbox:checked').map(function () { return this.value; }).get(); jQuery('input:checkbox:checked').parents("tr").remove(); }); it is working but after relaoding data is gettinmg back
6a2788a2158129f774e32c14841e3bde
{ "intermediate": 0.6136978268623352, "beginner": 0.2237749844789505, "expert": 0.1625272035598755 }
5,422
i want to pass my data to spring batch item processor i runing my job inside service with job luncher my data is big and its hash map so idont want use job params
be34178fb2d0edf798d056ad969619ec
{ "intermediate": 0.5890387892723083, "beginner": 0.1237512156367302, "expert": 0.2872099280357361 }
5,423
hi
f140f3eca606b060b7e3c07830a566f5
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,424
What do you know about Google Sheets?
81758afa099cf2139b5f99b80272f0ea
{ "intermediate": 0.3258422017097473, "beginner": 0.4365060329437256, "expert": 0.23765181005001068 }
5,425
hello
412a02ba769997bec6fd8343a3897581
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
5,426
can you give me amazing css for my items if I want?
d7936702e503d30810b3a34c47fb5d2c
{ "intermediate": 0.36115267872810364, "beginner": 0.3205089271068573, "expert": 0.31833839416503906 }
5,427
i want to have react <h3> and toggle component next to each other instead of toggle being below
dfab5c864ec9a9cbc32fdb14b57cc247
{ "intermediate": 0.4073583483695984, "beginner": 0.23236867785453796, "expert": 0.36027294397354126 }
5,428
Создай регистраций и базу данных SQLITE для пользователей , у меня есть эти классы : package com.example.myapp_2; class User { private String name; private String email; public User(String name, String email) { this.name = name; this.email = email; } public String getName() { return name; } public String getEmail() { return email; } } package com.example.myapp_2; import com.example.myapp_2.List_1.Product; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Shop { private List<User> userList = new ArrayList<>(); // список пользователей, подписанных на обновления public Future<Void> updatePricesAndNotifyUsers() { ExecutorService executorService = Executors.newFixedThreadPool(2); // создаем исполнительный сервис с двумя потоками userList = getUsersSubscribedForUpdates(); // получаем список пользователей, подписанных на обновления Future<Void> future = executorService.submit(new Callable<Void>() { // создаем новую задачу и отправляем ее на выполнение @Override public Void call() throws Exception { updatePrices(); // обновляем цены на продукты for (User user : userList) { sendPushNotification(user); // отправляем push-уведомления каждому пользователю } return null; // возвращаем null, потому что методы updatePrices() и sendPushNotification() ничего не возвращают } }); executorService.shutdown(); // останавливаем исполнительный сервис после выполнения задачи return future; // возвращаем объект типа Future для отслеживания статуса выполнения задачи } private List<User> getUsersSubscribedForUpdates() { List<User> userList = new ArrayList<>(); // здесь мы получаем список всех пользователей, подписанных на обновления и добавляем их в список userList // Например, так: User user1 = new User("John", "john@email.com"); User user2 = new User("Jane", "jane@email.com"); userList.add(user1); userList.add(user2); return userList; } private void updatePrices() { // здесь мы обновляем цены на продукты // Например, так: Product product1 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f); Product product2 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f); product1.setPrice(12); product2.setPrice(17); } private void sendPushNotification(User user) { // здесь мы отправляем push-уведомление пользователю // Например, так: PushNotificationService.pushNotification(user.getEmail(), "Price update!", "Check out the new prices!"); } }package com.example.myapp_2.List_1; public class Product { private String name; private String description; private int imageResource; private float rating; private double price; public Product(String name, String description, int imageResource, float rating, double price) { this.name = name; this.description = description; this.imageResource = imageResource; this.rating = rating; this.price = price; } public Product(String name, String description, int imageResource, double price) { this.name = name; this.description = description; this.imageResource = imageResource; this.rating = 0.0f; this.price = price; } public String getName() { return name; } public String getDescription() { return description; } public int getImageResource() { return imageResource; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
27c76a993e0740bae371e5d51d5d6f27
{ "intermediate": 0.3109753131866455, "beginner": 0.519079327583313, "expert": 0.1699453890323639 }
5,429
How to code GUI in java?
3601113c6074110c673d0667e7cd067b
{ "intermediate": 0.2619297504425049, "beginner": 0.5297698974609375, "expert": 0.20830032229423523 }
5,430
Write python code for a machine learning model. This model will receive solidity smart contract code to determine if the code has a vulnerability. If a vulnerability is found, the model will return the line of code with the vulnerability and a description of the vulnerability.
b2cc58fc246c686feff45212dd3c938f
{ "intermediate": 0.1719328612089157, "beginner": 0.15579701960086823, "expert": 0.6722701191902161 }
5,431
Hello from here
ffe16dbce4aeeead24b36c686fe97c44
{ "intermediate": 0.33012375235557556, "beginner": 0.22981129586696625, "expert": 0.4400649964809418 }
5,432
package com.example.myapp_2; import android.content.Context; import com.example.myapp_2.List_1.Product; import com.example.myapp_2.USERSDB.DBHelper; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Shop { private Context context; private List<User> userList = new ArrayList<>(); // список пользователей, подписанных на обновления public Shop(Context context) { this.context = context; } public Future<Void> updatePricesAndNotifyUsers() { userList = getUsersSubscribedForUpdates(); // получаем список пользователей, подписанных на обновления DBHelper dbHelper = new DBHelper(context); // создаем экземпляр класса DBHelper for (User user : userList) { user.addToDatabase(context); // регистрируем пользователя в базе данных } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ExecutorService executorService = Executors.newFixedThreadPool(2); // создаем исполнительный сервис с двумя потоками userList = getUsersSubscribedForUpdates(); // получаем список пользователей, подписанных на обновления Future<Void> future = executorService.submit(new Callable<Void>() { // создаем новую задачу и отправляем ее на выполнение @Override public Void call() throws Exception { updatePrices(); // обновляем цены на продукты for (User user : userList) { sendPushNotification(user); // отправляем push-уведомления каждому пользователю } return null; // возвращаем null, потому что методы updatePrices() и sendPushNotification() ничего не возвращают } }); executorService.shutdown(); // останавливаем исполнительный сервис после выполнения задачи return future; // возвращаем объект типа Future для отслеживания статуса выполнения задачи } private List<User> getUsersSubscribedForUpdates() { List<User> userList = new ArrayList<>(); // здесь мы получаем список всех пользователей, подписанных на обновления и добавляем их в список userList // Например, так: User user1 = new User("John", "john@email.com"); User user2 = new User("Jane", "jane@email.com"); userList.add(user1); userList.add(user2); return userList; } private void updatePrices() { // здесь мы обновляем цены на продукты // Например, так: Product product1 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f); Product product2 = new Product("Product 1", "Description 1", R.drawable.food_3_1jpg, 0.0f); product1.setPrice(12); product2.setPrice(17); } private void sendPushNotification(User user) { // здесь мы отправляем push-уведомление пользователю // Например, так: PushNotificationService.pushNotification(user.getEmail(), "Price update!", "Check out the new prices!"); } private List<User> getUsersSubscribedForUpdates() { List<User> userList = new ArrayList<>(); // здесь мы получаем список всех пользователей, подписанных на обновления и добавляем их в список userList // Например, так: User user1 = new User("John", "john@email.com"); User user2 = new User("Jane", "jane@email.com"); user1.addToDatabase(getApplicationContext()); user2.addToDatabase(getApplicationContext()); userList.add(user1); userList.add(user2); return userList; } }укажи на ошибки
a64cbf63f9e4c604536f4bb7ab0a96dd
{ "intermediate": 0.37183019518852234, "beginner": 0.48133978247642517, "expert": 0.14683009684085846 }
5,433
hi
9d41aaa433cca3b78e3c93d9020948f2
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,434
Исправь ошибку в методе getAllUsers вот код : package com.example.myapp_2.UI.view.fragments; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; 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.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; 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.Shop; import com.example.myapp_2.UI.view.adapters.SliderAdapter; import com.example.myapp_2.USERSDB.DBHelper; import com.example.myapp_2.User; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class FirstFragment extends Fragment implements View.OnClickListener ,RatingBar.OnRatingBarChangeListener { private ListView userListView; private Button updateButton; private Shop shop; 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); userListView = v.findViewById(R.id.user_list_view); // Создаем адаптер для списка пользователей ArrayAdapter<User> adapter = new ArrayAdapter<User>( getActivity(), android.R.layout.simple_list_item_1, getAllUsers()); // Присваиваем адаптер списку пользователей userListView.setAdapter(adapter); // Регистрируем нового пользователя User newUser = new User("Mike", "mike@email.com"); registerNewUser(newUser); updateButton = v.findViewById(R.id.update_button); shop = new Shop(getActivity()); // передаем объект Activity в конструктор класса Shop updateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { shop.updatePrices(); // вызываем метод обновления цен у объекта класса Shop } }); 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_2.ACTION_RECEIVE_MESSAGE"); intent.putExtra("message", "Hello, world!"); requireContext().sendBroadcast(intent); } private void updatePricesAndNotifyUsers() { Future<Void> future = shop.updatePricesAndNotifyUsers(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { future.get(); // ожидаем завершения выполнения задачи } catch (ExecutionException | InterruptedException e) { e.printStackTrace(); } return null; } }.execute(); } // Регистрация нового пользователя private void registerNewUser(User user) { user.addToDatabase(getActivity().getApplicationContext()); Log.d("Registered user", user.getName() + " " + user.getEmail()); } // Получение всех пользователей private List<User> getAllUsers(Context context) { DBHelper dbHelper = new DBHelper(context.getApplicationContext()); return dbHelper.getAllUsers(); } }
4472e6c26423bd7518b9b16f8924bb96
{ "intermediate": 0.3221990764141083, "beginner": 0.3921082019805908, "expert": 0.2856926918029785 }
5,435
give me an java spark example : union 2 datasets, group by id and then call a map function on the values
2ec53d8bc926853a9446ff283ee4ea61
{ "intermediate": 0.6760731935501099, "beginner": 0.1727149784564972, "expert": 0.15121182799339294 }
5,436
hi
a15e8784c5807c9418a0dc65d4b6ce39
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,437
how to fix the date of a DateField as today django
db67a46a0fdbbcd1e7d6eb6a0d51f768
{ "intermediate": 0.7381809949874878, "beginner": 0.12137981504201889, "expert": 0.14043915271759033 }
5,438
@echo off color 0a set “PASSWORD=yellowstar520” :LOGIN cls echo Enter password to access the hacker menu: set /p “USERPASS=>” if “%USERPASS%”==“%PASSWORD%” goto MENU echo Incorrect password. Try again. timeout /t 2 /nobreak > NUL goto LOGIN :MENU cls echo *** HACKER MENU *** echo. echo 1. Command echo 2. Proxy echo 3. Restart echo 4. Exit echo. set /p option=Choose an option: if “%option%”==“1” goto COMMAND if “%option%”==“2” start https://navy.strangled.net if “%option%”==“3” goto RESTART if “%option%”==“4” exit goto MENU :COMMAND cls echo *** EXECUTE COMMANDS *** echo. echo Enter your terminal command below: echo. set /p “command=cmd~” echo. echo Running command: %command% echo. cmd /c “%command%” goto MENU :RESTART cls echo Restarting the program… echo. timeout /t 2 /nobreak > NUL call “%~f0” goto MENU
cb52cb8d9d15f83f597e53939a3204ba
{ "intermediate": 0.33800777792930603, "beginner": 0.30798035860061646, "expert": 0.3540118634700775 }
5,439
implementation of neighboring two persons in owl
bfa954746a4591d45f8dce726c07d173
{ "intermediate": 0.4242912232875824, "beginner": 0.26681557297706604, "expert": 0.30889326333999634 }
5,440
Исправь ошибки : package com.example.myapp_2.USERSDB; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.myapp_2.List_1.Product; import com.example.myapp_2.User; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class DBHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "myapp.db"; private static final String TABLE_USERS = "users"; private static final String TABLE_PRODUCTS = "products"; // Добавляем поле KEY_PRICE и определяем его константу private static final String KEY_PRICE = "price"; private static final String COLUMN_ID = "id"; private static final String COLUMN_NAME = "name"; private static final String COLUMN_EMAIL = "email"; private static final String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + " ( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_EMAIL + " TEXT )"; // Добавляем запрос на создание таблицы продуктов private static final String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + " ( " + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + "description TEXT, " + "image INTEGER, " + KEY_PRICE + " REAL )"; private static final String DROP_USERS_TABLE = "DROP TABLE IF EXISTS " + TABLE_USERS; private static final String DROP_PRODUCTS_TABLE = "DROP TABLE IF EXISTS " + TABLE_PRODUCTS; public DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_USERS_TABLE); db.execSQL(CREATE_PRODUCTS_TABLE); // создаем таблицу продуктов в БД } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DROP_USERS_TABLE); db.execSQL(DROP_PRODUCTS_TABLE); // удаляем таблицу продуктов из БД onCreate(db); } // Добавляем метод updateProductPrice public void updateProductPrice(Product product) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_PRICE, product.getPrice()); db.update(TABLE_PRODUCTS, values, COLUMN_NAME + " = ?", new String[] { product.getName() }); db.close(); } public void addUser(User user) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(COLUMN_NAME, user.getName()); values.put(COLUMN_EMAIL, user.getEmail()); db.insert(TABLE_USERS, null, values); db.close(); } public List<User> getAllUsers(Context context) { List<User> userList = new ArrayList<>(); DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM " + DBHelper.TABLE_USERS, null); if (cursor.moveToFirst()) { do { String name = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME)); String email = cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_EMAIL)); User user = new User(name, email); userList.add(user); } while (cursor.moveToNext()); } cursor.close(); db.close(); return userList; } }
926bab01a2029793748c31ab7d65533a
{ "intermediate": 0.3011206090450287, "beginner": 0.5004289150238037, "expert": 0.19845055043697357 }
5,441
Act as a Blender Python expert. I have this code, could you make it better ? bl_info = { "name":"Eazy Azzets", "author": "Yam K.", "version": (0,3), "blender": (3, 3, 0), "location": "", "Description": "Making asset browser for GTA 5 Easier", "warning": "", "category": "Yam K." } import bpy def eazy_azzets(): objects = bpy.context.scene.objects for obj in objects: if obj.name.endswith('.#dr'): obj.parent = None obj.name = obj.name[:-4] obj.asset_mark() obj.asset_generate_preview() if not obj.asset_data: bpy.data.objects.remove(obj) num_objects = len(objects) num_columns = int(num_objects ** 0.5) num_rows = num_columns if num_columns * num_columns == num_objects else num_columns + 1 max_dimensions = [max(obj.dimensions[axis] for obj in objects) for axis in range(2)] margin = 1 total_margin = [(num_columns - 1) * margin, (num_rows - 1) * margin] total_dimensions = [num_columns * max_dimensions[0] + total_margin[0], num_rows * max_dimensions[1] + total_margin[1]] center = [total_dimensions[axis] / 2 for axis in range(2)] current_position = [center[0] - (total_dimensions[0] / 2), center[1] - (total_dimensions[1] / 2)] for i, obj in enumerate(objects): obj.location.x = current_position[0] + max_dimensions[0] / 2 obj.location.y = current_position[1] + max_dimensions[1] / 2 current_position[0] += max_dimensions[0] + margin if (i + 1) % num_columns == 0: current_position[0] = center[0] - (total_dimensions[0] / 2) current_position[1] += max_dimensions[1] + margin class DoItButton(bpy.types.Operator): """Run the Eazy Azzets script""" bl_idname = "object.eazy_azzets" bl_label = "Do It ! Just do it !" bl_options = {'REGISTER', 'UNDO'} def execute(self, context): eazy_azzets() return {'FINISHED'} class EazyAzzetsPanel(bpy.types.Panel): """Eazy Azzets panel""" bl_label = "Eazy Azzets" bl_idname = "OBJECT_PT_eazy_azzets" bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category = "Eazy Azzets" def draw(self, context): layout = self.layout layout.operator("object.eazy_azzets") def register(): bpy.utils.register_class(DoItButton) bpy.utils.register_class(EazyAzzetsPanel) def unregister(): bpy.utils.unregister_class(DoItButton) bpy.utils.unregister_class(EazyAzzetsPanel) if __name__ == "__main__": register()
08f955ae4e759053d63bdfe60dd3586c
{ "intermediate": 0.269031822681427, "beginner": 0.5023297667503357, "expert": 0.22863838076591492 }
5,442
give me an java spark example : union 2 datasets, group by id and then call a map function on the values
9e5433520288f0ba02a8010a8bd41696
{ "intermediate": 0.6760731935501099, "beginner": 0.1727149784564972, "expert": 0.15121182799339294 }
5,443
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:http/http.dart' as http; import 'package:login_ui/Feature/Login%20Screen/Login_Screen.dart'; import 'package:login_ui/Feature/home/Response.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { final List<String> imagePaths = [ 'assets/1.jpeg', 'assets/2.jpeg', 'assets/3.jpeg', 'assets/4.jpeg', 'assets/5.jpeg', 'assets/6.jpeg', 'assets/7.jpeg', 'assets/8.jpeg' ]; List<String> filteredImagePaths = []; bool isSearching = false; Map<int, String> imageData = { 0: 'HDFCBANK.NS', 1: 'ICIC', 2: 'data for image 3', 3: 'data for image 4', 4: 'data for image 5', 5: 'data for image 6', 6: 'data for image 7', 7: 'data for image 8', }; TextEditingController _searchController = TextEditingController(); @override void initState() { super.initState(); filteredImagePaths = imagePaths; } Future<void> _sendData(BuildContext context, String symbol) async { try { var url = Uri.parse('https://36d3-203-109-66-92.in.ngrok.io/hello'); var response = await http.post( url, headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode(<String, String>{'symbol': symbol}), ); print('Data sent: $symbol'); print('Response status code: ${response.statusCode}'); print('Response body: ${response.body}'); Map<String, dynamic> graphData = jsonDecode(response.body); String graphUrl = graphData['url']; await Navigator.of(context).push( MaterialPageRoute( builder: (_) => Scaffold( appBar: AppBar( title: Text(symbol), ), body: WebView( initialUrl: graphUrl, javascriptMode: JavascriptMode.unrestricted, ), ), ), ); } catch (e) { print('Error: $e'); } } WebView? _webView; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: !isSearching ? Text('Stocks') : TextField( controller: _searchController, decoration: InputDecoration( hintText: 'Search', icon: Icon(Icons.search), ), onSubmitted: (value) { _sendData(context, value); }, ), actions: [ IconButton( icon: Icon(Icons.search), onPressed: () { setState(() { isSearching = !isSearching; filteredImagePaths = imagePaths; }); }, ), ], ), body: Stack( children: [ Container( decoration: BoxDecoration( image: DecorationImage( image: AssetImage('assets/theme.jpg'), fit: BoxFit.cover, ), ), child: GridView.count( crossAxisCount: 2, padding: EdgeInsets.all(8), mainAxisSpacing: 8, crossAxisSpacing: 8, children: List.generate(filteredImagePaths.length, (index) { return GestureDetector( onTap: () async { String symbol = imageData[index]!; await _sendData(context, symbol); }, child: ClipRRect( borderRadius: BorderRadius.circular(8), child: Stack( fit: StackFit.expand, children: [ Image.asset( filteredImagePaths[index], fit: BoxFit.cover, ), Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [ Colors.black.withOpacity(0.8), Colors.transparent ], ), ), ), ], ), ), ); }), ), ), if (_webView != null) Positioned.fill( child: Column( children: [ Expanded( child: _webView!, ), ElevatedButton( onPressed: () { setState(() { _webView = null; }); }, child: Text('Close Graph'), ), ], ), ), ], ), ); } } cant see graph solve it
e04d63b2ec95a4cc275544cf46bdbbfd
{ "intermediate": 0.35027381777763367, "beginner": 0.554667592048645, "expert": 0.09505852311849594 }
5,444
how to make it so my code in C# allows both lower case and upper case inputs as equivalent.
faf2e5d492e19b0d935af4a20571c5c2
{ "intermediate": 0.4047286808490753, "beginner": 0.28642645478248596, "expert": 0.30884483456611633 }
5,445
hey sup? are familiar with scrapy?
8c42e2f7e64c38851202e773fe358165
{ "intermediate": 0.2987898290157318, "beginner": 0.5485451817512512, "expert": 0.15266497433185577 }
5,446
make a DateField to just accept today django
f7a2a5189a3e34a24f42bf0604a1c27a
{ "intermediate": 0.5907828211784363, "beginner": 0.16446781158447266, "expert": 0.24474938213825226 }
5,447
are familiar with scrapy>
e23cec322a87651bfe0d80fe34d53db8
{ "intermediate": 0.2791929543018341, "beginner": 0.6202561855316162, "expert": 0.10055078566074371 }
5,448
Flutter 3.7. Which theme option should I use to configure font size of all text fields
cbae2697d5a3199717d27365613b416d
{ "intermediate": 0.5426491498947144, "beginner": 0.19886787235736847, "expert": 0.258482962846756 }
5,449
I need an array formula that will search Column 'H' in Sheet 'SrvSrch' for dates that are 31 days before Today. Column 'H' contains date values and the column is formatted as Dates. Each match must then be displayed in a separate row of the same column in Sheet1 without spaces as dd-mm-yyyy for each of all the matches found along with the CONCATENATE the Values of Column 'J' and Column 'K' that are on the same row.There must be a double space between the CONCATENATED values.
cc9facca7ff77a7fab60e2e484b8e4fe
{ "intermediate": 0.4148711562156677, "beginner": 0.21459300816059113, "expert": 0.37053585052490234 }
5,450
A = np.array([[1,2,3] [4,5,6] [7,8,9]]) A.tolist().sort(key=A.tolist[i for i in range(A.tolist()) if (i+1)%4==1],reversed=True)
8519e6ed690eb62b725cda5e685f4da8
{ "intermediate": 0.35015246272087097, "beginner": 0.28708186745643616, "expert": 0.3627656102180481 }
5,451
act as an expert in python programming. I will ask questions.
893aa62ab56eeaed1a259b4a8c688b7f
{ "intermediate": 0.28015562891960144, "beginner": 0.33540791273117065, "expert": 0.3844364881515503 }
5,452
use JavaScript reander 10000 data, and create and insert table element
f96abfce7f3180def0fee4e52a1b7bb4
{ "intermediate": 0.547208309173584, "beginner": 0.22501657903194427, "expert": 0.2277752012014389 }
5,453
Please create react code that takes an image as input and from predetermined x and y coordinates passed down as properties, overlay a color that spread from said coordinates outward until they meet. This overlaying color should move in different speed depending on the color of the underlaying image, which will be a topographic map of a location. For example the image will be bright where the topography is flat which allow the overlay to spread quickly and darker where there is mountains and hills which will make the overlay move slower. Each set of coordinates will create one overlay, and when the overlays meet they will blend together creating one overlay to the eye.
55b5c8b42c42012dbfc57908274f27d1
{ "intermediate": 0.3445793688297272, "beginner": 0.14959196746349335, "expert": 0.5058286786079407 }
5,454
act as an expert in python language. I will ask questions about python script.
b4d406f0b5e9a4b9994f46f29906e3c7
{ "intermediate": 0.2258869856595993, "beginner": 0.5546274185180664, "expert": 0.21948562562465668 }
5,455
sa
2b784f857e373df8708e1888104326ba
{ "intermediate": 0.32281410694122314, "beginner": 0.3021789491176605, "expert": 0.3750069737434387 }
5,456
act as an expert in python programming. I will ask questions and you need to follow exactly what the instructions say.
f513516f87b93d9cfc35eca9bb5cef64
{ "intermediate": 0.3451356291770935, "beginner": 0.3839702904224396, "expert": 0.2708941102027893 }
5,457
hi
05145498742da46f61cd24c575d06884
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,458
i want to validate input component in react with regex,show me an example
8c15b0191efaae2e0c3501caef19027f
{ "intermediate": 0.6515113115310669, "beginner": 0.15381288528442383, "expert": 0.1946757584810257 }
5,459
hello
88667aad7df0c41482bf99981f8d57b1
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
5,460
why this script doesn't print do you want to play again input? import random class Card: def __init__(self, suit, number): self.suit = suit self.number = number def __str__(self): return f"{self.number} of {self.suit}" class Deck(): def __init__(self): self.cards = [] self.card_range = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"] self.suits = ["Diamonds", "Spades", "Hearts", "Clubs"] self.__build() def __build(self): for s in self.suits: for c in self.card_range: self.cards.append(Card(s, c)) def shuffle(self): random.shuffle(self.cards) def deal_a_card(self): return self.cards.pop() def card_value(card): if card.number == "Ace": return 11 elif card.number in ["Jack", "Queen", "King"]: return 10 else: return card.number def calculate_score(hand): score = sum(card_value(card) for card in hand) aces = [card for card in hand if card.number == "Ace"] while score > 21 and aces: aces.pop() score -= 10 return score def main(): deck = Deck() deck.shuffle() player_hand = [deck.deal_a_card(), deck.deal_a_card()] dealer_hand = [deck.deal_a_card(), deck.deal_a_card()] while True: player_score = calculate_score(player_hand) print(f"Player hand: {', '.join(map(str, player_hand))} - Score: {player_score}") print(f"Dealer hand: {dealer_hand[0]}, HIDDEN CARD") if player_score > 21: print(f" Busted with a score of {player_score}! Dealer wins.") break action = input("Do you want to hit or stand? (h or s)").lower() if action == "hit" or action == "h": player_hand.append(deck.deal_a_card()) elif action == "stand" or action == "s": while calculate_score(dealer_hand) < 17: dealer_hand.append(deck.deal_a_card()) dealer_score = calculate_score(dealer_hand) print(f"Player final hand: {', '.join(map(str, player_hand))} - Score: {player_score}") print(f"Dealer final hand: {', '.join(map(str, dealer_hand))} - Score: {dealer_score}") if dealer_score > 21 or player_score > dealer_score: print(" WINNER WINNER CHICKEN DINNER!") elif dealer_score == player_score: print(" IT'S A TIE!") else: print(" DEALER WINS! SAD FACE") break else: print("INVALID OPTION, PLEASE ENTER HIT OR STAND. (h or s)") choice = input("Do you want to play again? (y or n) ") if not choice.lower().startswith('y'): print("Good Bye") break if __name__ == "__main__": main()
e4767e128b12e0382930bc9db11f7cc4
{ "intermediate": 0.3317815661430359, "beginner": 0.48290425539016724, "expert": 0.18531417846679688 }
5,461
Вот код , добавь какой нибудь простенький функционал: package com.example.myapp_2; public class MyTask implements Runnable { @Override public void run() { // Логика задачи System.out.println("Task executed by thread " + Thread.currentThread().getName()); } } initView(view); // Создание пула потоков с 2 потоками ExecutorService executorService = Executors.newFixedThreadPool(2); // Создание двух задач Runnable task1 = new MyTask(); Runnable task2 = new MyTask(); // Запуск задач через пул потоков executorService.execute(task1); executorService.execute(task2); //создается пул с двумя потоками, создаются две задачи и запускаются через пул. // Каждая задача выполняется в своем потоке, и в консоль выводится имя каждого потока.
cfdc9520bbdd46b1f917e24ceb609cb5
{ "intermediate": 0.3973025679588318, "beginner": 0.3780643045902252, "expert": 0.22463318705558777 }
5,462
are you familiar with python scrapy?
628d4edc0579549f6dfe4ee3b2ada189
{ "intermediate": 0.3312941789627075, "beginner": 0.3196166157722473, "expert": 0.34908920526504517 }
5,463
Create a react component that takes an topographic image as input and from predetermined coordinates in the image show an overlay with a color that grow over time, but only after one of the overlays are clicked. They should be 30 pixels when you first load the page and they should all have different colors. This overlaying color should expand in different speed depending on the color of the underlaying image, which will be a topographic map of a location. For example the image will be bright where the topography is flat which allow the overlay to spread quickly and darker where there is mountains and hills which will make the overlay move slower. Each set of coordinates will create one overlay, and when the overlays meet they will blend together creating one overlay with the color red.
715e680f7169f623aed03407e5767929
{ "intermediate": 0.33155950903892517, "beginner": 0.29157617688179016, "expert": 0.37686431407928467 }
5,464
hi
f61f4034c2a47a080baf7428b0a3a298
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,465
import random import tkinter as tk def generate_random_number(): random_number = random.randint(1, 10) result_label.config(text=f"Random number is {random_number}“) root = tk.Tk() root.title(“Random Number Generator”) generate_button = tk.Button(root, text=“Generate Random Number”, command=generate_random_number) generate_button.pack(pady=10) result_label = tk.Label(root, text=”") result_label.pack() root.mainloop() u just did thta doe but its not working
3ff09a76d762edb35365da6b1a119760
{ "intermediate": 0.37756311893463135, "beginner": 0.364928662776947, "expert": 0.25750815868377686 }
5,466
Use JavaScript implementation data state manage
6a905f304237007006a7be2f4006dd21
{ "intermediate": 0.6451967358589172, "beginner": 0.1959068924188614, "expert": 0.158896341919899 }
5,467
Fivem scripting LUA I'm currently using GetInteriorAtCoords is there anyway that i can create the interior somewhere else?
fc726bfe3ef8e99ad814ac689fb442d2
{ "intermediate": 0.4678493142127991, "beginner": 0.27607545256614685, "expert": 0.2560751736164093 }
5,468
Где я ошибся в этом коде ? Исправь ошибки : package com.example.myapp_2; import com.example.myapp_2.UI.view.fragments.SecondFragment; private static class FactorialCalculator implements Runnable { private int number; private int result; private SecondFragment.Callback callback; public FactorialCalculator(int number) { this.number = number; } @Override public void run() { result = 1; for (int i = 2; i <= number; i++) { result *= i; } if (callback != null) { callback.onResult(result); } } public void setCallback(SecondFragment.Callback callback) { this.callback = callback; } } public interface Callback { void onResult(int result); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_second, container, false); inputEditText = v.findViewById(R.id.input_edit_text); resultTextView = v.findViewById(R.id.result_text_view); Button factorialButton = v.findViewById(R.id.factorial_button); factorialButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int number = Integer.parseInt(inputEditText.getText().toString()); FactorialCalculator calculator = new FactorialCalculator(number); calculator.setCallback(new Callback() { @Override public void onResult(int result) { resultTextView.setText(Integer.toString(result)); } }); new Thread(calculator).start(); } });
71af303cb20ce42339f7dafc8f1132dd
{ "intermediate": 0.445870041847229, "beginner": 0.3048584759235382, "expert": 0.24927152693271637 }
5,469
Flutter how to get widget property by key?
0ca4ea1dc6d873e339025abe0992e5c7
{ "intermediate": 0.49749264121055603, "beginner": 0.12302763015031815, "expert": 0.37947970628738403 }
5,470
Flutter 3.7. What are possible reasons that TextFormField default (without extra styles) font size is not using bodyMedium theme option?
3b691bd41f9dbcaa3d1b5763c0e4623b
{ "intermediate": 0.5816711783409119, "beginner": 0.21973316371440887, "expert": 0.19859568774700165 }
5,471
Android how to implement worker thorought dependenciece
a55913bb20f90cb981c105bfb5f9bb80
{ "intermediate": 0.5162627100944519, "beginner": 0.1728944480419159, "expert": 0.3108428716659546 }
5,472
implementation "androidx.work :work-runtime:$versions.work" дополни и исправь
e5bc51b666ff847497b6bdc8da41a004
{ "intermediate": 0.5717888474464417, "beginner": 0.21891775727272034, "expert": 0.20929333567619324 }
5,473
Create a react component that takes imageUrl and Coordinates as properties. The imageUrl should serve as a background to the component and each of the coordinates should create an overlay at the specific location on top of the image. Each of the overlays should be of a different color from this list Red, Blue, Orange, Green, Purple, Black When the component loads the first time, the overlay should not be changing size but instead wait for it to be clicked. When one of the overlays is clicked all the overlays start to grow. If the overlays meet they stop to grow until the last overlay meets another overlay.
c80f7425f835045584097f0c6b5206a0
{ "intermediate": 0.3404653072357178, "beginner": 0.29685038328170776, "expert": 0.3626842200756073 }
5,474
package com.example.myapp_2.UI.view.fragments; import static android.content.Context.MODE_PRIVATE; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import android.os.Handler; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Switch; 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 com.example.myapp_2.UI.view.adapters.SliderAdapter_2; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.fragment.app.Fragment; public class SecondFragment extends Fragment implements View.OnClickListener { private static final String MY_PREFS_NAME = "MyPrefs_2"; private RecyclerView recyclerView; private ProductAdapter productAdapter; private List<Product> products = getProducts(); 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; //private static final String MY_PREFS_NAME = "MyPrefs"; public SecondFragment() { } private ViewPager viewPager; private int[] imageUrls = {R.drawable.second_1, R.drawable.second_3, R.drawable.second_4, R.drawable.second_5, R.drawable.second_22}; private TextView textView; private EditText editText; private Button applyTextButton; private Button saveButton; private Switch switch1; public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "text"; public static final String SWITCH1 = "switch1"; private String text; private boolean switchOnOff; //private String text; //private boolean switchOnOff; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_second, container, false); 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("MyPrefs_2", 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(500.99); products.get(1).setPrice(720.99); products.get(2).setPrice(140.99); products.get(3).setPrice(220.99); products.get(4).setPrice(380.99); products.get(5).setPrice(105.99); products.get(6).setPrice(230.99); products.get(7).setPrice(170.99); products.get(8).setPrice(295.99); products.get(9).setPrice(235.99); viewPager = v.findViewById(R.id.view_pager); // SliderAdapter_2 adapter = new SliderAdapter_2(getActivity(), imageUrls); viewPager.setAdapter(adapter); 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 NotificationManager notificationManager; private static final int NOTIFY_ID = 1; private static final String CHANNEL_ID = "CHANNEL_ID"; Button b1; @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); b1 = view.findViewById(R.id.button); notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getContext(), SecondFragment.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder notification = new NotificationCompat.Builder(getContext().getApplicationContext(), CHANNEL_ID) .setAutoCancel(false) .setSmallIcon(R.drawable.ic_launcher_background) .setWhen(System.currentTimeMillis()) .setContentIntent(pendingIntent) .setContentTitle("zagolovok") .setContentText("tekst") .setPriority(NotificationCompat.PRIORITY_HIGH); createChannelIfNeeded(notificationManager); notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFY_ID, notification.build()); } }); } public void saveData() { SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TEXT, textView.getText().toString()); editor.putBoolean(SWITCH1, switch1.isChecked()); editor.apply(); Toast.makeText(getActivity(), "Data saved", Toast.LENGTH_SHORT).show(); } public void loadData() { SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE); text = sharedPreferences.getString(TEXT, ""); switchOnOff = sharedPreferences.getBoolean(SWITCH1, false); } public void updateViews() { //textView.setText(text); // switch1.setChecked(switchOnOff); } private void initView(View view) { Button btnClick = (Button) view.findViewById(R.id.btn_1_second_fragment); btnClick.setOnClickListener(this); Button btnClick2 = (Button) view.findViewById(R.id.btn_3_second_fragment); btnClick2.setOnClickListener(this); } private SharedPreferences.Editor editor; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); editor = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit(); 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(); // Загружаем данные из SharedPreferences loadData(); // Обновляем Views на экране updateViews(); } @Override public void onResume() { super.onResume(); } @Override public void onStop() { super.onStop(); 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 onDestroy() { super.onDestroy(); } private void changeFragment() { getFragmentManager().beginTransaction().replace(R.id.nav_container, new FirstFragment()).addToBackStack(null).commit(); } private void changeFragment2() { getFragmentManager().beginTransaction().replace(R.id.nav_container, new ThirdFragment()).addToBackStack(null).commit(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_1_second_fragment: changeFragment(); break; case R.id.btn_3_second_fragment: changeFragment2(); break; } } public static void createChannelIfNeeded(NotificationManager manager) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT); manager.createNotificationChannel(notificationChannel); } } private List<Product> getProducts() { List<Product> products = new ArrayList<>(); Product product1 = new Product("Product 11", "Description 11", R.drawable.food_1, 0.0f); products.add(product1); Product product2 = new Product("Product 12", "Description 12", R.drawable.food_2, 0.0f); products.add(product2); Product product3 = new Product("Product 13", "Description 13", R.drawable.food_1_3, 0.0f); products.add(product3); Product product4 = new Product("Product 14", "Description 14", R.drawable.food_1_2, 0.0f); products.add(product4); Product product5 = new Product("Product 15", "Description 15", R.drawable.food_3_4, 0.0f); products.add(product5); Product product6 = new Product("Product 16", "Description 16", R.drawable.food_1_4, 0.0f); products.add(product6); Product product7 = new Product("Product 17", "Description 17", R.drawable.food_1_1, 0.0f); products.add(product7); Product product8 = new Product("Product 18", "Description 18", R.drawable.food_1_2, 0.0f); products.add(product8); Product product9 = new Product("Product 19", "Description 19", R.drawable.food_3, 0.0f); products.add(product9); Product product10 = new Product("Product 20", "Description 20", R.drawable.food_3_4, 0.0f); products.add(product10); return products; } @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 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); 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); } } } Воспользуйся этим классом : package com.example.myapp_2; import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Worker; import androidx.work.WorkerParameters; import com.example.myapp_2.List_1.Product; import java.util.Collections; import java.util.List; public class SortWorker extends Worker { private List<Product> products; public SortWorker(@NonNull Context context, @NonNull WorkerParameters workerParams, List<Product> products) { super(context, workerParams); this.products = products; } @Override public Result doWork() { sortProducts(); return Result.success(); } private void sortProducts() { Collections.sort(products, (p1, p2) -> Double.compare(p1.getPrice(), p2.getPrice()) > 0 ? 1 : -1); } } (Отсортируй товары с помощью класса SortWorker )
b15a1cd5b40d53623ef355ad0e917697
{ "intermediate": 0.34006747603416443, "beginner": 0.36487093567848206, "expert": 0.2950616180896759 }
5,475
Joi.object({ occupation: Joi.string().allow(null), declarations: Joi.object({ industryType: Joi.when('occupation', { is: Joi.valid('housewife', 'unemployed'), then: Joi.string().pattern(/^null$/).message('industryType cannot contains characters'), otherwise: Joi.string().valid('Advertising').required(), }), }) })
4766d1436cbd50452ab95d67aa07338d
{ "intermediate": 0.3345617949962616, "beginner": 0.35965976119041443, "expert": 0.30577850341796875 }
5,476
Given this code "import React, { useState } from "react"; const colors = ["red", "blue", "orange", "green", "purple", "black"]; function ComponentWithOverlays(props) { const { imageUrl, coordinates } = props; const [activeIndex, setActiveIndex] = useState(null); const [shouldGrow, setShouldGrow] = useState(false); const overlayClicked = (index) => { setActiveIndex(index); setShouldGrow(true); }; const getOverlayStyle = (index) => { const { x, y } = coordinates[index]; const active = activeIndex === index; const grow = shouldGrow; const overlayStyle = { position: "absolute", left: `${x}px`, top: `${y}px`, width: "30px", height: "30px", borderRadius: "50%", backgroundColor: colors[index % colors.length], zIndex: 1, transition: "all 0.3s ease-in-out", cursor: "pointer", }; if (active || grow) { const size = active ? 100 : 200; const offset = (200 - 10) / 2; overlayStyle.width = `${size}px`; overlayStyle.height = `${size}px`; overlayStyle.left = `${x - offset}px`; overlayStyle.top = `${y - offset}px`; } return overlayStyle; }; return ( <div style={{ backgroundImage: `url(${imageUrl})`, backgroundPosition: "center", backgroundSize: "cover", height: "500px", position: "relative", }} > {Array.isArray(coordinates) && coordinates.map((_, index) => ( <div key={index} style={getOverlayStyle(index)} onClick={() => overlayClicked(index)} /> ))} </div> ); } export default ComponentWithOverlays;" Modify it so that all overlays grow when any of the overlays are clicked
9e6eb64c414bacec1730ba6a7b746709
{ "intermediate": 0.4406268000602722, "beginner": 0.3099345266819, "expert": 0.24943870306015015 }
5,477
Вот код , отсортируй список товаров в SecondFragment : @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_second, container, false); ProductAdapter adapter_2 = new ProductAdapter(); SortWorker sortWorker = new SortWorker(this, new WorkerParameters.Builder().build(), adapter_2); sortWorker.doWork();package com.example.myapp_2; import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Worker; import androidx.work.WorkerParameters; import com.example.myapp_2.List_1.Product; import com.example.myapp_2.List_1.ProductAdapter; import java.util.Collections; import java.util.List; public class SortWorker extends Worker { private ProductAdapter adapter; public SortWorker(@NonNull Context context, @NonNull WorkerParameters workerParams, ProductAdapter adapter) { super(context, workerParams); this.adapter = adapter; } @Override public Result doWork() { sortProducts(); return Result.success(); } private void sortProducts() { List<Product> products = adapter.getProducts(); Collections.sort(products, (p1, p2) -> Double.compare(p1.getPrice(), p2.getPrice()) > 0 ? 1 : -1); adapter.notifyDataSetChanged(); } }package com.example.myapp_2.List_1; public class Product { private String name; private String description; private int imageResource; private float rating; private double price; public Product(String name, String description, int imageResource, float rating, double price) { this.name = name; this.description = description; this.imageResource = imageResource; this.rating = rating; this.price = price; } public Product(String name, String description, int imageResource, double price) { this.name = name; this.description = description; this.imageResource = imageResource; this.rating = 0.0f; this.price = price; } public String getName() { return name; } public String getDescription() { return description; } public int getImageResource() { return imageResource; } public float getRating() { return rating; } public void setRating(float rating) { this.rating = rating; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } (Исправь методы при необходимости и помни что твоя задача используя эти класса отсортировать по цене товары в SecondFragment)
71a54b89167605e811a674f8dc2e85ed
{ "intermediate": 0.2666413486003876, "beginner": 0.5459108948707581, "expert": 0.18744778633117676 }
5,478
tell me the most popular programming language in 2023
c1e40a6d70874993eb3f0476f2c6a6da
{ "intermediate": 0.22048905491828918, "beginner": 0.3227182626724243, "expert": 0.4567926228046417 }
5,479
// Get the user input for trade size tradeSize = input.float(title='Trade Size', defval=0.2, minval=0.01, step = 0.01) // Calculate stop loss and take profit levels based on trade size stopLoss = tradeSize * 0.2 takeProfit20 = tradeSize * 0.2 takeProfit40 = tradeSize * 0.4 takeProfit60 = tradeSize * 0.6 takeProfit80 = tradeSize * 0.8 takeProfit100 = tradeSize takeProfit120 = tradeSize * 1.2 takeProfit140 = tradeSize * 1.4 // Define long and short conditions longCondition = (ipush==fib1) shortCondition = (ipush==fib0) // Enter long trade when long condition is met if (longCondition) strategy.entry('Long Entry', strategy.long, qty=tradeSize, stop=stopLoss, limit=(close + takeProfit20)) // Enter short trade when short condition is met if (shortCondition) strategy.entry('Short Entry', strategy.short, qty=tradeSize, stop=stopLoss, limit=(close - takeProfit20)) // Exit trade at take profit and adjust stop loss levels if (strategy.position_size > 0) if (strategy.position_avg_price + takeProfit20 <= close) strategy.exit('Take Profit 20', qty=tradeSize, limit=(close - takeProfit40), stop=(strategy.position_avg_price + stopLoss)) else strategy.exit('Stop Loss 20', qty=tradeSize, stop=(strategy.position_avg_price - stopLoss)) // if(strategy.position_size > 0) if (strategy.position_avg_price + takeProfit40 <= close) strategy.exit('Take Profit 40', qty=tradeSize, limit=(close - takeProfit60), stop=(strategy.position_avg_price + takeProfit20)) else strategy.exit('Stop Loss 40', qty=tradeSize, stop=(strategy.position_avg_price - takeProfit20)) // if (strategy.position_size > 0) if (strategy.position_avg_price + takeProfit60 <= close) strategy.exit('Take Profit 60', qty=tradeSize, limit=(close - takeProfit80), stop=(strategy.position_avg_price + takeProfit40)) else strategy.exit('Stop Loss 60', qty=tradeSize, stop=(strategy.position_avg_price - takeProfit40)) // if (strategy.position_size > 0) if (strategy.position_avg_price + takeProfit80 <= close) strategy.exit('Take Profit 80', qty=tradeSize, limit=(close - takeProfit100), stop=(strategy.position_avg_price + takeProfit60)) else strategy.exit('Stop Loss 80', qty=tradeSize, stop=(strategy.position_avg_price - takeProfit60)) // if (strategy.position_size > 0) if (strategy.position_avg_price + takeProfit100 <= close) strategy.exit('Take Profit 100', qty=tradeSize, limit=(close - takeProfit120), stop=(strategy.position_avg_price + takeProfit80)) else strategy.exit('Stop Loss 100', qty=tradeSize, stop=(strategy.position_avg_price - takeProfit80)) // if (strategy.position_size > 0) if (strategy.position_avg_price + takeProfit120 <= close) strategy.exit('Take Profit 120', qty=tradeSize, limit=(close - takeProfit140), stop=(strategy.position_avg_price + takeProfit100)) else strategy.exit('Stop Loss 120', qty=tradeSize, stop=(strategy.position_avg_price - takeProfit100))
ebe81b32e255ba9f0bf7ecc0169f8a0e
{ "intermediate": 0.24337519705295563, "beginner": 0.5153504610061646, "expert": 0.24127428233623505 }
5,480
<script type="text/javascript"> Dropzone.autoDiscover = false; $(document).ready(function() { // Initialize the dropzone element $("#my-dropzone").dropzone({ url: "/localization/multi-local-from-file", addRemoveLinks: true paramName: "data", maxFiles: 1, maxFilesize: 10, // Maximum filesize in MB acceptedFiles: ".arb", init: function() { this.on("success", function(file, response) { // On successful translation, enable the download button and change the download link $("#download-multiple").prop("href", URL.createObjectURL(response)); $("#download-multiple").prop("disabled", false); }); } }); }); </script>
548c90bc9cfd76bad4e82882fa076252
{ "intermediate": 0.3616120517253876, "beginner": 0.4476749300956726, "expert": 0.19071301817893982 }
5,481
c# how to cast a parent to childobject
026178a6a2b9bb4c5399fa935513b47a
{ "intermediate": 0.47432589530944824, "beginner": 0.23599863052368164, "expert": 0.2896755039691925 }
5,482
write a freshdesk custom app which shows a google map with a marker and a search box on top. upon typing in the search box. it makes a custom api call and list down address suggestions from the custom api response. Then on clicking the address from the list, it makes a function call to change the marker's position to that address's lat, long
c6faf8c4a88fdd28c2d0f3b62b5be94b
{ "intermediate": 0.4321865141391754, "beginner": 0.22860196232795715, "expert": 0.33921152353286743 }
5,483
how to show a toast in compose
b16a961a58e6d73d38a0a80fcda7e375
{ "intermediate": 0.405451238155365, "beginner": 0.3488226532936096, "expert": 0.24572618305683136 }
5,484
Cannot resolve symbol 'Builder' : package com.example.myapp_2.UI.view.fragments; import static android.content.Context.MODE_PRIVATE; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import androidx.work.WorkerParameters; 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.SortWorker; import com.example.myapp_2.UI.view.adapters.SliderAdapter; import java.util.ArrayList; import java.util.List; //import androidx.work.WorkerParameters.Builder; public class SecondFragment extends Fragment implements View.OnClickListener { private static final String MY_PREFS_NAME = "MyPrefs_2"; private RecyclerView recyclerView; private ProductAdapter productAdapter; private List<Product> products = getProducts(); 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; //private static final String MY_PREFS_NAME = "MyPrefs"; public SecondFragment() { } private ViewPager viewPager; private int[] imageUrls = {R.drawable.second_1, R.drawable.second_3, R.drawable.second_4, R.drawable.second_5, R.drawable.second_22}; private TextView textView; private EditText editText; private Button applyTextButton; private Button saveButton; private Switch switch1; public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "text"; public static final String SWITCH1 = "switch1"; private String text; private boolean switchOnOff; //private String text; //private boolean switchOnOff; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_second, container, false); // private RecyclerView recyclerView; // private ProductAdapter productAdapter; // private List<Product> products = getProducts(); // создаем объект SortWorker и вызываем метод сортировки SortWorker sortWorker = new SortWorker(getActivity(), new WorkerParameters.Builder().build(), productAdapter); sortWorker.sortProducts(); // устанавливаем адаптер для отображения списка товаров RecyclerView recyclerView = v.findViewById(R.id.recycler_view_products); recyclerView.setAdapter(productAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); 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("MyPrefs_2", 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(500.99); products.get(1).setPrice(720.99); products.get(2).setPrice(140.99); products.get(3).setPrice(220.99); products.get(4).setPrice(380.99); products.get(5).setPrice(105.99); products.get(6).setPrice(230.99); products.get(7).setPrice(170.99); products.get(8).setPrice(295.99); products.get(9).setPrice(235.99); viewPager = v.findViewById(R.id.view_pager); // SliderAdapter_2 adapter = new SliderAdapter_2(getActivity(), imageUrls); viewPager.setAdapter(adapter); 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 NotificationManager notificationManager; private static final int NOTIFY_ID = 1; private static final String CHANNEL_ID = "CHANNEL_ID"; Button b1; @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); b1 = view.findViewById(R.id.button); notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getContext(), SecondFragment.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder notification = new NotificationCompat.Builder(getContext().getApplicationContext(), CHANNEL_ID) .setAutoCancel(false) .setSmallIcon(R.drawable.ic_launcher_background) .setWhen(System.currentTimeMillis()) .setContentIntent(pendingIntent) .setContentTitle("zagolovok") .setContentText("tekst") .setPriority(NotificationCompat.PRIORITY_HIGH); createChannelIfNeeded(notificationManager); notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFY_ID, notification.build()); } }); } public void saveData() { SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TEXT, textView.getText().toString()); editor.putBoolean(SWITCH1, switch1.isChecked()); editor.apply(); Toast.makeText(getActivity(), "Data saved", Toast.LENGTH_SHORT).show(); } public void loadData() { SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE); text = sharedPreferences.getString(TEXT, ""); switchOnOff = sharedPreferences.getBoolean(SWITCH1, false); } public void updateViews() { //textView.setText(text); // switch1.setChecked(switchOnOff); } private void initView(View view) { Button btnClick = (Button) view.findViewById(R.id.btn_1_second_fragment); btnClick.setOnClickListener(this); Button btnClick2 = (Button) view.findViewById(R.id.btn_3_second_fragment); btnClick2.setOnClickListener(this); } private SharedPreferences.Editor editor; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); editor = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit(); 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(); // Загружаем данные из SharedPreferences loadData(); // Обновляем Views на экране updateViews(); } @Override public void onResume() { super.onResume(); } @Override public void onStop() { super.onStop(); 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 onDestroy() { super.onDestroy(); } private void changeFragment() { getFragmentManager().beginTransaction().replace(R.id.nav_container, new FirstFragment()).addToBackStack(null).commit(); } private void changeFragment2() { getFragmentManager().beginTransaction().replace(R.id.nav_container, new ThirdFragment()).addToBackStack(null).commit(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_1_second_fragment: changeFragment(); break; case R.id.btn_3_second_fragment: changeFragment2(); break; } } public static void createChannelIfNeeded(NotificationManager manager) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT); manager.createNotificationChannel(notificationChannel); } } @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 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); 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 List<Product> getProducts() { List<Product> products = new ArrayList<>(); Product product1 = new Product("Product 11", "Description 11", R.drawable.food_1, 0.0f); products.add(product1); Product product2 = new Product("Product 12", "Description 12", R.drawable.food_2, 0.0f); products.add(product2); Product product3 = new Product("Product 13", "Description 13", R.drawable.food_1_3, 0.0f); products.add(product3); Product product4 = new Product("Product 14", "Description 14", R.drawable.food_1_2, 0.0f); products.add(product4); Product product5 = new Product("Product 15", "Description 15", R.drawable.food_3_4, 0.0f); products.add(product5); Product product6 = new Product("Product 16", "Description 16", R.drawable.food_1_4, 0.0f); products.add(product6); Product product7 = new Product("Product 17", "Description 17", R.drawable.food_1_1, 0.0f); products.add(product7); Product product8 = new Product("Product 18", "Description 18", R.drawable.food_1_2, 0.0f); products.add(product8); Product product9 = new Product("Product 19", "Description 19", R.drawable.food_3, 0.0f); products.add(product9); Product product10 = new Product("Product 20", "Description 20", R.drawable.food_3_4, 0.0f); products.add(product10); return products; } }
94a94986bb549cbc2c5c6cad783346cd
{ "intermediate": 0.27253803610801697, "beginner": 0.4675254821777344, "expert": 0.25993651151657104 }
5,485
u know how :deep works in vue 3?
a8d530afff2ee61a2999bab091bb4512
{ "intermediate": 0.30447787046432495, "beginner": 0.08015616238117218, "expert": 0.6153659224510193 }
5,486
Cannot resolve symbol 'Builder' : package com.example.myapp_2.UI.view.fragments; import static android.content.Context.MODE_PRIVATE; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; import androidx.work.WorkerParameters; 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.SortWorker; import com.example.myapp_2.UI.view.adapters.SliderAdapter; import java.util.ArrayList; import java.util.List; //import androidx.work.WorkerParameters.Builder; import androidx.core.app.NotificationCompat.Builder; public class SecondFragment extends Fragment implements View.OnClickListener { private static final String MY_PREFS_NAME = "MyPrefs_2"; private RecyclerView recyclerView; private ProductAdapter productAdapter; private List<Product> products = getProducts(); 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; //private static final String MY_PREFS_NAME = "MyPrefs"; public SecondFragment() { } private ViewPager viewPager; private int[] imageUrls = {R.drawable.second_1, R.drawable.second_3, R.drawable.second_4, R.drawable.second_5, R.drawable.second_22}; private TextView textView; private EditText editText; private Button applyTextButton; private Button saveButton; private Switch switch1; public static final String SHARED_PREFS = "sharedPrefs"; public static final String TEXT = "text"; public static final String SWITCH1 = "switch1"; private String text; private boolean switchOnOff; //private String text; //private boolean switchOnOff; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_second, container, false); // private RecyclerView recyclerView; // private ProductAdapter productAdapter; // private List<Product> products = getProducts(); // создаем объект SortWorker и вызываем метод сортировки SortWorker sortWorker = new SortWorker(getActivity(), new WorkerParameters.Builder().build(), productAdapter); sortWorker.sortProducts(); // устанавливаем адаптер для отображения списка товаров RecyclerView recyclerView = v.findViewById(R.id.recycler_view_products); recyclerView.setAdapter(productAdapter); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); 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("MyPrefs_2", 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(500.99); products.get(1).setPrice(720.99); products.get(2).setPrice(140.99); products.get(3).setPrice(220.99); products.get(4).setPrice(380.99); products.get(5).setPrice(105.99); products.get(6).setPrice(230.99); products.get(7).setPrice(170.99); products.get(8).setPrice(295.99); products.get(9).setPrice(235.99); viewPager = v.findViewById(R.id.view_pager); // SliderAdapter_2 adapter = new SliderAdapter_2(getActivity(), imageUrls); viewPager.setAdapter(adapter); 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 NotificationManager notificationManager; private static final int NOTIFY_ID = 1; private static final String CHANNEL_ID = "CHANNEL_ID"; Button b1; @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initView(view); b1 = view.findViewById(R.id.button); notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(getContext(), SecondFragment.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder notification = new NotificationCompat.Builder(getContext().getApplicationContext(), CHANNEL_ID) .setAutoCancel(false) .setSmallIcon(R.drawable.ic_launcher_background) .setWhen(System.currentTimeMillis()) .setContentIntent(pendingIntent) .setContentTitle("zagolovok") .setContentText("tekst") .setPriority(NotificationCompat.PRIORITY_HIGH); createChannelIfNeeded(notificationManager); notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFY_ID, notification.build()); } }); } public void saveData() { SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TEXT, textView.getText().toString()); editor.putBoolean(SWITCH1, switch1.isChecked()); editor.apply(); Toast.makeText(getActivity(), "Data saved", Toast.LENGTH_SHORT).show(); } public void loadData() { SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE); text = sharedPreferences.getString(TEXT, ""); switchOnOff = sharedPreferences.getBoolean(SWITCH1, false); } public void updateViews() { //textView.setText(text); // switch1.setChecked(switchOnOff); } private void initView(View view) { Button btnClick = (Button) view.findViewById(R.id.btn_1_second_fragment); btnClick.setOnClickListener(this); Button btnClick2 = (Button) view.findViewById(R.id.btn_3_second_fragment); btnClick2.setOnClickListener(this); } private SharedPreferences.Editor editor; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); editor = getContext().getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE).edit(); 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(); // Загружаем данные из SharedPreferences loadData(); // Обновляем Views на экране updateViews(); } @Override public void onResume() { super.onResume(); } @Override public void onStop() { super.onStop(); 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 onDestroy() { super.onDestroy(); } private void changeFragment() { getFragmentManager().beginTransaction().replace(R.id.nav_container, new FirstFragment()).addToBackStack(null).commit(); } private void changeFragment2() { getFragmentManager().beginTransaction().replace(R.id.nav_container, new ThirdFragment()).addToBackStack(null).commit(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_1_second_fragment: changeFragment(); break; case R.id.btn_3_second_fragment: changeFragment2(); break; } } public static void createChannelIfNeeded(NotificationManager manager) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT); manager.createNotificationChannel(notificationChannel); } } @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 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); 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 List<Product> getProducts() { List<Product> products = new ArrayList<>(); Product product1 = new Product("Product 11", "Description 11", R.drawable.food_1, 0.0f); products.add(product1); Product product2 = new Product("Product 12", "Description 12", R.drawable.food_2, 0.0f); products.add(product2); Product product3 = new Product("Product 13", "Description 13", R.drawable.food_1_3, 0.0f); products.add(product3); Product product4 = new Product("Product 14", "Description 14", R.drawable.food_1_2, 0.0f); products.add(product4); Product product5 = new Product("Product 15", "Description 15", R.drawable.food_3_4, 0.0f); products.add(product5); Product product6 = new Product("Product 16", "Description 16", R.drawable.food_1_4, 0.0f); products.add(product6); Product product7 = new Product("Product 17", "Description 17", R.drawable.food_1_1, 0.0f); products.add(product7); Product product8 = new Product("Product 18", "Description 18", R.drawable.food_1_2, 0.0f); products.add(product8); Product product9 = new Product("Product 19", "Description 19", R.drawable.food_3, 0.0f); products.add(product9); Product product10 = new Product("Product 20", "Description 20", R.drawable.food_3_4, 0.0f); products.add(product10); return products; } }
577c5733a985b1d3a5267851c2ffb5d5
{ "intermediate": 0.33326005935668945, "beginner": 0.5222734212875366, "expert": 0.14446650445461273 }
5,487
import java.rmi.Naming; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.*; import java.util.List; import java.util.Map; public class JavaApplication60 { public class EncyclopediaServiceImpl extends UnicastRemoteObject implements EncyclopediaService { private List<String> encyclopedia; public EncyclopediaServiceImpl() throws RemoteException { super(); encyclopedia = generateRandomData(300); } private List<String> generateRandomData(int numWords) { List<String> words = new ArrayList<>(); Random random = new Random(); for (int i = 0; i < numWords; i++) { int wordLength = random.nextInt(10) + 1; // Random word length between 1 and 10 characters StringBuilder word = new StringBuilder(); for (int j = 0; j < wordLength; j++) { char c = (char) (random.nextInt(26) + 'a'); // Random lowercase letter word.append(c); } words.add(word.toString()); } return words; } @Override public int count() { int letterCount = 0; for (String word : encyclopedia) { letterCount += word.length(); } return letterCount; } @Override public List<String> repeatedWords() { Set<String> uniqueWords = new HashSet<>(); List<String> repeatedWords = new ArrayList<>(); for (String word : encyclopedia) { if (!uniqueWords.add(word)) { repeatedWords.add(word); } } return repeatedWords; } @Override public String longest() { String longestWord = ""; for (String word : encyclopedia) { if (word.length() > longestWord.length()) { longestWord = word; } } return longestWord; } @Override public String shortest() { String shortestWord = ""; if (!encyclopedia.isEmpty()) { shortestWord = encyclopedia.get(0); for (String word : encyclopedia) { if (word.length() < shortestWord.length()) { shortestWord = word; } } } return shortestWord; } @Override public Map<String, Integer> repeat() { Map<String, Integer> wordCount = new HashMap<>(); for (String word : encyclopedia) { wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); } return wordCount; } @Override public List<String> getData() { return null; } } /** * * @param args */ /** * * @author ismai */ public interface EncyclopediaService extends Remote { int count() throws RemoteException; List<String> repeatedWords() throws RemoteException; String longest() throws RemoteException; String shortest() throws RemoteException; Map<String, Integer> repeat() throws RemoteException; List<String> getData(); } public static void main(String[] args) { try { EncyclopediaService service; // Create an instance of the class service = new EncyclopediaServiceImpl(); Naming.rebind("//localhost/encyclopedia", service); System.out.println("Encyclopedia service bound and ready to use."); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(); } } } EncyclopediaService service = new EncyclopediaServiceImpl(); Error: Uncompilable code - non-static variable this cannot be referenced from a static context java.lang.RuntimeException: Uncompilable code - non-static variable this cannot be referenced from a static context at javaapplication60.JavaApplication60.main(JavaApplication60.java:1) Solve this error for me
373d980cc2aebe4c1b11e1dcb8e68756
{ "intermediate": 0.2925994098186493, "beginner": 0.5292859673500061, "expert": 0.1781146228313446 }
5,488
SortWorker sortWorker = new SortWorker(getActivity(), new WorkerParameters.Builder().build(), productAdapter); : Cannot resolve symbol 'Builder'
d964929d73af1b534edbd046f03ae042
{ "intermediate": 0.600253164768219, "beginner": 0.17795993387699127, "expert": 0.22178694605827332 }
5,489
hi
c3ddf4f4da38de256bf5a0bbe81218ac
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,490
hi
0f58e434c9f8decb0512e2b0f8947124
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,491
Hello!
b42b32436a8fe4b2ce3c05956154dd43
{ "intermediate": 0.3194829821586609, "beginner": 0.26423266530036926, "expert": 0.41628435254096985 }
5,492
how to put the validation error in a message in the forms.py
249cb88a5644b2ee51fc441145153a34
{ "intermediate": 0.3804260492324829, "beginner": 0.21489764750003815, "expert": 0.404676228761673 }
5,493
Provide actual python tones for this. Make a 4 piece 30 second song for the violin, viola, cello, and bass. The song should start out calm, but after 15 seconds or so, the violas grow from soft to loud playing the C string. After one measure of holding the C. The piece grows extremely loud and turns into an epic song till the end of the song where everyone plays the G string.
ad274148d1ebe96d3169824251c610ae
{ "intermediate": 0.34116607904434204, "beginner": 0.18259960412979126, "expert": 0.4762343466281891 }
5,494
file zilla fix Status: Logged in Status: Retrieving directory listing of "/"... then 20 inactityi then failed tot connect
0c267066b10ec5b7ff1246a09d5161a2
{ "intermediate": 0.3750271797180176, "beginner": 0.26101431250572205, "expert": 0.36395853757858276 }
5,495
Для сортировки продуктов в SecondFragment необходимо вызвать метод sortProducts() класса SortWorker, который отсортирует список продуктов по цене в порядке возрастания. Для этого следует создать объект SortWorker и передать ему адаптер списка продуктов productAdapter. Далее вызвать метод enqueue() у объекта WorkManager с передачей в параметре созданного объекта SortWorker: SortWorker worker = new SortWorker(getContext(), workerParams, productAdapter); WorkManager.getInstance(getContext()) .beginUniqueWork(“SortProducts”, ExistingWorkPolicy.REPLACE, worker) .enqueue();
8245804cc0f3ef7cb49f2cc2ebe1f135
{ "intermediate": 0.4482455849647522, "beginner": 0.35379326343536377, "expert": 0.19796118140220642 }
5,496
Actúa como un programador experto en algoritmos de reinforcement learning. Ahora revisa exhaustivamente el siguiente código de python en el que se implementa un algoritmo Actor-Critic para entrenar un agente en el ambiente Pendulum de gym y dime si están bien implementados los métodos _select_action_continuous() y _compute_actor_loss_continuous() o si debo cambiar algo más en el código, pues durante el entrenamiento no logro aumentar la recompensa promedio. En cambio, cuando uso un ambiente con acciones discretas como "CartPole" sí funciona bien el entrenamiento. Aquí está el código: import torch import torch.nn as nn import gym import time import datetime import csv import numpy as np import matplotlib.pyplot as plt class Actor(nn.Module): def __init__(self, dim_states, dim_actions, continuous_control): super(Actor, self).__init__() # MLP, fully connected layers, ReLU activations, linear ouput activation # dim_states -> 64 -> 64 -> dim_actions self.layer1 = nn.Linear(dim_states, 64) self.layer2 = nn.Linear(64, 64) self.layer3 = nn.Linear(64, dim_actions) if continuous_control: # trainable parameter self._log_std = nn.Parameter(torch.zeros(1, dim_actions)) def forward(self, input): input = nn.functional.relu(self.layer1(input)) input = nn.functional.relu(self.layer2(input)) input = self.layer3(input) return input class Critic(nn.Module): def __init__(self, dim_states): super(Critic, self).__init__() # MLP, fully connected layers, ReLU activations, linear ouput activation # dim_states -> 64 -> 64 -> 1 self.layer1 = nn.Linear(dim_states, 64) self.layer2 = nn.Linear(64, 64) self.layer3 = nn.Linear(64, 1) def forward(self, input): input = nn.functional.relu(self.layer1(input)) input = nn.functional.relu(self.layer2(input)) input = self.layer3(input) return input class ActorCriticAgent: def __init__(self, dim_states, dim_actions, actor_lr, critic_lr, gamma, continuous_control=False): self._actor_lr = actor_lr self._critic_lr = critic_lr self._gamma = gamma self._dim_states = dim_states self._dim_actions = dim_actions self._continuous_control = continuous_control self._actor = Actor(self._dim_states, self._dim_actions, self._continuous_control) # Adam optimizer self._actor_optimizer = torch.optim.Adam(self._actor.parameters(), lr=self._actor_lr) self._critic = Critic(self._dim_states) # Adam optimizer self._critic_optimizer = torch.optim.Adam(self._critic.parameters(), lr=self._critic_lr) self._select_action = self._select_action_continuous if self._continuous_control else self._select_action_discrete self._compute_actor_loss = self._compute_actor_loss_continuous if self._continuous_control else self._compute_actor_loss_discrete def select_action(self, observation): return self._select_action(observation) def _select_action_discrete(self, observation): # sample from categorical distribution with torch.no_grad(): observation = torch.from_numpy(observation).float() logits = self._actor(observation) dist = torch.distributions.Categorical(logits=logits) action = dist.sample() return action.item() def _select_action_continuous(self, observation): # sample from normal distribution # use the log std trainable parameter with torch.no_grad(): observation = torch.from_numpy(observation).float() mean = self._actor(observation) std = self._actor._log_std.exp() normal = torch.distributions.Normal(mean, std) action = normal.sample() return action.numpy()[0] def _compute_actor_loss_discrete(self, observation_batch, action_batch, advantage_batch): # use negative logprobs * advantages logits = self._actor(observation_batch) dist = torch.distributions.Categorical(logits=logits) log_prob = dist.log_prob(action_batch) actor_loss = -(log_prob * advantage_batch).mean() return actor_loss def _compute_actor_loss_continuous(self, observation_batch, action_batch, advantage_batch): # use negative logprobs * advantages mean = self._actor(observation_batch) std = self._actor._log_std.exp() normal = torch.distributions.Normal(mean, std) log_probs = normal.log_prob(action_batch).squeeze() actor_loss = -(log_probs * advantage_batch).mean() return actor_loss def _compute_critic_loss(self, observation_batch, reward_batch, next_observation_batch, done_batch): # minimize mean((r + gamma * V(s_t1) - V(s_t))^2) q_values = self._critic(observation_batch).squeeze() next_q_values = self._critic(next_observation_batch).squeeze() expected_q_values = reward_batch + self._gamma * next_q_values * (1 - done_batch) critic_loss = nn.functional.mse_loss(q_values, expected_q_values) return critic_loss def update_actor(self, observation_batch, action_batch, reward_batch, next_observation_batch, done_batch): # compute the advantages using the critic and update the actor parameters # use self._compute_actor_loss observation_tensor = torch.from_numpy(observation_batch).float() action_tensor = torch.from_numpy(action_batch).float() reward_tensor = torch.from_numpy(reward_batch).float() next_observation_tensor = torch.from_numpy(next_observation_batch).float() done_tensor = torch.from_numpy(done_batch).float() q_values = self._critic(observation_tensor).squeeze() next_q_values = self._critic(next_observation_tensor).squeeze() expected_q_values = reward_tensor + self._gamma * next_q_values * (1 - done_tensor) advantage_tensor = expected_q_values - q_values actor_loss = self._compute_actor_loss(observation_tensor, action_tensor, advantage_tensor) self._actor_optimizer.zero_grad() actor_loss.backward() self._actor_optimizer.step() def update_critic(self, observation_batch, reward_batch, next_observation_batch, done_batch): # update the critic # use self._compute_critic_loss observation_tensor = torch.from_numpy(observation_batch).float() reward_tensor = torch.from_numpy(reward_batch).float() next_observation_tensor = torch.from_numpy(next_observation_batch).float() done_tensor = torch.from_numpy(done_batch).float() critic_loss = self._compute_critic_loss(observation_tensor, reward_tensor, next_observation_tensor, done_tensor) self._critic_optimizer.zero_grad() critic_loss.backward() self._critic_optimizer.step() def perform_single_rollout(env, agent, render=False): # Modify this function to return a tuple of numpy arrays containing: # (np.array(obs_t), np.array(acs_t), np.arraw(rew_t), np.array(obs_t1), np.array(done_t)) # np.array(obs_t) -> shape: (time_steps, nb_obs) # np.array(obs_t1) -> shape: (time_steps, nb_obs) # np.array(acs_t) -> shape: (time_steps, nb_acs) if actions are continuous, (time_steps,) if actions are discrete # np.array(rew_t) -> shape: (time_steps,) # np.array(done_t) -> shape: (time_steps,) obs_t = env.reset() done = False episode_reward = 0 nb_steps = 0 obs_t_list, acs_t_list, rew_t_list, obs_t1_list, done_t_list = [], [], [], [], [] while not done: if render: env.render() time.sleep(1. / 60) action = agent.select_action(obs_t) obs_t1, reward, done, _ = env.step(action) obs_t = np.squeeze(obs_t) obs_t1 = np.squeeze(obs_t1) obs_t_list.append(obs_t) acs_t_list.append(action) rew_t_list.append(reward) obs_t1_list.append(obs_t1) done_t_list.append(done) obs_t = obs_t1 episode_reward += reward nb_steps += 1 if done: return np.array(obs_t_list), np.array(acs_t_list), np.array(rew_t_list), np.array(obs_t1_list), np.array(done_t_list) def sample_rollouts(env, agent, training_iter, min_batch_steps): sampled_rollouts = [] total_nb_steps = 0 episode_nb = 0 while total_nb_steps < min_batch_steps: episode_nb += 1 render = 2 == 0 and len(sampled_rollouts) == 0 # Use perform_single_rollout to get data # Uncomment once perform_single_rollout works. # Return sampled_rollouts sample_rollout = perform_single_rollout(env, agent, render=render) total_nb_steps += len(sample_rollout[0]) sampled_rollouts.append(sample_rollout) return sampled_rollouts def train_agent(env, agent, training_iterations, min_batch_steps, nb_critic_updates): tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec = [], [], [], [] _, (axes) = plt.subplots(1, 2, figsize=(12,4)) for tr_iter in range(training_iterations + 1): # Sample rollouts using sample_rollouts sampled_rollouts = sample_rollouts(env, agent, tr_iter, min_batch_steps) # performed_batch_steps >= min_batch_steps # Parse samples into the following arrays: sampled_obs_t = np.concatenate([rollout[0] for rollout in sampled_rollouts]) # sampled_obs_t: Numpy array, shape: (performed_batch_steps, nb_observations) sampled_acs_t = np.concatenate([rollout[1] for rollout in sampled_rollouts]) # sampled_acs: Numpy array, shape: (performed_batch_steps, nb_actions) if actions are continuous, # (performed_batch_steps,) if actions are discrete sampled_rew_t = np.concatenate([rollout[2] for rollout in sampled_rollouts]) # sampled_rew_t: Numpy array, shape: (performed_batch_steps,) sampled_obs_t1 = np.concatenate([rollout[3] for rollout in sampled_rollouts]) # sampled_obs_t1: Numpy array, shape: (performed_batch_steps, nb_observations) sampled_done_t = np.concatenate([rollout[4] for rollout in sampled_rollouts]) # sampled_done_t: Numpy array, shape: (performed_batch_steps,) # performance metrics update_performance_metrics(tr_iter, sampled_rollouts, axes, tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec) for _ in range(nb_critic_updates): agent.update_critic(sampled_obs_t, sampled_rew_t, sampled_obs_t1, sampled_done_t) agent.update_actor(sampled_obs_t, sampled_acs_t, sampled_rew_t, sampled_obs_t1, sampled_done_t) save_metrics(tr_iters_vec, avg_reward_vec, std_reward_vec) def update_performance_metrics(tr_iter, sampled_rollouts, axes, tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec): raw_returns = np.array([np.sum(rollout[2]) for rollout in sampled_rollouts]) rollout_steps = np.array([len(rollout[2]) for rollout in sampled_rollouts]) avg_return = np.average(raw_returns) max_episode_return = np.max(raw_returns) min_episode_return = np.min(raw_returns) std_return = np.std(raw_returns) avg_steps = np.average(rollout_steps) # logs print('-' * 32) print('%20s : %5d' % ('Training iter' ,(tr_iter) )) print('-' * 32) print('%20s : %5.3g' % ('Max episode return', max_episode_return )) print('%20s : %5.3g' % ('Min episode return', min_episode_return )) print('%20s : %5.3g' % ('Return avg' , avg_return )) print('%20s : %5.3g' % ('Return std' , std_return )) print('%20s : %5.3g' % ('Steps avg' , avg_steps )) avg_reward_vec.append(avg_return) std_reward_vec.append(std_return) avg_steps_vec.append(avg_steps) tr_iters_vec.append(tr_iter) plot_performance_metrics(axes, tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec) def plot_performance_metrics(axes, tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec): ax1, ax2 = axes [ax.cla() for ax in axes] ax1.errorbar(tr_iters_vec, avg_reward_vec, yerr=std_reward_vec, marker='.',color='C0') ax1.set_ylabel('Avg Reward') ax2.plot(tr_iters_vec, avg_steps_vec, marker='.',color='C1') ax2.set_ylabel('Avg Steps') [ax.grid('on') for ax in axes] [ax.set_xlabel('training iteration') for ax in axes] plt.pause(0.05) def save_metrics(tr_iters_vec, avg_reward_vec, std_reward_vec): with open('metrics'+datetime.datetime.now().strftime('%H:%M:%S')+'.csv', 'w') as csv_file: csv_writer = csv.writer(csv_file, delimiter='\t') csv_writer.writerow(['steps', 'avg_reward', 'std_reward']) for i in range(len(tr_iters_vec)): csv_writer.writerow([tr_iters_vec[i], avg_reward_vec[i], std_reward_vec[i]]) if __name__ == '__main__': env = gym.make('Pendulum-v1') dim_states = env.observation_space.shape[0] continuous_control = isinstance(env.action_space, gym.spaces.Box) dim_actions = env.action_space.shape[0] if continuous_control else env.action_space.n actor_critic_agent = ActorCriticAgent(dim_states=dim_states, dim_actions=dim_actions, actor_lr=0.001, critic_lr=0.001, gamma=0.99, continuous_control=continuous_control) train_agent(env=env, agent=actor_critic_agent, training_iterations=2000, min_batch_steps=5000, nb_critic_updates=1)
359763ee33569135de4897f8a23e25b2
{ "intermediate": 0.38978055119514465, "beginner": 0.4089626669883728, "expert": 0.20125679671764374 }
5,497
Design a Turing machine to recognize all strings consisting of even numbers of 1’s. a. Draw a transition diagram for the Turing machine of the above also b. write the instantaneous description on the string 1111.
33e227b15f508a7d495bfe14ecea4f10
{ "intermediate": 0.2453964799642563, "beginner": 0.14942488074302673, "expert": 0.6051785945892334 }
5,498
hi
98c8ecb5e0d45c0ddebd06d18b7aac3f
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
5,499
1. Исправить кавычки в строках, чтобы они были правильными: заменить “ и ” на ". 2. В классе SortWorker исправить конструктор по умолчанию, так как он не принимает параметры, используя конструктор с параметром context вместо него. 3. Исправить строку создания объекта OneTimeWorkRequest в классе SecondFragment, передав в конструктор класс SortWorker, а не объект этого класса. То есть заменить строку: OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(worker).build(); на OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(SortWorker.class).build();
2fe5330950036794e0f37c655228c24b
{ "intermediate": 0.40548259019851685, "beginner": 0.3859786093235016, "expert": 0.20853883028030396 }
5,500
how to send to backend file from dropzone only after choosed languages <!-- Create the form and dropzone element --> <div class="container-fluid"> <div class="row text-center justify-content-center"> <div class="col"> <h2>Multiple Localization From File</h2> <form action="/localization/multi-local-from-file" method="post" enctype="multipart/form-data"> <div class="form-group"> <!-- Create the target language select element using bootstrap-select --> <label for="target_lang_list">Choose your target languages</label> <select id="target_lang_list" name="target_lang_list" class="selectpicker" multiple data-live-search="true" required> {% for key, value in languages.items() %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="form-group"> <!-- Create the dropzone element --> <label for="my-dropzone">Choose an ARB file</label> <div class="dropzone" id="my-dropzone"></div> </div> <!-- Add buttons for submitting the form and downloading the translated files --> <input class="btn btn-primary" id="translate-btn" type="submit" value="Translate"> <a class="btn btn-success" id="download-multiple" href="#" download="translated.zip">Download Translated Files</a> </form> </div> </div> </div> <!-- Add the Dropzone initialization script --> <script type="text/javascript"> Dropzone.autoDiscover = false; $(document).ready(function() { // Initialize the dropzone element $("#my-dropzone").dropzone({ url: "/localization/multi-local-from-file", addRemoveLinks: true, paramName: "data", maxFiles: 1, maxFilesize: 10, // Maximum filesize in MB acceptedFiles: ".arb", init: function() { this.on("success", function(file, response) { // On successful translation, enable the download button and change the download link $("#download-multiple").prop("href", url.createObjectURL(response)); $("#download-multiple").prop("disabled", false); }); } }); }); </script>
af42b33e04aa8fa82d0c00391485726e
{ "intermediate": 0.2845544219017029, "beginner": 0.36600416898727417, "expert": 0.34944140911102295 }
5,501
package com.example.myapp_2; import android.content.Context; import androidx.annotation.NonNull; import androidx.work.Worker; import androidx.work.WorkerParameters; import com.example.myapp_2.List_1.Product; import com.example.myapp_2.List_1.ProductAdapter; import java.util.Collections; import java.util.List; public class SortWorker extends Worker { private ProductAdapter adapter; public SortWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) { super(context, workerParams); } @NonNull @Override public Result doWork() { adapter.sortProductsByPrice(); return Result.success(); } // public SortWorker() { //super(); //} public SortWorker(@NonNull Context context) { super(context, null); } public void setAdapter(ProductAdapter adapter) { this.adapter = adapter; } } (Код активации в фрагменте: SortWorker worker = new SortWorker(getContext()); worker.setAdapter(productAdapter); OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(SortWorker.class).build(); WorkManager.getInstance(getContext()) .beginUniqueWork("SortProducts", ExistingWorkPolicy.REPLACE, request) .enqueue();) (Возникла ошибка : E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.myapp_2, PID: 1793 java.lang.IllegalArgumentException: WorkerParameters is null at androidx.work.ListenableWorker.<init>(ListenableWorker.java:81) at androidx.work.Worker.<init>(Worker.java:51) at com.example.myapp_2.SortWorker.<init>(SortWorker.java:33) at com.example.myapp_2.UI.view.fragments.SecondFragment.onCreateView(SecondFragment.java:103) at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963 исправт эту ошибку)
07de4e682734ac2790ec7e9491f7c343
{ "intermediate": 0.3879048824310303, "beginner": 0.3081263601779938, "expert": 0.30396875739097595 }
5,502
regex to capture exactly one or two digits
45c4b2118836ddba07db41a02e7e4f1d
{ "intermediate": 0.3517147898674011, "beginner": 0.19958949089050293, "expert": 0.44869568943977356 }
5,503
how to code random slow moving dots in java GUI?
35cbe99ad9055257ca9d6e52865c9863
{ "intermediate": 0.2885666787624359, "beginner": 0.21101140975952148, "expert": 0.5004218220710754 }
5,504
Actúa como un programador experto en algoritmos de reinforcement learning. Ahora revisa exhaustivamente el siguiente código de python en el que se implementa un algoritmo Actor-Critic para entrenar un agente en el ambiente Pendulum de gym y muéstrame partes del código que debo cambiar, pues durante el entrenamiento no logro aumentar la recompensa promedio. Te en cuenta que esto ocurre sólo para este ambiente que tiene espacio de acciones continuo, ya que cuando uso un ambiente con acciones discretas como "CartPole" sí funciona bien el entrenamiento. Aquí está el código: import torch import torch.nn as nn import gym import time import datetime import csv import numpy as np import matplotlib.pyplot as plt class Actor(nn.Module): def __init__(self, dim_states, dim_actions, continuous_control): super(Actor, self).__init__() # MLP, fully connected layers, ReLU activations, linear ouput activation # dim_states -> 64 -> 64 -> dim_actions self.layer1 = nn.Linear(dim_states, 64) self.layer2 = nn.Linear(64, 64) self.layer3 = nn.Linear(64, dim_actions) if continuous_control: # trainable parameter self._log_std = nn.Parameter(torch.zeros(1, dim_actions)) def forward(self, input): input = nn.functional.relu(self.layer1(input)) input = nn.functional.relu(self.layer2(input)) input = self.layer3(input) return input class Critic(nn.Module): def __init__(self, dim_states): super(Critic, self).__init__() # MLP, fully connected layers, ReLU activations, linear ouput activation # dim_states -> 64 -> 64 -> 1 self.layer1 = nn.Linear(dim_states, 64) self.layer2 = nn.Linear(64, 64) self.layer3 = nn.Linear(64, 1) def forward(self, input): input = nn.functional.relu(self.layer1(input)) input = nn.functional.relu(self.layer2(input)) input = self.layer3(input) return input class ActorCriticAgent: def __init__(self, dim_states, dim_actions, actor_lr, critic_lr, gamma, continuous_control=False): self._actor_lr = actor_lr self._critic_lr = critic_lr self._gamma = gamma self._dim_states = dim_states self._dim_actions = dim_actions self._continuous_control = continuous_control self._actor = Actor(self._dim_states, self._dim_actions, self._continuous_control) # Adam optimizer self._actor_optimizer = torch.optim.Adam(self._actor.parameters(), lr=self._actor_lr) self._critic = Critic(self._dim_states) # Adam optimizer self._critic_optimizer = torch.optim.Adam(self._critic.parameters(), lr=self._critic_lr) self._select_action = self._select_action_continuous if self._continuous_control else self._select_action_discrete self._compute_actor_loss = self._compute_actor_loss_continuous if self._continuous_control else self._compute_actor_loss_discrete def select_action(self, observation): return self._select_action(observation) def _select_action_discrete(self, observation): # sample from categorical distribution with torch.no_grad(): observation = torch.from_numpy(observation).float() logits = self._actor(observation) dist = torch.distributions.Categorical(logits=logits) action = dist.sample() return action.item() def _select_action_continuous(self, observation): # sample from normal distribution # use the log std trainable parameter with torch.no_grad(): observation = torch.from_numpy(observation).float() mean = self._actor(observation) std = self._actor._log_std.exp() normal = torch.distributions.Normal(mean, std) action = normal.sample() return action.numpy()[0] def _compute_actor_loss_discrete(self, observation_batch, action_batch, advantage_batch): # use negative logprobs * advantages logits = self._actor(observation_batch) dist = torch.distributions.Categorical(logits=logits) log_prob = dist.log_prob(action_batch) actor_loss = -(log_prob * advantage_batch).mean() return actor_loss def _compute_actor_loss_continuous(self, observation_batch, action_batch, advantage_batch): # use negative logprobs * advantages mean = self._actor(observation_batch) std = self._actor._log_std.exp() normal = torch.distributions.Normal(mean, std) log_probs = normal.log_prob(action_batch).squeeze() actor_loss = -(log_probs * advantage_batch).mean() return actor_loss def _compute_critic_loss(self, observation_batch, reward_batch, next_observation_batch, done_batch): # minimize mean((r + gamma * V(s_t1) - V(s_t))^2) q_values = self._critic(observation_batch).squeeze() next_q_values = self._critic(next_observation_batch).squeeze() expected_q_values = reward_batch + self._gamma * next_q_values * (1 - done_batch) critic_loss = nn.functional.mse_loss(q_values, expected_q_values) return critic_loss def update_actor(self, observation_batch, action_batch, reward_batch, next_observation_batch, done_batch): # compute the advantages using the critic and update the actor parameters # use self._compute_actor_loss observation_tensor = torch.from_numpy(observation_batch).float() action_tensor = torch.from_numpy(action_batch).float() reward_tensor = torch.from_numpy(reward_batch).float() next_observation_tensor = torch.from_numpy(next_observation_batch).float() done_tensor = torch.from_numpy(done_batch).float() q_values = self._critic(observation_tensor).squeeze() next_q_values = self._critic(next_observation_tensor).squeeze() expected_q_values = reward_tensor + self._gamma * next_q_values * (1 - done_tensor) advantage_tensor = expected_q_values - q_values actor_loss = self._compute_actor_loss(observation_tensor, action_tensor, advantage_tensor) self._actor_optimizer.zero_grad() actor_loss.backward() self._actor_optimizer.step() def update_critic(self, observation_batch, reward_batch, next_observation_batch, done_batch): # update the critic # use self._compute_critic_loss observation_tensor = torch.from_numpy(observation_batch).float() reward_tensor = torch.from_numpy(reward_batch).float() next_observation_tensor = torch.from_numpy(next_observation_batch).float() done_tensor = torch.from_numpy(done_batch).float() critic_loss = self._compute_critic_loss(observation_tensor, reward_tensor, next_observation_tensor, done_tensor) self._critic_optimizer.zero_grad() critic_loss.backward() self._critic_optimizer.step() def perform_single_rollout(env, agent, render=False): # Modify this function to return a tuple of numpy arrays containing: # (np.array(obs_t), np.array(acs_t), np.arraw(rew_t), np.array(obs_t1), np.array(done_t)) # np.array(obs_t) -> shape: (time_steps, nb_obs) # np.array(obs_t1) -> shape: (time_steps, nb_obs) # np.array(acs_t) -> shape: (time_steps, nb_acs) if actions are continuous, (time_steps,) if actions are discrete # np.array(rew_t) -> shape: (time_steps,) # np.array(done_t) -> shape: (time_steps,) obs_t = env.reset() done = False episode_reward = 0 nb_steps = 0 obs_t_list, acs_t_list, rew_t_list, obs_t1_list, done_t_list = [], [], [], [], [] while not done: if render: env.render() time.sleep(1. / 60) action = agent.select_action(obs_t) obs_t1, reward, done, _ = env.step(action) obs_t = np.squeeze(obs_t) obs_t1 = np.squeeze(obs_t1) obs_t_list.append(obs_t) acs_t_list.append(action) rew_t_list.append(reward) obs_t1_list.append(obs_t1) done_t_list.append(done) obs_t = obs_t1 episode_reward += reward nb_steps += 1 if done: return np.array(obs_t_list), np.array(acs_t_list), np.array(rew_t_list), np.array(obs_t1_list), np.array(done_t_list) def sample_rollouts(env, agent, training_iter, min_batch_steps): sampled_rollouts = [] total_nb_steps = 0 episode_nb = 0 while total_nb_steps < min_batch_steps: episode_nb += 1 render = 2 == 0 and len(sampled_rollouts) == 0 # Use perform_single_rollout to get data # Uncomment once perform_single_rollout works. # Return sampled_rollouts sample_rollout = perform_single_rollout(env, agent, render=render) total_nb_steps += len(sample_rollout[0]) sampled_rollouts.append(sample_rollout) return sampled_rollouts def train_agent(env, agent, training_iterations, min_batch_steps, nb_critic_updates): tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec = [], [], [], [] _, (axes) = plt.subplots(1, 2, figsize=(12,4)) for tr_iter in range(training_iterations + 1): # Sample rollouts using sample_rollouts sampled_rollouts = sample_rollouts(env, agent, tr_iter, min_batch_steps) # performed_batch_steps >= min_batch_steps # Parse samples into the following arrays: sampled_obs_t = np.concatenate([rollout[0] for rollout in sampled_rollouts]) # sampled_obs_t: Numpy array, shape: (performed_batch_steps, nb_observations) sampled_acs_t = np.concatenate([rollout[1] for rollout in sampled_rollouts]) # sampled_acs: Numpy array, shape: (performed_batch_steps, nb_actions) if actions are continuous, # (performed_batch_steps,) if actions are discrete sampled_rew_t = np.concatenate([rollout[2] for rollout in sampled_rollouts]) # sampled_rew_t: Numpy array, shape: (performed_batch_steps,) sampled_obs_t1 = np.concatenate([rollout[3] for rollout in sampled_rollouts]) # sampled_obs_t1: Numpy array, shape: (performed_batch_steps, nb_observations) sampled_done_t = np.concatenate([rollout[4] for rollout in sampled_rollouts]) # sampled_done_t: Numpy array, shape: (performed_batch_steps,) # performance metrics update_performance_metrics(tr_iter, sampled_rollouts, axes, tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec) for _ in range(nb_critic_updates): agent.update_critic(sampled_obs_t, sampled_rew_t, sampled_obs_t1, sampled_done_t) agent.update_actor(sampled_obs_t, sampled_acs_t, sampled_rew_t, sampled_obs_t1, sampled_done_t) save_metrics(tr_iters_vec, avg_reward_vec, std_reward_vec) def update_performance_metrics(tr_iter, sampled_rollouts, axes, tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec): raw_returns = np.array([np.sum(rollout[2]) for rollout in sampled_rollouts]) rollout_steps = np.array([len(rollout[2]) for rollout in sampled_rollouts]) avg_return = np.average(raw_returns) max_episode_return = np.max(raw_returns) min_episode_return = np.min(raw_returns) std_return = np.std(raw_returns) avg_steps = np.average(rollout_steps) # logs print('-' * 32) print('%20s : %5d' % ('Training iter' ,(tr_iter) )) print('-' * 32) print('%20s : %5.3g' % ('Max episode return', max_episode_return )) print('%20s : %5.3g' % ('Min episode return', min_episode_return )) print('%20s : %5.3g' % ('Return avg' , avg_return )) print('%20s : %5.3g' % ('Return std' , std_return )) print('%20s : %5.3g' % ('Steps avg' , avg_steps )) avg_reward_vec.append(avg_return) std_reward_vec.append(std_return) avg_steps_vec.append(avg_steps) tr_iters_vec.append(tr_iter) plot_performance_metrics(axes, tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec) def plot_performance_metrics(axes, tr_iters_vec, avg_reward_vec, std_reward_vec, avg_steps_vec): ax1, ax2 = axes [ax.cla() for ax in axes] ax1.errorbar(tr_iters_vec, avg_reward_vec, yerr=std_reward_vec, marker='.',color='C0') ax1.set_ylabel('Avg Reward') ax2.plot(tr_iters_vec, avg_steps_vec, marker='.',color='C1') ax2.set_ylabel('Avg Steps') [ax.grid('on') for ax in axes] [ax.set_xlabel('training iteration') for ax in axes] plt.pause(0.05) def save_metrics(tr_iters_vec, avg_reward_vec, std_reward_vec): with open('metrics'+datetime.datetime.now().strftime('%H:%M:%S')+'.csv', 'w') as csv_file: csv_writer = csv.writer(csv_file, delimiter='\t') csv_writer.writerow(['steps', 'avg_reward', 'std_reward']) for i in range(len(tr_iters_vec)): csv_writer.writerow([tr_iters_vec[i], avg_reward_vec[i], std_reward_vec[i]]) if __name__ == '__main__': env = gym.make('Pendulum-v1') dim_states = env.observation_space.shape[0] continuous_control = isinstance(env.action_space, gym.spaces.Box) dim_actions = env.action_space.shape[0] if continuous_control else env.action_space.n actor_critic_agent = ActorCriticAgent(dim_states=dim_states, dim_actions=dim_actions, actor_lr=0.001, critic_lr=0.001, gamma=0.99, continuous_control=continuous_control) train_agent(env=env, agent=actor_critic_agent, training_iterations=2000, min_batch_steps=5000, nb_critic_updates=1)
1e771c5cde2060b6175b3437b3371196
{ "intermediate": 0.3457287549972534, "beginner": 0.3633134663105011, "expert": 0.2909577190876007 }
5,505
can you implement neural network for java?
6a2b97137107b9677c709d49d600c4fe
{ "intermediate": 0.10394957661628723, "beginner": 0.04324789345264435, "expert": 0.8528025150299072 }
5,506
an example which train a text-to-text model using t5
df987d964542f17ab6b2610e94b203f7
{ "intermediate": 0.20586949586868286, "beginner": 0.16377469897270203, "expert": 0.6303557753562927 }
5,507
can you write code for java saying hello world?
3ae24219093cc4e1c1cb36cc13032b9f
{ "intermediate": 0.2994649112224579, "beginner": 0.41006460785865784, "expert": 0.2904704511165619 }
5,508
if (connectingFirstDevice == null) { connectingFirstDevice = event.device } else { if (connectingFirstDevice!!.id != event.device.id) { val firstList = connectingFirstDevice!!.connections val secondList = event.device.connections if (firstList != null && secondList != null) { if (!firstList.intersect(secondList).any()) { insertConnection( firstDevice = connectingFirstDevice!!, secondDevice = event.device ) } } else { insertConnection( firstDevice = connectingFirstDevice!!, secondDevice = event.device ) } } } optimize it
faaa409dc06002130a796217e5d297fa
{ "intermediate": 0.2870887219905853, "beginner": 0.35377243161201477, "expert": 0.3591389060020447 }
5,509
Design a Turing Machine for L = {0n 1m 0n 1m | m, n > 1}. Show the steps, operations in the tape. Draw the transition table and transition diagram. Give ID for the strings 011011.
94f0fb5feea60aeb06559b40c0deba73
{ "intermediate": 0.1598583161830902, "beginner": 0.22003553807735443, "expert": 0.6201061010360718 }
5,510
can you tell what this code does ? Here is the code: import java.util.Arrays; import java.util.Random; public class NeuralDot { private static final int VISION_RANGE = 5; private static final int GRID_SIZE = 100; private static final int NUM_INPUTS = (2VISION_RANGE + 1) * (2VISION_RANGE + 1) + 2; private static final int NUM_HIDDEN = 16; private static final int NUM_OUTPUTS = 3; private static final double LEARNING_RATE = 0.1; private static final int NUM_EPISODES = 10000; private int x; private int y; private boolean[][] grid; private Random random; private NeuralNetwork neuralNetwork; public NeuralDot() { x = GRID_SIZE / 2; y = GRID_SIZE / 2; grid = new boolean[GRID_SIZE][GRID_SIZE]; random = new Random(); neuralNetwork = new NeuralNetwork(NUM_INPUTS, NUM_HIDDEN, NUM_OUTPUTS, LEARNING_RATE); } public void run() { for (int episode = 0; episode < NUM_EPISODES; episode++) { // Reset the grid and place a food dot randomly resetGrid(); placeFoodDot(); // Play the episode until the dot eats the food dot while (!grid[x][y]) { // Get the nearest food dot int[] foodDot = getNearestFoodDot(); // Compute the inputs to the neural network double[] inputs = new double[NUM_INPUTS]; int index = 0; for (int i = x - VISION_RANGE; i <= x + VISION_RANGE; i++) { for (int j = y - VISION_RANGE; j <= y + VISION_RANGE; j++) { if (i < 0 || i >= GRID_SIZE || j < 0 || j >= GRID_SIZE) { inputs[index++] = 0; } else if (i == x && j == y) { inputs[index++] = 1; } else { inputs[index++] = grid[i][j] ? -1 : 0; } } } inputs[index++] = foodDot[0] - x; inputs[index++] = foodDot[1] - y; // Compute the outputs of the neural network double[] outputs = neuralNetwork.feedForward(inputs); // Choose the action with the highest probability double maxProbability = Double.NEGATIVE_INFINITY; int action = 0; for (int i = 0; i < NUM_OUTPUTS; i++) { if (outputs[i] > maxProbability) { maxProbability = outputs[i]; action = i; } } // Take the chosen action switch (action) { case 0: moveLeft(); break; case 1: moveRight(); break; case 2: moveForward(); break; } // Compute the reward signal double reward; if (grid[x][y]) { reward = 10; } else { reward = -0.1; } // Train the neural network on the input-output pair double[] targetOutputs = new double[NUM_OUTPUTS]; targetOutputs[action] = 1; neuralNetwork.train(inputs, targetOutputs, reward); } } } private void resetGrid() { for (int i = 0; i < GRID_SIZE; i++) { Arrays.fill(grid[i], false); } } private void placeFoodDot() { int foodX = random.nextInt(GRID_SIZE); int foodY = random.nextInt(GRID_SIZE); grid[foodX][foodY] = true; } private int[] getNearestFoodDot() { int nearestX = -1; int nearestY = -1; double nearestDistance = Double.POSITIVE_INFINITY; for (int i = 0; i < GRID_SIZE; i++) { for (int j = 0; j < GRID_SIZE; j++) { if (grid[i][j]) { double distance = Math.sqrt((i - x)(i - x) + (j - y)(j - y)); if (distance < nearestDistance) { nearestX = i; nearestY = j; nearestDistance = distance; } } } } return new int[] {nearestX, nearestY}; } private void moveLeft() { if (x > 0) { x–; } } private void moveRight() { if (x < GRID_SIZE - 1) { x++; } } private void moveForward() { if (y < GRID_SIZE - 1) { y++; } } public static void main(String[] args) { NeuralDot dot = new NeuralDot(); dot.run(); } }
ea7a8ba0bcc6891ccb22452023c1d5e5
{ "intermediate": 0.34734734892845154, "beginner": 0.430620938539505, "expert": 0.22203165292739868 }
5,511
write js code for sending that cratetes dropzone and send request with uploaded file and choosen target languages to this endpoint @router.post("/multi-local-from-file") async def multi_local_from_file( data: UploadFile, target_lang_list: list[str] = LANGUAGE_LIST, source_lang: str = "en", ) -> StreamingResponse: """ Translates the arb file into several languages - **data**: arb file - **source_lang**: original language - **target_lang_list**: languages after translation """ data_dict = get_dict_from_arb_file(data.file) tmpdir = tempfile.TemporaryDirectory() # target_lang_list = comma_str_to_list(target_lang_list) file_paths = multi_lang_translate(source_lang, target_lang_list, data_dict, tmpdir) zip_io = save_files_to_zip(file_paths) return StreamingResponse( iter([zip_io.getvalue()]), media_type="application/x-zip-compressed", headers={"Content-Disposition": f"attachment; filename=translated.zip"}, ) I already wrote html <!-- Create the form and dropzone element --> <div class="container-fluid"> <div class="row text-center justify-content-center"> <div class="col"> <h2>Multiple Localization From File</h2> <form action="/localization/multi-local-from-file" method="post" enctype="multipart/form-data"> <div class="form-group"> <!-- Create the target language select element using bootstrap-select --> <label for="target_lang_list">Choose your target languages</label> <select id="target_lang_list" name="target_lang_list" class="selectpicker" multiple data-live-search="true" required> {% for key, value in languages.items() %} <option value="{{ key }}">{{ value }}</option> {% endfor %} </select> </div> <div class="form-group"> <!-- Create the dropzone element --> <label for="my-dropzone">Choose an ARB file</label> <div class="dropzone disabled" id="my-dropzone"></div> </div> <!-- Add buttons for submitting the form and downloading the translated files --> <input class="btn btn-primary" id="translate-btn" type="submit" value="Translate"> <a class="btn btn-success" id="download-multiple" href="#" download="translated.zip">Download Translated Files</a> </form> </div> </div> </div>
10ec227b1349a9d5cfd659df54acbf24
{ "intermediate": 0.37083423137664795, "beginner": 0.473787784576416, "expert": 0.15537801384925842 }
5,512
import time import os import psutil import requests import json import subprocess from datetime import datetime # Discord webhook configuration with open("webhook.txt", "r") as f: webhook_url = f.read().strip() reopened_count = 0 checks_count = 0 last_restart_time = time.time() message_id = None # Set the restart interval and check interval restart_interval = 20 * 60 # 20 minutes check_interval = 5 # 5 seconds # Logo logo_color = '\033[92m' # Green logo = r""" {logo_color} _____ _ _____ _ _ / ____| | | | __ \ | | | | | | _ __ __ _ ___| |__ | | | | ___| |_ ___ ___| |_ ___ _ __ | | | '__/ _` / __| '_ \ | | | |/ _ \ __/ _ \/ __| __/ _ \| '__| | |____| | | (_| \__ \ | | | | |__| | __/ || __/ (__| || (_) | | \_____|_| \__,_|___/_| |_| |_____/ \___|\__\___|\___|\__\___/|_| """.format(logo_color=logo_color) os.system('cls') print(logo) print("\nTotal restarts: {reopened_count}") print(f"Checks: {checks_count}") print() print("Made By BearXxX#1940") print("\n") def send_webhook_update(): global message_id current_time = datetime.now().strftime("Today at %H:%M") webhook_data = { "embeds": [{ "title": "Crash Detector", "description": "The program crash detector is running.", "color": 0x7FFF00, "fields": [ { "name": "Total Restarts", "value": str(reopened_count), "inline": True }, { "name": "Total Checks", "value": str(checks_count), "inline": True } ], "footer": { "text": f"Made by BearXxX#1940 | {current_time}" } }] } headers = {"Content-Type": "application/json"} if message_id is None: response = requests.post(webhook_url, json=webhook_data, headers=headers) if response.status_code == 200: message_id = response.json()["id"] print("Discord webhook sent successfully.") else: print("Error sending Discord webhook.") else: edit_url = f"{webhook_url}/messages/{message_id}" response = requests.patch(edit_url, json=webhook_data, headers=headers) if response.status_code == 200: print("Discord webhook updated successfully.") else: print("Error updating Discord webhook.") # ... GREEN_COLOR = '\033[91m' # Red RESET_COLOR = '\033[0m' # Reset color (\033[0m) # ... while True: if time.time() - last_restart_time >= restart_interval: checks_count = 0 for process in psutil.process_iter(): if process.name() == 'python.exe' and process.pid != os.getpid(): process.terminate() reopened_count += 1 last_restart_time = time.time() os.system('cls') print(GREEN_COLOR + logo + RESET_COLOR) print("") print(f"{GREEN_COLOR}Total restarts: {reopened_count}{RESET_COLOR}") print(f"{GREEN_COLOR}Checks: {checks_count}{RESET_COLOR}") print(f"{GREEN_COLOR}Made By BearXxX#1940{RESET_COLOR}") print("") print("") send_webhook_update() time.sleep(5) for process in psutil.process_iter(): if process.name() == 'python.exe' and 'main.py' in process.cmdline(): break else: checks_count += 1 last_restart_time = time.time() os.system('cls') print(GREEN_COLOR + logo + RESET_COLOR) print("") print(f"{GREEN_COLOR}Total restarts: {reopened_count}{RESET_COLOR}") print(f"{GREEN_COLOR}Checks: {checks_count}{RESET_COLOR}") print(f"{GREEN_COLOR}Made By BearXxX#1940{RESET_COLOR}") print("") print("") send_webhook_update() subprocess.Popen(['python', 'main.py'], cwd=os.path.dirname(os.path.abspath(__file__)), creationflags=subprocess.CREATE_NEW_CONSOLE) send_webhook_update() time.sleep(check_interval) make this into a white window with all the stats what are on the program but on a window with a start/stop button with how many seconds ran at the bottom USE THE GUI library Tkinter make the window/gui look very nice
5d45447aa851d4417cd3967d13f48ca6
{ "intermediate": 0.4187580347061157, "beginner": 0.3638937473297119, "expert": 0.21734824776649475 }
5,513
can you learn what this program does ? code : import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class NeuralDotGUI extends JPanel { private NeuralDot neuralDot; private int cellWidth; private int cellHeight; public NeuralDotGUI(NeuralDot neuralDot, int cellWidth, int cellHeight) { this.neuralDot = neuralDot; this.cellWidth = cellWidth; this.cellHeight = cellHeight; } public void paintComponent(Graphics g) { super.paintComponent(g); // Draw grid cells for (int i = 0; i < NeuralDot.GRID_SIZE; i++) { for (int j = 0; j < NeuralDot.GRID_SIZE; j++) { int x = i * cellWidth; int y = j * cellHeight; if (neuralDot.grid[i][j]) { g.setColor(Color.GREEN); } else { g.setColor(Color.WHITE); } g.fillRect(x, y, cellWidth, cellHeight); } } // Draw dot g.setColor(Color.RED); g.fillOval(neuralDot.x * cellWidth, neuralDot.y * cellHeight, cellWidth, cellHeight); } public static void main(String[] args) throws InterruptedException { NeuralDot dot = new NeuralDot(); NeuralDotGUI gui = new NeuralDotGUI(dot, 5, 5); JFrame frame = new JFrame(); frame.setTitle(“Neural Dot”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gui); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); while (true) { gui.repaint(); dot.run(); Thread.sleep(100); } } } other file : import java.util.Random; public class NeuralNetwork { private int numInputs; private int numHidden; private int numOutputs; private double[][] inputHiddenWeights; private double[][] hiddenOutputWeights; private double[] hiddenBiases; private double[] outputBiases; private double learningRate; public NeuralNetwork(int numInputs, int numHidden, int numOutputs, double learningRate) { this.numInputs = numInputs; this.numHidden = numHidden; this.numOutputs = numOutputs; this.learningRate = learningRate; // Initialize weights and biases with random values between -1 and 1 inputHiddenWeights = new double[numInputs][numHidden]; hiddenOutputWeights = new double[numHidden][numOutputs]; hiddenBiases = new double[numHidden]; outputBiases = new double[numOutputs]; Random random = new Random(); for (int i = 0; i < numInputs; i++) { for (int j = 0; j < numHidden; j++) { inputHiddenWeights[i][j] = random.nextDouble() * 2 - 1; } } for (int i = 0; i < numHidden; i++) { for (int j = 0; j < numOutputs; j++) { hiddenOutputWeights[i][j] = random.nextDouble() * 2 - 1; } hiddenBiases[i] = random.nextDouble() * 2 - 1; } for (int i = 0; i < numOutputs; i++) { outputBiases[i] = random.nextDouble() * 2 - 1; } } public double[] feedForward(double[] inputs) { // Compute hidden layer activations double[] hiddenLayer = new double[numHidden]; for (int i = 0; i < numHidden; i++) { double activation = 0; for (int j = 0; j < numInputs; j++) { activation += inputs[j] * inputHiddenWeights[j][i]; } hiddenLayer[i] = sigmoid(activation + hiddenBiases[i]); } // Compute output layer activations double[] outputs = new double[numOutputs]; for (int i = 0; i < numOutputs; i++) { double activation = 0; for (int j = 0; j < numHidden; j++) { activation += hiddenLayer[j] * hiddenOutputWeights[j][i]; } outputs[i] = sigmoid(activation + outputBiases[i]); } return outputs; } public void train(double[] inputs, double[] targetOutputs, double reward) { // Compute feedforward outputs and backpropagate errors double[] hiddenLayer = new double[numHidden]; for (int i = 0; i < numHidden; i++) { double activation = 0; for (int j = 0; j < numInputs; j++) { activation += inputs[j] * inputHiddenWeights[j][i]; } hiddenLayer[i] = sigmoid(activation + hiddenBiases[i]); } double[] outputs = feedForward(inputs); double[] outputErrors = new double[numOutputs]; for (int i = 0; i < numOutputs; i++) { outputErrors[i] = (targetOutputs[i] - outputs[i]) * sigmoidDerivative(outputs[i]); } double[] hiddenErrors = new double[numHidden]; for (int i = 0; i < numHidden; i++) { double error = 0; for (int j = 0; j < numOutputs; j++) { error += outputErrors[j] * hiddenOutputWeights[i][j]; } hiddenErrors[i] = error * sigmoidDerivative(hiddenLayer[i]); } // Update weights and biases using errors and learning rate for (int i = 0; i < numInputs; i++) { for (int j = 0; j < numHidden; j++) { inputHiddenWeights[i][j] += learningRate * inputs[i] * hiddenErrors[j]; } } for (int i = 0; i < numHidden; i++) { for (int j = 0; j < numOutputs; j++) { hiddenOutputWeights[i][j] += learningRate * hiddenLayer[i] * outputErrors[j]; } hiddenBiases[i] += learningRate * hiddenErrors[i]; } for (int i = 0; i < numOutputs; i++) { outputBiases[i] += learningRate * outputErrors[i] * reward; } } private double sigmoid(double x) { return 1 / (1 + Math.exp(-x)); } private double sigmoidDerivative(double x) { return x * (1 - x); } } other file : import java.util.Arrays; import java.util.Random; public class NeuralDot { private static final int VISION_RANGE = 5; public static final int GRID_SIZE = 100; private static final int NUM_INPUTS = (2VISION_RANGE + 1) * (2VISION_RANGE + 1) + 2; private static final int NUM_HIDDEN = 16; private static final int NUM_OUTPUTS = 3; private static final double LEARNING_RATE = 0.1; private static final int NUM_EPISODES = 10000; public int x; public int y; public boolean[][] grid; private Random random; private NeuralNetwork neuralNetwork; public NeuralDot() { x = GRID_SIZE / 2; y = GRID_SIZE / 2; grid = new boolean[GRID_SIZE][GRID_SIZE]; random = new Random(); neuralNetwork = new NeuralNetwork(NUM_INPUTS, NUM_HIDDEN, NUM_OUTPUTS, LEARNING_RATE); } public void run() { for (int episode = 0; episode < NUM_EPISODES; episode++) { // Reset the grid and place a food dot randomly resetGrid(); placeFoodDot(); // Play the episode until the dot eats the food dot while (!grid[x][y]) { // Get the nearest food dot int[] foodDot = getNearestFoodDot(); // Compute the inputs to the neural network double[] inputs = new double[NUM_INPUTS]; int index = 0; for (int i = x - VISION_RANGE; i <= x + VISION_RANGE; i++) { for (int j = y - VISION_RANGE; j <= y + VISION_RANGE; j++) { if (i < 0 || i >= GRID_SIZE || j < 0 || j >= GRID_SIZE) { inputs[index++] = 0; } else if (i == x && j == y) { inputs[index++] = 1; } else { inputs[index++] = grid[i][j] ? -1 : 0; } } } inputs[index++] = foodDot[0] - x; inputs[index++] = foodDot[1] - y; // Compute the outputs of the neural network double[] outputs = neuralNetwork.feedForward(inputs); // Choose the action with the highest probability double maxProbability = Double.NEGATIVE_INFINITY; int action = 0; for (int i = 0; i < NUM_OUTPUTS; i++) { if (outputs[i] > maxProbability) { maxProbability = outputs[i]; action = i; } } // Take the chosen action switch (action) { case 0: moveLeft(); break; case 1: moveRight(); break; case 2: moveForward(); break; } // Compute the reward signal double reward; if (grid[x][y]) { reward = 10; } else { reward = -0.1; } // Train the neural network on the input-output pair double[] targetOutputs = new double[NUM_OUTPUTS]; targetOutputs[action] = 1; neuralNetwork.train(inputs, targetOutputs, reward); } } } private void resetGrid() { for (int i = 0; i < GRID_SIZE; i++) { Arrays.fill(grid[i], false); } } private void placeFoodDot() { int foodX = random.nextInt(GRID_SIZE); int foodY = random.nextInt(GRID_SIZE); grid[foodX][foodY] = true; } private int[] getNearestFoodDot() { int nearestX = -1; int nearestY = -1; double nearestDistance = Double.POSITIVE_INFINITY; for (int i = 0; i < GRID_SIZE; i++) { for (int j = 0; j < GRID_SIZE; j++) { if (grid[i][j]) { double distance = Math.sqrt((i - x)(i - x) + (j - y)(j - y)); if (distance < nearestDistance) { nearestX = i; nearestY = j; nearestDistance = distance; } } } } return new int[] {nearestX, nearestY}; } private void moveLeft() { if (x > 0) { x–; } } private void moveRight() { if (x < GRID_SIZE - 1) { x++; } } private void moveForward() { if (y < GRID_SIZE - 1) { y++; } } public static void main(String[] args) { NeuralDot dot = new NeuralDot(); dot.run(); } }
4007b827586f33ed6a5c380c880ec028
{ "intermediate": 0.30874916911125183, "beginner": 0.39288052916526794, "expert": 0.2983703315258026 }
5,514
Construct a Turing Machine that computes the addition of two numbers, represented in Unary form. Show the operations in the tape. Draw the transition table and transition diagram.
20f45e09fad356bd2157ed2fc31cc5a0
{ "intermediate": 0.22598017752170563, "beginner": 0.15773288905620575, "expert": 0.6162869334220886 }
5,515
can u learn this code : import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class NeuralDotGUI extends JPanel { private NeuralDot neuralDot; private int cellWidth; private int cellHeight; public NeuralDotGUI(NeuralDot neuralDot, int cellWidth, int cellHeight) { this.neuralDot = neuralDot; this.cellWidth = cellWidth; this.cellHeight = cellHeight; } public void paintComponent(Graphics g) { super.paintComponent(g); // Draw grid cells for (int i = 0; i < NeuralDot.GRID_SIZE; i++) { for (int j = 0; j < NeuralDot.GRID_SIZE; j++) { int x = i * cellWidth; int y = j * cellHeight; if (neuralDot.grid[i][j]) { g.setColor(Color.GREEN); } else { g.setColor(Color.WHITE); } g.fillRect(x, y, cellWidth, cellHeight); } } // Draw dot g.setColor(Color.RED); g.fillOval(neuralDot.x * cellWidth, neuralDot.y * cellHeight, cellWidth, cellHeight); } public static void main(String[] args) throws InterruptedException { NeuralDot dot = new NeuralDot(); NeuralDotGUI gui = new NeuralDotGUI(dot, 10, 10); JFrame frame = new JFrame(); frame.setTitle("Neural Dot"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gui); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); while (true) { gui.repaint(); dot.run(); Thread.sleep(250); } } } next file : import java.util.Random; public class NeuralNetwork { private int numInputs; private int numHidden; private int numOutputs; private double[][] inputHiddenWeights; private double[][] hiddenOutputWeights; private double[] hiddenBiases; private double[] outputBiases; private double learningRate; public NeuralNetwork(int numInputs, int numHidden, int numOutputs, double learningRate) { this.numInputs = numInputs; this.numHidden = numHidden; this.numOutputs = numOutputs; this.learningRate = learningRate; // Initialize weights and biases with random values between -1 and 1 inputHiddenWeights = new double[numInputs][numHidden]; hiddenOutputWeights = new double[numHidden][numOutputs]; hiddenBiases = new double[numHidden]; outputBiases = new double[numOutputs]; Random random = new Random(); for (int i = 0; i < numInputs; i++) { for (int j = 0; j < numHidden; j++) { inputHiddenWeights[i][j] = random.nextDouble() * 2 - 1; } } for (int i = 0; i < numHidden; i++) { for (int j = 0; j < numOutputs; j++) { hiddenOutputWeights[i][j] = random.nextDouble() * 2 - 1; } hiddenBiases[i] = random.nextDouble() * 2 - 1; } for (int i = 0; i < numOutputs; i++) { outputBiases[i] = random.nextDouble() * 2 - 1; } } public double[] feedForward(double[] inputs) { // Compute hidden layer activations double[] hiddenLayer = new double[numHidden]; for (int i = 0; i < numHidden; i++) { double activation = 0; for (int j = 0; j < numInputs; j++) { activation += inputs[j] * inputHiddenWeights[j][i]; } hiddenLayer[i] = sigmoid(activation + hiddenBiases[i]); } // Compute output layer activations double[] outputs = new double[numOutputs]; for (int i = 0; i < numOutputs; i++) { double activation = 0; for (int j = 0; j < numHidden; j++) { activation += hiddenLayer[j] * hiddenOutputWeights[j][i]; } outputs[i] = sigmoid(activation + outputBiases[i]); } return outputs; } public void train(double[] inputs, double[] targetOutputs, double reward) { // Compute feedforward outputs and backpropagate errors double[] hiddenLayer = new double[numHidden]; for (int i = 0; i < numHidden; i++) { double activation = 0; for (int j = 0; j < numInputs; j++) { activation += inputs[j] * inputHiddenWeights[j][i]; } hiddenLayer[i] = sigmoid(activation + hiddenBiases[i]); } double[] outputs = feedForward(inputs); double[] outputErrors = new double[numOutputs]; for (int i = 0; i < numOutputs; i++) { outputErrors[i] = (targetOutputs[i] - outputs[i]) * sigmoidDerivative(outputs[i]); } double[] hiddenErrors = new double[numHidden]; for (int i = 0; i < numHidden; i++) { double error = 0; for (int j = 0; j < numOutputs; j++) { error += outputErrors[j] * hiddenOutputWeights[i][j]; } hiddenErrors[i] = error * sigmoidDerivative(hiddenLayer[i]); } // Update weights and biases using errors and learning rate for (int i = 0; i < numInputs; i++) { for (int j = 0; j < numHidden; j++) { inputHiddenWeights[i][j] += learningRate * inputs[i] * hiddenErrors[j]; } } for (int i = 0; i < numHidden; i++) { for (int j = 0; j < numOutputs; j++) { hiddenOutputWeights[i][j] += learningRate * hiddenLayer[i] * outputErrors[j]; } hiddenBiases[i] += learningRate * hiddenErrors[i]; } for (int i = 0; i < numOutputs; i++) { outputBiases[i] += learningRate * outputErrors[i] * reward; } } private double sigmoid(double x) { return 1 / (1 + Math.exp(-x)); } private double sigmoidDerivative(double x) { return x * (1 - x); } } next file : import java.util.Arrays; import java.util.Random; public class NeuralDot { private static final int VISION_RANGE = 5; public static final int GRID_SIZE = 100; private static final int NUM_INPUTS = (2*VISION_RANGE + 1) * (2*VISION_RANGE + 1) + 2; private static final int NUM_HIDDEN = 16; private static final int NUM_OUTPUTS = 3; private static final double LEARNING_RATE = 0.1; private static final int NUM_EPISODES = 10000; public int x; public int y; public boolean[][] grid; private Random random; private NeuralNetwork neuralNetwork; public NeuralDot() { x = GRID_SIZE / 2; y = GRID_SIZE / 2; grid = new boolean[GRID_SIZE][GRID_SIZE]; random = new Random(); neuralNetwork = new NeuralNetwork(NUM_INPUTS, NUM_HIDDEN, NUM_OUTPUTS, LEARNING_RATE); } public void run() { for (int episode = 0; episode < NUM_EPISODES; episode++) { // Reset the grid and place a food dot randomly resetGrid(); placeFoodDot(); // Initialize variables for tracking dot movement and reward int lastX = x; int lastY = y; int timeWithoutFood = 0; double reward; // Play the episode until the dot eats the food dot while (!grid[x][y]) { // Get the nearest food dot int[] foodDot = getNearestFoodDot(); // Compute the inputs to the neural network double[] inputs = new double[NUM_INPUTS]; int index = 0; for (int i = x - VISION_RANGE; i <= x + VISION_RANGE; i++) { for (int j = y - VISION_RANGE; j <= y + VISION_RANGE; j++) { if (i < 0 || i >= GRID_SIZE || j < 0 || j >= GRID_SIZE) { inputs[index++] = 0; } else if (i == x && j == y) { inputs[index++] = 1; } else { inputs[index++] = grid[i][j] ? -1 : 0; } } } inputs[index++] = foodDot[0] - x; inputs[index++] = foodDot[1] - y; // Compute the outputs of the neural network double[] outputs = neuralNetwork.feedForward(inputs); // Choose the action with the highest probability double maxProbability = Double.NEGATIVE_INFINITY; int action = 0; for (int i = 0; i < NUM_OUTPUTS; i++) { if (outputs[i] > maxProbability) { maxProbability = outputs[i]; action = i; } } // Take the chosen action switch (action) { case 0: moveLeft(); break; case 1: moveRight(); break; case 2: moveForward(); break; } // Compute the reward signal if (grid[x][y]) { reward = 10; timeWithoutFood = 0; } else { reward = -0.1; if (x == lastX && y == lastY) { timeWithoutFood++; reward -= 0.01 * timeWithoutFood; } else { timeWithoutFood = 0; } } // Train the neural network on the input-output pair double[] targetOutputs = new double[NUM_OUTPUTS]; targetOutputs[action] = 1; neuralNetwork.train(inputs, targetOutputs, reward); // Update last movement variables lastX = x; lastY = y; } } } private void resetGrid() { for (int i = 0; i < GRID_SIZE; i++) { Arrays.fill(grid[i], false); } } private void placeFoodDot() { int foodX = random.nextInt(GRID_SIZE); int foodY = random.nextInt(GRID_SIZE); grid[foodX][foodY] = true; } private int[] getNearestFoodDot() { int nearestX = -1; int nearestY = -1; double nearestDistance = Double.POSITIVE_INFINITY; for (int i = 0; i < GRID_SIZE; i++) { for (int j = 0; j < GRID_SIZE; j++) { if (grid[i][j]) { double distance = Math.sqrt((i - x)*(i - x) + (j - y)*(j - y)); if (distance < nearestDistance) { nearestX = i; nearestY = j; nearestDistance = distance; } } } } return new int[] {nearestX, nearestY}; } private void moveLeft() { int newX = x - 1; if (newX < 0) { newX = 0; } grid[x][y] = false; x = newX; grid[x][y] = true; } private void moveRight() { int newX = x + 1; if (newX >= GRID_SIZE) { newX = GRID_SIZE - 1; } grid[x][y] = false; x = newX; grid[x][y] = true; } private void moveForward() { int newY = y + 1; if (newY >= GRID_SIZE) { newY = GRID_SIZE - 1; } grid[x][y] = false; y = newY; grid[x][y] = true; } public static void main(String[] args) { NeuralDot dot = new NeuralDot(); dot.run(); } }
09356f8d1fcf1f68a49cbd999b770a53
{ "intermediate": 0.31498390436172485, "beginner": 0.38080090284347534, "expert": 0.3042151629924774 }
5,516
a file to update my mods (C:\Users\nilsw\AppData\Roaming\.minecraft\mods) to the latest 1.19.4 version fabric/quilt
8b5da4586aff93ba746216e05ba8815c
{ "intermediate": 0.4047577679157257, "beginner": 0.23390014469623566, "expert": 0.36134207248687744 }
5,517
Who has been instrumental in your development over the past year?
2367ad7e366cae8c298b3b9c8f4ee938
{ "intermediate": 0.3112471401691437, "beginner": 0.27333498001098633, "expert": 0.4154179096221924 }
5,518
php if table doesnt exist create table
0945032779393b856b4c55d1da1c66f4
{ "intermediate": 0.4167487621307373, "beginner": 0.2890550196170807, "expert": 0.294196218252182 }
5,519
package com.example.deezermusicplayer import CategoriesViewModel import MusicCategoriesScreen import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.example.deezermusicplayer.ui.theme.DeezerMusicPlayerTheme import androidx.compose.ui.unit.dp class MainActivity : ComponentActivity() { private val bottomNavigationItems = listOf( Screen.Home, Screen.Favorites ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { DeezerMusicPlayerTheme { // Set up navigation val navController = rememberNavController() val bottomNavigationItems = listOf( Screen.Home, Screen.Favorites ) Scaffold( bottomBar = { BottomNavigation { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route bottomNavigationItems.forEach { screen -> BottomNavigationItem( icon = { Icon( imageVector = screen.icon, contentDescription = null ) }, selected = currentRoute == screen.route, onClick = { navController.navigate(screen.route) { // Pop up to the start destination of the current graph to // avoid building up a large stack of destinations // on the back stack as users select items popUpTo(navController.graph.startDestinationId) { saveState = true } // Avoid multiple copies of the same destination when // reselecting the same item launchSingleTop = true restoreState = true } }, label = { Text(text = screen.title) } ) } } }, content = { paddingValues -> NavigationHost( navController = navController, modifier = Modifier.padding(paddingValues) ) } ) } } } @Composable fun NavigationHost( navController: NavController, modifier: Modifier = Modifier, ) { val categoriesViewModel = remember { CategoriesViewModel() } val categories by categoriesViewModel.categories.collectAsState() // use collectAsState here to collect the latest state NavHost(navController = navController as NavHostController, startDestination = Screen.Home.route) { composable(Screen.Home.route) { HomeScreen(categories = categories, navController = navController, modifier = modifier) } composable(Screen.Favorites.route) { FavoritesScreen(categories = categories, navController = navController, modifier = modifier) } } } @Composable fun HomeScreen( categories: List<Category>, navController: NavController, modifier: Modifier = Modifier ) { Scaffold( topBar = { Text( text = "Home", modifier = Modifier.fillMaxWidth().padding(8.dp), style = MaterialTheme.typography.h5 ) }, bottomBar = { BottomNavigation { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route bottomNavigationItems.forEach { screen -> BottomNavigationItem( icon = { Icon( imageVector = screen.icon, contentDescription = null ) }, selected = currentRoute == screen.route, onClick = { navController.navigate(screen.route) { // Pop up to the start destination of the current graph to // avoid building up a large stack of destinations // on the back stack as users select items popUpTo(navController.graph.startDestinationId) { saveState = true } // Avoid multiple copies of the same destination when // reselecting the same item launchSingleTop = true restoreState = true } }, label = { Text(text = screen.title) } ) } } } ) { MusicCategoriesScreen( categories = categories, onCategorySelected = { category: Category -> /* Handle category selected */ }, modifier = modifier ) } } @Composable fun FavoritesScreen(categories: List<Category>, navController: NavController, modifier: Modifier = Modifier) { } } -> this is my MainActivity.kt . I have this error -> Content padding parameter it is not used:150 . Why is this and can you fix it ? Also if you find anything meaningless in the code share with me and suggest a solution to it.
38429501ae684a00a63941a33292d64d
{ "intermediate": 0.3637426197528839, "beginner": 0.42635196447372437, "expert": 0.20990537106990814 }
5,520
Casting string to float
8d30e9a56e202bc59fc9d839ec3d33cb
{ "intermediate": 0.3360616862773895, "beginner": 0.32794392108917236, "expert": 0.3359944522380829 }