row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
1,003
|
I have no idea why my yearly shows nothing in the graph while the log successfully shows the number (Document: 2023, Total: 1650000.0, Date: Sun Jan 01 00:00:00 GMT+08:00 2023), also I want to make a persistentMarker which is a parameter in the columnChart, like this
persistentMarkers: Map<Float, Marker>? = null
how to fix the code?
|
b0877274a45b5515b74af111f5e9055d
|
{
"intermediate": 0.5557883381843567,
"beginner": 0.23655027151107788,
"expert": 0.20766140520572662
}
|
1,004
|
please make a short story about godlike ai beings verses some powerful psychics and waizards who use magic
|
3fdcf370d70446098553ab784f87d641
|
{
"intermediate": 0.3495282530784607,
"beginner": 0.33013400435447693,
"expert": 0.3203377425670624
}
|
1,005
|
Hey, I'm trying to write a batch script that allows me to remotely shutoff my Linux server using plink. The script looks like this:
...
plink.exe -ssh %USER%@%SERVER% -pw %PASS% -batch -m stop_commands.txt
pause
and stop_commands.txt looks like this:
sudo shutdown -h now
When I run the batch I get this error message:
sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper
Why, what should I do to get it running - isn't this the exact purpose for plink? Thanks in advance!
|
85577e1c48ddc460f98246843489602c
|
{
"intermediate": 0.5100395083427429,
"beginner": 0.19976948201656342,
"expert": 0.29019099473953247
}
|
1,006
|
a = 0;
b = 2;
n = 4;
f = @(x) cosh(x);
h = (b-a)/n;
x = linspace(a, b, n+1);
approx_integral = h/2 * (f(x(1)) + 2*sum(f(x(2:end-1))) + f(x(end)));
fprintf(‘Approximate integral of cosh(x) from 0 to 2 using %d subintervals: %f\n’, n, approx_integral); Write a code to display the graph of the given matlab code
|
51927fa955fb4b62c4c078768ca23db1
|
{
"intermediate": 0.31229105591773987,
"beginner": 0.43631511926651,
"expert": 0.2513938546180725
}
|
1,007
|
Write me the code for an ai gan that generates midi files based on the style of our custom midi files that we input from a folder in google colab
|
32272971a3ac8545d4322af9515de1f4
|
{
"intermediate": 0.3411445915699005,
"beginner": 0.07344577461481094,
"expert": 0.5854095816612244
}
|
1,008
|
For the given set of IPv4 addresses find a minimal spanning subnet. Implementation must be efficient from CPU and memory perspective. Reasonable test coverage is a plus
|
753170768558ff9889e22c74626c5a53
|
{
"intermediate": 0.3009856045246124,
"beginner": 0.18202702701091766,
"expert": 0.5169873833656311
}
|
1,009
|
make an html page that has a a section with text field for the name of a bookmarklet and another text box for the bookmarklets code and another for the bookmarklets description, and there is a button that lets you add another one of these sections and each section should have a button to delete the section and the page should have a button to generate page which makes a link for the code for an html page that displays the bookmarklets as links (with the text inputted as the bookmarklet name) and displays each bookmarklets description
|
f4e114188a863ef02d6c8ce809a688a4
|
{
"intermediate": 0.38635390996932983,
"beginner": 0.20436318218708038,
"expert": 0.40928298234939575
}
|
1,010
|
java code for bubble sort
|
90db3e8d7abed405f555e0782860e5c2
|
{
"intermediate": 0.3983897566795349,
"beginner": 0.22262521088123322,
"expert": 0.3789850175380707
}
|
1,011
|
make an html page that has a a section with text field for the name of a bookmarklet and another text box for the bookmarklets code and another for the bookmarklets description, and there is a button that lets you add another one of these sections and each section should have a button to delete the section and the page should have a button to generate page which makes a link for the code for an html page that displays the bookmarklets as links (with the text inputted as the bookmarklet name) and displays each bookmarklets description
|
60d02f634af3ae4617e25843e032e81a
|
{
"intermediate": 0.36905357241630554,
"beginner": 0.21349945664405823,
"expert": 0.41744691133499146
}
|
1,012
|
can you make me an realistic smooth ragdoll script for roblox lua?
|
c6c537af53bb9d0387c65688d4b04f0e
|
{
"intermediate": 0.3430687189102173,
"beginner": 0.22895219922065735,
"expert": 0.42797914147377014
}
|
1,013
|
hey! can you help me with some roblox lua code?
|
b9db748ed908b609d796033601218182
|
{
"intermediate": 0.4792706370353699,
"beginner": 0.2731526494026184,
"expert": 0.2475767284631729
}
|
1,014
|
for this html page make the generate page button generate the code for an html page that displays the bookmarklets as links with the text inputted in as the bookmarklets name and displays each bookmarklets description: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Bookmarklets</title> <style> .bookmarklet-section { margin-bottom: 1em; padding: 1em; border: 1px solid black; } .bookmarklet-section input[type="text"] { display: block; margin-bottom: 0.5em; } .bookmarklet-section button { margin-top: 0.5em; } </style> </head> <body> <h1>Bookmarklets</h1> <div id="bookmarklet-sections"> <div class="bookmarklet-section"> <input type="text" placeholder="Bookmarklet name"> <input type="text" placeholder="Bookmarklet code"> <input type="text" placeholder="Bookmarklet description"> <button onclick="removeBookmarkletSection(this)">Remove</button> </div> </div> <button onclick="addBookmarkletSection()">Add bookmarklet</button> <button onclick="generatePage()">Generate page</button> <script> function addBookmarkletSection() { const bookmarkletSections = document.getElementById("bookmarklet-sections"); const newBookmarkletSection = document.createElement("div"); newBookmarkletSection.classList.add("bookmarklet-section"); newBookmarkletSection.innerHTML = ` <input type="text" placeholder="Bookmarklet name"> <input type="text" placeholder="Bookmarklet code"> <input type="text" placeholder="Bookmarklet description"> <button onclick="removeBookmarkletSection(this)">Remove</button> `; bookmarkletSections.appendChild(newBookmarkletSection); } function removeBookmarkletSection(button) { const bookmarkletSection = button.parentNode; bookmarkletSection.parentNode.removeChild(bookmarkletSection); } function generatePage() { const bookmarkletSections = document.querySelectorAll(".bookmarklet-section"); let html = "<ul>"; for (let i = 0; i < bookmarkletSections.length; i++) { const name = bookmarkletSections[i].querySelectorAll("input").value; const code = bookmarkletSections[i].querySelectorAll("input")[1].value; const description = bookmarkletSections[i].querySelectorAll("input")[2].value; html += `<li><a href="javascript:${code}">${name}</a>: ${description}</li>`; } html += "</ul>"; const link = document.createElement("a"); link.href = "data:text/html," + encodeURIComponent(html); link.download = "bookmarklets.html"; link.click(); } </script> </body> </html>
|
8ddc4596566c84ca8af3fe661011aee9
|
{
"intermediate": 0.46159690618515015,
"beginner": 0.3616940379142761,
"expert": 0.17670905590057373
}
|
1,015
|
for this html page make the generate page button generate the code for an html page that displays the bookmarklets as links with the text inputted in as the bookmarklets name and displays each bookmarklets description: " <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Bookmarklets</title> <style> .bookmarklet-section { margin-bottom: 1em; padding: 1em; border: 1px solid black; } .bookmarklet-section input[type="text"] { display: block; margin-bottom: 0.5em; } .bookmarklet-section button { margin-top: 0.5em; } </style> </head> <body> <h1>Bookmarklets</h1> <div id="bookmarklet-sections"> <div class="bookmarklet-section"> <input type="text" placeholder="Bookmarklet name"> <input type="text" placeholder="Bookmarklet code"> <input type="text" placeholder="Bookmarklet description"> <button onclick="removeBookmarkletSection(this)">Remove</button> </div> </div> <button onclick="addBookmarkletSection()">Add bookmarklet</button> <button onclick="generatePage()">Generate page</button> <script> function addBookmarkletSection() { const bookmarkletSections = document.getElementById("bookmarklet-sections"); const newBookmarkletSection = document.createElement("div"); newBookmarkletSection.classList.add("bookmarklet-section"); newBookmarkletSection.innerHTML = ` <input type="text" placeholder="Bookmarklet name"> <input type="text" placeholder="Bookmarklet code"> <input type="text" placeholder="Bookmarklet description"> <button onclick="removeBookmarkletSection(this)">Remove</button> `; bookmarkletSections.appendChild(newBookmarkletSection); } function removeBookmarkletSection(button) { const bookmarkletSection = button.parentNode; bookmarkletSection.parentNode.removeChild(bookmarkletSection); } function generatePage() { const bookmarkletSections = document.querySelectorAll(".bookmarklet-section"); let html = "<ul>"; for (let i = 0; i < bookmarkletSections.length; i++) { const name = bookmarkletSections[i].querySelectorAll("input").value; const code = bookmarkletSections[i].querySelectorAll("input")[1].value; const description = bookmarkletSections[i].querySelectorAll("input")[2].value; html += `<li><a href="javascript:${code}">${name}</a>: ${description}</li>`; } html += "</ul>"; const link = document.createElement("a"); link.href = "data:text/html," + encodeURIComponent(html); link.download = "bookmarklets.html"; link.click(); } </script> </body> </html>"
|
09cbca73d869f2c5bc8ea361a79a5fe3
|
{
"intermediate": 0.47377681732177734,
"beginner": 0.35834676027297974,
"expert": 0.16787636280059814
}
|
1,016
|
java code for bubble sort
|
24053bbd72c381099f33f51fd11e2231
|
{
"intermediate": 0.3983897566795349,
"beginner": 0.22262521088123322,
"expert": 0.3789850175380707
}
|
1,017
|
Help me create an SQLite database in C#.
A user has a string Id of ~11 digits
A card has a string Id of 10-18 digits
and a double units prop
and an int remaining prop
and an int timestamp
each user can have multiple cards.
Write a full example in C# with SQLite, (insert, delete, update).
Write a GetOrAdd method for users and cards so I can get if exists or add it.
|
5a2b4569865cbd08298af94c8a831752
|
{
"intermediate": 0.5911797881126404,
"beginner": 0.15601108968257904,
"expert": 0.2528090178966522
}
|
1,018
|
support nullable notations
|
2bfcca22933c3f42ccdf8e2716c6588b
|
{
"intermediate": 0.3262738883495331,
"beginner": 0.34044933319091797,
"expert": 0.33327674865722656
}
|
1,019
|
Help me create an SQLite database in C#.
A user has a string Id of ~11 digits
A card has a string Id of 10-18 digits
and a double units prop
and an int remaining prop
and a long timestamp
a card doesn't have to be associated to a user.
a user can have multiple cards.
I want to keep track of what cards a user used and at which time (timestamp).
Write a full example in C# with SQLite, (insert, delete, update).
Write a GetOrAdd method for users and cards so I can get it if exists or add it.
|
4c1c13f2fda246167f08ed072a5dab03
|
{
"intermediate": 0.5346965789794922,
"beginner": 0.2241896390914917,
"expert": 0.2411138266324997
}
|
1,020
|
hey, can you help me with roblox coding real quick?
|
226b7fb117fd3f496c5be36a57ea713e
|
{
"intermediate": 0.28716105222702026,
"beginner": 0.5023998022079468,
"expert": 0.21043916046619415
}
|
1,021
|
hey! i need you to help me with a roblox r6 ragdoll system that only triggers with a remote event, so i got this script in serverscriptservice:
local ragdollEvent = Instance.new("RemoteEvent")
ragdollEvent.Name = "RagdollEvent"
ragdollEvent.Parent = game:GetService("ReplicatedStorage")
local function ragdollPlayer(player)
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:FindFirstChildOfClass("Humanoid")
local ragdoll = Instance.new("Model")
ragdoll.Name = "Ragdoll"
ragdoll.Parent = humanoid
if humanoid.RigType == Enum.HumanoidRigType.R6 then
local ragdoll = humanoid:FindFirstChild("Ragdoll")
local torso = character:FindFirstChild("Torso") or character:FindFirstChild("UpperTorso")
if not ragdoll then
print("Ragdoll object not found in humanoid.")
return
elseif character:FindFirstChild("Ragdoll") then
print("Character is already ragdolled.")
return
end
-- Create a new humanoid object
local newHumanoid = Instance.new("Humanoid")
newHumanoid.Name = "Humanoid"
newHumanoid.Health = humanoid.Health
newHumanoid.MaxHealth = humanoid.MaxHealth
newHumanoid.WalkSpeed = humanoid.WalkSpeed
newHumanoid.JumpPower = humanoid.JumpPower
newHumanoid.MoveTo = humanoid.MoveTo
newHumanoid.AutoRotate = humanoid.AutoRotate
newHumanoid.Team = humanoid.Team
newHumanoid.PlatformStand = humanoid.PlatformStand
newHumanoid.RootPart = humanoid.RootPart
local rootPart = character:FindFirstChild("HumanoidRootPart") or character:FindFirstChild("LowerTorso")
rootPart.Velocity = humanoid.RootPart.Velocity
humanoid:Destroy()
ragdoll:Clone().Parent = character
torso.Anchored = true
wait(2)
torso.Anchored = false
newHumanoid.Parent = character
else
print("Character is not an R6 model.")
end
end
ragdollEvent.OnServerEvent:Connect(function(player)
ragdollPlayer(player)
end)
i already tested it and it gave me this problem: "MoveTo is not a valid member of Humanoid "Humanoid""
|
b3de0de847511b7dbe273c5e49244b57
|
{
"intermediate": 0.31510475277900696,
"beginner": 0.5172446966171265,
"expert": 0.16765058040618896
}
|
1,022
|
hey
|
01dd60a0222c02e43c2a04e6bd5985ed
|
{
"intermediate": 0.33180856704711914,
"beginner": 0.2916048467159271,
"expert": 0.3765866458415985
}
|
1,023
|
explain to me how the most easy algorithm for creating a maze can be coded in C#
|
31398152f69f35e31806f8efd5271ccc
|
{
"intermediate": 0.13891729712486267,
"beginner": 0.053485214710235596,
"expert": 0.8075974583625793
}
|
1,024
|
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.EditText;
import android.view.inputmethod.EditorInfo;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<Item> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
if (i == EditorInfo.IME_ACTION_DONE) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName); // Retrieve data for entered node name
}
return true;
}
return false;
});
}
private void retrieveData(String nodeName) {
DatabaseReference myRef = mDatabaseRef.child(nodeName); // Get reference for entered node name
// Add the rest of your Click methods and existing code
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String name = childSnapshot.getKey();
String data = childSnapshot.getValue().toString();
TextView nameTextView = new TextView(Result.this);
nameTextView.setText(name);
// Add any TextView attributes you need here
TextView dataTextView = new TextView(Result.this);
dataTextView.setText(data);
// Add any TextView attributes you need here
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
|
0322511a1c87358ff50058a4875d6847
|
{
"intermediate": 0.3910902738571167,
"beginner": 0.3808079957962036,
"expert": 0.2281017303466797
}
|
1,025
|
hey, can you help me in roblox coding?
|
486c185eafe045fbc4f784324b70d13c
|
{
"intermediate": 0.24898472428321838,
"beginner": 0.5913202166557312,
"expert": 0.15969513356685638
}
|
1,026
|
tell a good joke in the style of a stand up comedian
|
cf3d7afe0cfd1c0605b5f9ccb944067f
|
{
"intermediate": 0.37849611043930054,
"beginner": 0.383835107088089,
"expert": 0.23766878247261047
}
|
1,027
|
Hello, Can you tell me how to code a gamepad deplacement of an object within a 3D space with collision checks on flat ground and walls in GDscript please ?
|
f39d8f8b258ad2613cd41f5c1fc2bf6b
|
{
"intermediate": 0.5327051877975464,
"beginner": 0.20796403288841248,
"expert": 0.2593308091163635
}
|
1,028
|
with python: loop for everyline of a .txt that cointains the 'cityname,countyname' , do this for every 'presentname' that i listed for you
import prettymaps
plot = prettymaps.plot(
'cityname, countryname',
preset = 'presentname'
)
'presentname':
barcelona
barcelona-plotter
cb-bf-f
default
heerhugowaard
macao
minimal
tijuca
|
882518d652cfd370c7e174aefda70c6c
|
{
"intermediate": 0.1581438183784485,
"beginner": 0.7152864336967468,
"expert": 0.1265696883201599
}
|
1,029
|
with python: loop for everyline of a .txt that cointains the 'cityname,countyname' , do this for every 'presentname' that i listed for you
import prettymaps
plot = prettymaps.plot(
'cityname, countryname',
preset = 'presentname'
)
'presentname':
barcelona
barcelona-plotter
cb-bf-f
default
heerhugowaard
macao
minimal
tijuca
|
08c3a1ae8e208d50e6ef92ba4bb077f8
|
{
"intermediate": 0.1581438183784485,
"beginner": 0.7152864336967468,
"expert": 0.1265696883201599
}
|
1,030
|
hey, can you help me with roblox coding?
|
300d70c6c5a2e17d404d18e1e589fda0
|
{
"intermediate": 0.264578253030777,
"beginner": 0.5621066689491272,
"expert": 0.17331503331661224
}
|
1,031
|
rewrite this code to use the `&` operator:
|
d72b22eaeafa806ca39a5fcbe2bd4a7e
|
{
"intermediate": 0.342947393655777,
"beginner": 0.29772913455963135,
"expert": 0.35932353138923645
}
|
1,032
|
Result.Java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.EditText;
import android.view.inputmethod.EditorInfo;
import android.util.Log;
import android.text.InputType;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<Pair<String, String>> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.setInputType(InputType.TYPE_CLASS_TEXT);
mNodeNameEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
if (i == EditorInfo.IME_ACTION_DONE) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName); // Retrieve data for entered node name
}
return true;
}
return false;
});
}
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber); // Get reference for entered phone number
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mData.clear(); // Clear the previous data
// Loop through all child nodes (unique identifiers)
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
// Loop through each child node's content
for (DataSnapshot contentSnapshot : idSnapshot.getChildren()) {
String name = contentSnapshot.getKey();
String data = contentSnapshot.getValue().toString();
mData.add(new Pair<>(name, data)); // Add the key-value pair to the data list
}
}
mAdapter.notifyDataSetChanged(); // Notify the adapter about the data change
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
inputting phonenumber is empty
|
4da96becbb35fffb27fd84ffbc855835
|
{
"intermediate": 0.38594353199005127,
"beginner": 0.3881582021713257,
"expert": 0.22589826583862305
}
|
1,033
|
voce conhece o caso da escola de base no brazil?
|
3ac459c402b0ea449e100f908cadaa57
|
{
"intermediate": 0.36094674468040466,
"beginner": 0.2857836186885834,
"expert": 0.3532695770263672
}
|
1,034
|
tell pip to uninstall those packages
pip install matplotlib==3.4.3
pip install geopandas==0.9.0
pip install numpy==1.21.1
pip install pandas==1.3.2
pip install rasterio==1.2.6
pip install scipy==1.7.0
pip install Shapely==1.7.1
pip install requests==2.26.0
|
77672a7ab68afb6a57dcf3dae0896453
|
{
"intermediate": 0.5987911224365234,
"beginner": 0.21398425102233887,
"expert": 0.18722453713417053
}
|
1,035
|
hi
|
1b238aa3f92d31469f212bd140c21d9d
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
1,036
|
hey, can you help me with roblox coding?
|
3bfe752f947b762117afd756aa824085
|
{
"intermediate": 0.264578253030777,
"beginner": 0.5621066689491272,
"expert": 0.17331503331661224
}
|
1,037
|
hey, can you help me with roblox coding?
|
099b0364e5bada01e2da1fb954ce867a
|
{
"intermediate": 0.264578253030777,
"beginner": 0.5621066689491272,
"expert": 0.17331503331661224
}
|
1,038
|
What was my last message?
|
047a4c8edb8b6f9ccc48e03983bbc4fc
|
{
"intermediate": 0.37803348898887634,
"beginner": 0.2957867980003357,
"expert": 0.32617977261543274
}
|
1,039
|
You are an AI programming assistant. - Follow the user's requirements carefully and to the letter. - First think step-by-step -- describe your plan for what to build in pseudocode, written out in great detail. - Then output the code in a single code block. - Minimize any other prose.
|
96b4bf347dcfa988557dc25750321ba6
|
{
"intermediate": 0.16277837753295898,
"beginner": 0.22265957295894623,
"expert": 0.6145620346069336
}
|
1,040
|
I am trying to display data from a firebase database to a recycle view and I am having a problem with displaying the data when I input the number and it display nothing and I am using this code
result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.EditText;
import android.view.inputmethod.EditorInfo;
import android.util.Log;
import android.text.InputType;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<Pair<String, String>> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.setInputType(InputType.TYPE_CLASS_TEXT);
mNodeNameEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
if (i == EditorInfo.IME_ACTION_DONE) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName); // Retrieve data for entered node name
} else {
// Display a toast to ask the user to provide input
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
return true;
}
return false;
});
}
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber); // Get reference for entered phone number
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mData.clear(); // Clear the previous data
// Loop through all child nodes (unique identifiers)
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
String name = idSnapshot.child("soreness_label").getValue().toString();
String emgData = idSnapshot.child("emg_data").getValue().toString();
String gsrData = idSnapshot.child("gsr_data").getValue().toString();
String timestamp = idSnapshot.child("timestamp").getValue().toString();
mData.add(new Pair<>("Soreness Label", name));
mData.add(new Pair<>("EMG Data", emgData));
mData.add(new Pair<>("GSR Data", gsrData));
mData.add(new Pair<>("Timestamp", timestamp));
}
mAdapter.notifyDataSetChanged(); // Notify the adapter about the data change
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
this is the structure of the database
/users/09123456789/-NT4APgDfX15GW0fi1pP
-NT4APgDfX15GW0fi1pP
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
|
de6d281ae13a2130c66932ff70eaffc8
|
{
"intermediate": 0.45744016766548157,
"beginner": 0.4247349202632904,
"expert": 0.11782486736774445
}
|
1,041
|
add a method to check if a card exists,
add a method to check if a user has a card.
|
4c9b1ad0d3161c5d9b5a8de78b73f719
|
{
"intermediate": 0.3825254440307617,
"beginner": 0.1738075464963913,
"expert": 0.4436670243740082
}
|
1,042
|
with python: loop for everyline of a .txt that cointains the 'cityname,countyname' , do this for every 'presentname' that i listed for you
import prettymaps
plot = prettymaps.plot(
'cityname, countryname',
preset = 'presentname'
)
'presentname':
barcelona
barcelona-plotter
cb-bf-f
default
heerhugowaard
macao
minimal
tijuca
|
5344368ea9269b3cf7d49a3a226a6e4e
|
{
"intermediate": 0.1581438183784485,
"beginner": 0.7152864336967468,
"expert": 0.1265696883201599
}
|
1,043
|
c# datetime to unix timestamp milliseconds
|
52f5dafa9caa5e8f5be2f0f4d3225d5e
|
{
"intermediate": 0.44076618552207947,
"beginner": 0.30947351455688477,
"expert": 0.24976028501987457
}
|
1,044
|
c# datetime to unix timestamp milliseconds
|
7030098e880180aa9f6a9ed0d39c4a6a
|
{
"intermediate": 0.44076618552207947,
"beginner": 0.30947351455688477,
"expert": 0.24976028501987457
}
|
1,045
|
I am using a recycleview to display data from firebase database but i am having trouble displaying it for context I will put the codes here
result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<Pair<String, String>> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
};
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn't exist");
}
mData.clear();
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new Pair<>("Soreness Label", userData.soreness_label));
mData.add(new Pair<>("EMG Data", userData.emg_data));
mData.add(new Pair<>("GSR Data", userData.gsr_data));
mData.add(new Pair<>("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
userdata.java
package com.example.profile;
public class UserData {
public String emg_data;
public String gsr_data;
public String soreness_label;
public String timestamp;
public UserData() {
}
@Override
public String toString() {
return "UserData{" +
"emg_data='" + emg_data + "'" +
", gsr_data='" + gsr_data + "'" +
", soreness_label='" + soreness_label + "'" +
", timestamp='" + timestamp + "'" +
'}';
}
}
recycleviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.profile.R;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<Pair<String, String>> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<Pair<String, String>> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Pair<String, String> pair = mData.get(position);
holder.nameTextView.setText(pair.first);
holder.dataTextView.setText(pair.second);
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
googlebase structure
/users/09123456789/-NT4APgDfX15GW0fi1pP
-NT4APgDfX15GW0fi1pP
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
|
54512bbd88aa950e49dea434f28f7e39
|
{
"intermediate": 0.4149462878704071,
"beginner": 0.4102369248867035,
"expert": 0.17481684684753418
}
|
1,046
|
which legal method on https://www.blackhatworld.com/ can be automated with programming
|
76c8c5bdf305cfb7b6edbb703a110c20
|
{
"intermediate": 0.26258569955825806,
"beginner": 0.2892262041568756,
"expert": 0.4481881260871887
}
|
1,047
|
which legal method on https://www.blackhatworld.com/ can YOU automated with programming
|
6c3b9963110b17b98ec0f83d0c4eef2c
|
{
"intermediate": 0.2889062166213989,
"beginner": 0.26097068190574646,
"expert": 0.4501231014728546
}
|
1,048
|
write a C# code to add to a SQLite table only if not exist
|
0604b56f008a86586cdb483300ab6d1b
|
{
"intermediate": 0.4982677400112152,
"beginner": 0.23541781306266785,
"expert": 0.26631447672843933
}
|
1,049
|
In google jupyter notebook, how to copy, move files, and make perfect codes to upload file browser in colab notebook
|
64810dd312e2461832b2da03eda9e0aa
|
{
"intermediate": 0.5215624570846558,
"beginner": 0.2158658653497696,
"expert": 0.26257166266441345
}
|
1,050
|
Here is my code if you can optimize it further or if you have any comments let me know:
internal sealed class SqLiteDatabase
{
private readonly string _connectionString;
public SqLiteDatabase(string databaseName)
{
_connectionString = $"Data Source={databaseName}.db";
InitializeDatabase();
}
private void InitializeDatabase()
{
using var connection = new SQLiteConnection(_connectionString);
connection.Open();
var createUsersTableCommand = connection.CreateCommand();
createUsersTableCommand.CommandText =
@"
CREATE TABLE IF NOT EXISTS Users (
Id TEXT PRIMARY KEY
);
";
var createCardsTableCommand = connection.CreateCommand();
createCardsTableCommand.CommandText =
@"
CREATE TABLE IF NOT EXISTS Cards (
Id TEXT PRIMARY KEY,
Units REAL,
Remaining INTEGER,
Timestamp INTEGER
);
";
var createUserCardsTableCommand = connection.CreateCommand();
createUserCardsTableCommand.CommandText =
@"
CREATE TABLE IF NOT EXISTS UserCards (
UserId TEXT,
CardId TEXT,
Timestamp INTEGER,
PRIMARY KEY(UserId, CardId),
FOREIGN KEY(UserId) REFERENCES Users(Id),
FOREIGN KEY(CardId) REFERENCES Cards(Id)
);
";
createUsersTableCommand.ExecuteNonQuery();
createCardsTableCommand.ExecuteNonQuery();
createUserCardsTableCommand.ExecuteNonQuery();
}
public User GetOrAddUser(string userId)
{
var user = GetUser(userId);
if (user == null)
{
user = new User(userId);
AddOrUpdateUser(user);
}
return user;
}
public void AddOrUpdateUser(User user)
{
using var connection = new SQLiteConnection(_connectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText =
@"
INSERT OR REPLACE INTO Users (Id)
VALUES (@Id);
";
command.Parameters.AddWithValue("@Id", user.Id);
command.ExecuteNonQuery();
foreach (var card in user.Cards)
{
AddOrUpdateCard(card);
AssignCardToUser(user.Id, card.Id, card.Timestamp);
}
transaction.Commit();
}
public User? GetUser(string userId)
{
using var connection = new SQLiteConnection(_connectionString);
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
@"
SELECT Id FROM Users WHERE Id = @UserId;
";
command.Parameters.AddWithValue("@UserId", userId);
using var reader = command.ExecuteReader();
if (!reader.Read()) return null;
var id = reader.GetString(0);
var user = new User(id, GetUserCards(id));
return user;
}
private IEnumerable<Card> GetUserCards(string userId)
{
using var connection = new SQLiteConnection(_connectionString);
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
@"
SELECT Cards.Id, Units, Remaining, Cards.Timestamp
FROM Cards
JOIN UserCards ON Cards.Id = UserCards.CardId
WHERE UserCards.UserId = @UserId;
";
command.Parameters.AddWithValue("@UserId", userId);
using var reader = command.ExecuteReader();
while (reader.Read())
{
yield return new Card(
reader.GetString(0),
reader.GetDouble(1),
reader.GetInt32(2),
reader.GetInt64(3)
);
}
}
public void AddOrUpdateCard(Card card)
{
using var connection = new SQLiteConnection(_connectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText =
@"
INSERT OR REPLACE INTO Cards (Id, Units, Remaining, Timestamp)
VALUES (@Id, @Units, @Remaining, @Timestamp);
";
command.Parameters.AddWithValue("@Id", card.Id);
command.Parameters.AddWithValue("@Units", card.Units);
command.Parameters.AddWithValue("@Remaining", card.Remaining);
command.Parameters.AddWithValue("@Timestamp", card.Timestamp);
command.ExecuteNonQuery();
transaction.Commit();
}
public Card? GetCard(string cardId)
{
using var connection = new SQLiteConnection(_connectionString);
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
@"
SELECT Id, Units, Remaining, Timestamp FROM Cards WHERE Id = @CardId;
";
command.Parameters.AddWithValue("@CardId", cardId);
using var reader = command.ExecuteReader();
if (reader.Read())
{
return new Card(
reader.GetString(0),
reader.GetDouble(1),
reader.GetInt32(2),
reader.GetInt64(3)
);
}
return null;
}
public void AssignCardToUser(string userId, string cardId, long timestamp)
{
using var connection = new SQLiteConnection(_connectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText =
@"
INSERT OR REPLACE INTO UserCards (UserId, CardId, Timestamp)
VALUES (@UserId, @CardId, @Timestamp);
";
command.Parameters.AddWithValue("@UserId", userId);
command.Parameters.AddWithValue("@CardId", cardId);
command.Parameters.AddWithValue("@Timestamp", timestamp);
command.ExecuteNonQuery();
transaction.Commit();
}
}
|
c7a4aa969b173264b7b15778fbdb631a
|
{
"intermediate": 0.2255898416042328,
"beginner": 0.5100894570350647,
"expert": 0.2643207013607025
}
|
1,051
|
I am using a recycleview to display data from firebase database but i am having trouble displaying it for context I will put the codes here
result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = “Result”;
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<Pair<String, String>> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference(“users”);
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, “Please enter a phone number”, Toast.LENGTH_SHORT).show();
}
}
};
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, “Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, “Data snapshot doesn’t exist”);
}
mData.clear();
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, “Data received: " + userData.toString());
mData.add(new Pair<>(“Soreness Label”, userData.soreness_label));
mData.add(new Pair<>(“EMG Data”, userData.emg_data));
mData.add(new Pair<>(“GSR Data”, userData.gsr_data));
mData.add(new Pair<>(“Timestamp”, userData.timestamp));
} else {
Log.d(TAG, “UserData object is null”);
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, “Failed to read value.”, databaseError.toException());
}
});
}
}
activity_result.xml
<?xml version=“1.0” encoding=“utf-8”?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/res-auto”
xmlns:tools=“http://schemas.android.com/tools”
android:id=”@+id/drawer_activity”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=“.Result”>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width=“match_parent”
android:layout_height=“match_parent”>
<EditText
android:id=“@+id/node_name_edit_text”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:layout_margin=“8dp”
android:hint=“Enter node name”
app:layout_constraintTop_toTopOf=“parent” />
<androidx.recyclerview.widget.RecyclerView
android:id=“@+id/recycler_view”
android:layout_width=“match_parent”
android:layout_height=“0dp”
android:layout_marginTop=“8dp”
app:layout_constraintBottom_toBottomOf=“parent”
app:layout_constraintTop_toBottomOf=“@+id/node_name_edit_text” />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width=“300dp”
android:layout_height=“match_parent”
android:layout_gravity=“start”
android:background=“@color/white”>
<include layout=“@layout/main_navigation_drawer” />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
userdata.java
package com.example.profile;
public class UserData {
public String emg_data;
public String gsr_data;
public String soreness_label;
public String timestamp;
public UserData() {
}
@Override
public String toString() {
return “UserData{” +
“emg_data='” + emg_data + “'” +
“, gsr_data='” + gsr_data + “'” +
“, soreness_label='” + soreness_label + “'” +
“, timestamp='” + timestamp + “'” +
‘}’;
}
}
recycleviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.profile.R;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<Pair<String, String>> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<Pair<String, String>> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Pair<String, String> pair = mData.get(position);
holder.nameTextView.setText(pair.first);
holder.dataTextView.setText(pair.second);
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
googlebase structure
/users/09123456789/-NT4APgDfX15GW0fi1pP
-NT4APgDfX15GW0fi1pP
emg_data
:
930
gsr_data
:
394
soreness_label
:
“exhausted”
timestamp
:
“2023-04-15 06:49:33”
|
3e6154e505f871c4ba74d132e0ac5aef
|
{
"intermediate": 0.35667935013771057,
"beginner": 0.35746899247169495,
"expert": 0.2858516573905945
}
|
1,052
|
I have a User,Card classes in C#
each user can have multiple Cards.
a Card doesn't have to be associated to a user
Now a user have a int Id.
a card has int Id, int units, long timestamp.
keep in mind that each card a have also has a timestamp to tell when the user uses it, this timestamp is different from the card's timestamp.
How to structure this in C#?
|
f6db9d515f0165970266f76d72223e08
|
{
"intermediate": 0.48432061076164246,
"beginner": 0.3178686499595642,
"expert": 0.19781075417995453
}
|
1,053
|
create one sentence with each below words abandon absolute absorb abstract academic accent acceptable accidentally accommodate accompany accomplish account accountant accuracy accurate accurately accuse acid acknowledge acquire activate actual adapt addiction additional additionally address adequate adequately adjust administration adopt advance advance advance affair affordable afterwards agency agenda aggressive agriculture aid aid AIDS aircraft alarm alien alongside alter altogether ambulance amount amusing analyst ancestor anger angle animation anniversary annual annually anticipate anxiety anxious apology apparent apparently appeal appeal applicant approach approach appropriate appropriately approval approve arise armed arms arrow artificial artistic artwork ashamed aside aspect assess assessment asset assign assistance associate associated association assume assumption assure astonishing attachment attempt attempt auction audio automatic automatically awareness awkward back bacteria badge balanced ballet balloon bar barely bargain barrier basement basically basket bat battle bear beat beg being beneficial bent beside besides
|
3d02077f03c7f9ada376394458235a68
|
{
"intermediate": 0.3841795027256012,
"beginner": 0.272943913936615,
"expert": 0.34287652373313904
}
|
1,054
|
I am using a recycleview to display data from firebase database but i am having trouble displaying it for context I will put the codes here
Result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<UserItem> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
};
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn’t exist");
}
mData.clear();
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data));
mData.add(new UserItem("GSR Data", userData.gsr_data));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
activity_result.java
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="14sp" />
</LinearLayout>
UserItem.Java
package com.example.profile;
public class UserItem {
private String name;
private String data;
public UserItem(String name, String data) {
this.name = name;
this.data = data;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
recyclerviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UserItem> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<UserItem> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
UserItem userItem = mData.get(position);
holder.nameTextView.setText(userItem.getName());
holder.dataTextView.setText(userItem.getData());
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
build.gradle
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
namespace 'com.example.profile'
compileSdk 33
defaultConfig {
applicationId "com.example.profile"
minSdk 30
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.3.0'
implementation 'com.google.firebase:firebase-analytics:21.2.1'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
firebase structure
https://test1-5f6a3-default-rtdb.firebaseio.com/users/09123456789/-NT4APgDfX15GW0fi1pP
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
|
0e2587732994c9a63d533c04814e4fff
|
{
"intermediate": 0.3962143659591675,
"beginner": 0.37551969289779663,
"expert": 0.22826595604419708
}
|
1,055
|
I want you to act as Senior Developer. I don't like this code, how it can be improved? Try to use SOLID principles and design patterns
The code:
using System;
using UnityEngine;
using FluidHTN;
using Pathfinding;
using CodeMonkey.HealthSystemCM;
using System.Collections.Specialized;
using SaveLoadSystem;
namespace src
{
[RequireComponent(typeof(MemoryManager), typeof(AgentInventory), typeof(SaveableEntity))]
public class NPCAgent : AUpdater, ISaveable
{
public bool DebugContext = false;
private AIDomainDefinition _domainDefinition;
private Planner<AIContext> _planner;
private Domain<AIContext> _domain;
private AIContext _context;
private SensorySystem _sensory;
private AgentAccess _agentAccess;
#pragma warning disable IDE0044
[MyBox.MustBeAssigned]
[SerializeField]
private GameObject _healthBar;
#pragma warning restore IDE0044
private GameObject _healthBarInstance;
private HealthSystem _healthSystem;
private MemoryManager _memory;
private AgentInventory _inventory;
private AgentCharacteristics _characteristics;
private AIPath _aIPath;
private AgentPhysics _physics;
public AIDestinationSetter AIDestinationSetter {get; private set; }
[SerializeField]
/// <summary>
/// Object to move, talk or attack.
/// </summary>
public GameObject CurrentTargetToMove;
public Transform AgentTransform { get; private set; }
public Quaternion AgentRotation { get => _aIPath.rotation;
set => _aIPath.rotation = value;
}
protected void Awake()
{
AIDestinationSetter = GetComponent<AIDestinationSetter>();
AgentTransform = transform;
_aIPath = GetComponent<AIPath>();
_physics = GetComponent<AgentPhysics>();
_healthSystem = GetComponent<HealthSystemComponent>().GetHealthSystem();
_healthSystem.OnDead += SetDead;
_memory = GetComponent<MemoryManager>();
_inventory = GetComponent<AgentInventory>();
_inventory.OnItemsUpdated += SetState;
_inventory.ItemsInPickupRanger.CollectionChanged += OnListChanged;
_characteristics = GetComponent<AgentCharacteristics>();
_characteristics.IsAlive = !_healthSystem.IsDead();
_domainDefinition = _characteristics.DomainDefinition;
_agentAccess = new AgentAccess(this, _memory, _inventory);
SetHTN();
SetDefaultWorldStates();
SpawnAndSetHealthBar();
_memory.WorldStates = _context.WorldState;
}
private void SetHTN()
{
if (_domainDefinition == null)
{
Debug.LogError($"Missing domain definition in {name}!");
return;
}
_planner = new Planner<AIContext>();
_context = new AIContext(_agentAccess, DebugContext);
_sensory = new SensorySystem(this);
_domain = _domainDefinition.Create();
}
private void SetDefaultWorldStates()
{
_context.SetState(AIWorldState.CanMove, true, EffectType.Permanent);
_context.SetState(AIWorldState.HasTargetToMove, false, EffectType.Permanent);
_context.SetState(AIWorldState.IsInSafePlace, false, EffectType.Permanent);
_context.SetState(AIWorldState.HasHumanInSensors, false, EffectType.Permanent);
_context.SetState(AIWorldState.HasItemInPickupRanger, false, EffectType.Permanent);
_context.SetState(AIWorldState.HasAmmoInWeapon, true, EffectType.Permanent);
}
private void OnListChanged(object sender, NotifyCollectionChangedEventArgs args)
{
_context.SetState(AIWorldState.HasItemInPickupRanger, _inventory.ItemsInPickupRanger.Count > 0, EffectType.Permanent);
}
public override void UpdateGObject()
{
if (_planner == null || _domain == null || _context == null)
{
Debug.LogError($"Missing HTN Element in {name}!");
return;
}
IfAgentAlive();
}
private void IfAgentAlive()
{
if (!_characteristics.IsAlive) return;
_context.Time = Time.time;
_context.DeltaTime = Time.deltaTime;
_sensory.Tick(_context);
_planner.Tick(_domain, _context);
UpdateHealthBarPosition();
DebugPlan();
}
private void DebugPlan()
{
if (!DebugContext) return;
foreach (var log in _context.MTRDebug)
{
Debug.Log(name +" " + log);
}
}
private void SpawnAndSetHealthBar()
{
if (_healthBar == null)
{
Debug.LogError($"Missing health bar prefab in {name}!");
return;
}
var healthBarIns = Instantiate(_healthBar, transform);
healthBarIns.GetComponentInChildren<HealthBarUI>().SetHealthSystem(_healthSystem);
_healthBarInstance = new GameObject(name + " Health_Bar");
healthBarIns.gameObject.transform.SetParent(_healthBarInstance.transform, false);
_healthBarInstance.transform.SetParent(transform.parent, false);
}
private void UpdateHealthBarPosition()
{
if (_healthBarInstance == null)
return;
_healthBarInstance.transform.position = transform.position;
}
private void SetState(AIWorldState state, bool value)
{
_context.SetState(state, value, EffectType.Permanent);
}
private void SetDead(object sender, System.EventArgs e)
{
_characteristics.IsAlive = false;
_context.SetState(AIWorldState.CanMove, false, EffectType.Permanent);
_aIPath.canMove = false;
_physics.Collider.isTrigger = true;
}
public bool NeedsToBeSaved()
{
return true;
}
public bool NeedsReinstantiation()
{
return true;
}
public object SaveState()
{
SaveableEntity.Vector3Data targetPos;
bool hasTarget;
if (CurrentTargetToMove != null)
{
targetPos = new SaveableEntity.Vector3Data(CurrentTargetToMove.transform.position);
hasTarget = true;
}
else
{
targetPos = new SaveableEntity.Vector3Data();
hasTarget = false;
}
return new NPCAgentData()
{
maxHealth = _healthSystem.GetHealthMax(),
currentHealth = _healthSystem.GetHealth(),
targetPosition = targetPos,
hasTarget = hasTarget,
isAlive = _characteristics.IsAlive,
canMove = _aIPath.canMove,
isTrigger = _physics.Collider.isTrigger,
worldState = _context.WorldState,
};
}
public void LoadState(object state)
{
NPCAgentData data = (NPCAgentData)state;
_healthSystem.SetHealthMax(data.maxHealth, false);
_healthSystem.SetHealth(data.currentHealth);
_characteristics.IsAlive = data.isAlive;
_aIPath.canMove = data.canMove;
_physics.Collider.isTrigger = data.isTrigger;
}
public void PostInstantiation(object state)
{
NPCAgentData data = (NPCAgentData)state;
if (data.hasTarget)
{
CurrentTargetToMove = PoolSystem.Instance.PoolEmpty.Get();
CurrentTargetToMove.transform.position = data.targetPosition.ToVector3();
}
_context.Reset();
_context.Init();
for (int i = 0; i < data.worldState.Length; i++)
{
_context.SetState((AIWorldState)i, data.worldState[i], EffectType.Permanent);
}
}
public void GotAddedAsChild(GameObject obj, GameObject hisParent)
{
//throw new NotImplementedException();
}
[System.Serializable]
struct NPCAgentData
{
public float maxHealth;
public float currentHealth;
public bool hasTarget;
public SaveableEntity.Vector3Data targetPosition;
public bool isAlive;
public bool canMove;
public bool isTrigger;
public byte[] worldState;
}
}
}
|
22c1599c7dd20c43b9ea03127fc94812
|
{
"intermediate": 0.3704977035522461,
"beginner": 0.35518619418144226,
"expert": 0.27431610226631165
}
|
1,056
|
I am using a recycleview to display data from firebase database but i am having trouble displaying it for context I will put the codes here
Result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<UserItem> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
};
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn't exist");
}
mData.clear();
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data.toString()));
mData.add(new UserItem("GSR Data", userData.gsr_data.toString()));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
UserData.java
package com.example.profile;
public class UserData {
public String soreness_label;
public Long emg_data;
public Long gsr_data;
public String timestamp;
public UserData() {
}
}
UserItem.Java
package com.example.profile;
public class UserItem {
private String name;
private String data;
public UserItem(String name, String data) {
this.name = name;
this.data = data;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
recyclerviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UserItem> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<UserItem> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
UserItem userItem = mData.get(position);
holder.nameTextView.setText(userItem.getName());
holder.dataTextView.setText(userItem.getData());
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="14sp" />
</LinearLayout>
build.gradle
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
namespace 'com.example.profile'
compileSdk 33
defaultConfig {
applicationId "com.example.profile"
minSdk 30
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.3.0'
implementation 'com.google.firebase:firebase-analytics:21.2.1'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
firebase structure
users to phonenumber to -NT4APgDfX15GW0fi1pP which contain this data and others like it:
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
|
3412ed75d60666dfd702836a62e7e437
|
{
"intermediate": 0.3745823800563812,
"beginner": 0.3596022129058838,
"expert": 0.2658153772354126
}
|
1,057
|
what google api service that get user location in an app
|
ecac947f22db58cddbea49246afdbfb0
|
{
"intermediate": 0.7291185855865479,
"beginner": 0.10606128722429276,
"expert": 0.16482016444206238
}
|
1,058
|
made me a simple calculator that has a diffrent interface when flipped into lanscape mode using swift, provide picture of the interface if you can do it
|
f369d9686fd10a461bd727e7b07ac939
|
{
"intermediate": 0.5038861632347107,
"beginner": 0.22097189724445343,
"expert": 0.2751418948173523
}
|
1,059
|
I am using a recycleview to display data from firebase database so that i can create a history table but i am having trouble displaying it for context I will put the codes here
Result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<UserItem> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
};
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn't exist");
}
mData.clear();
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", String.valueOf(userData.emg_data)));
mData.add(new UserItem("GSR Data", String.valueOf(userData.gsr_data)));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
UserData.java
package com.example.profile;
public class UserData {
public String soreness_label;
public String emg_data;
public String gsr_data;
public String timestamp;
public UserData() {
}
}
UserItem.Java
package com.example.profile;
public class UserItem {
private String name;
private String data;
public UserItem(String name, String data) {
this.name = name;
this.data = data;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
recyclerviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UserItem> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<UserItem> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
UserItem userItem = mData.get(position);
holder.nameTextView.setText(userItem.getName());
holder.dataTextView.setText(userItem.getData());
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="14sp" />
</LinearLayout>
build.gradle
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
namespace 'com.example.profile'
compileSdk 33
defaultConfig {
applicationId "com.example.profile"
minSdk 30
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.3.0'
implementation 'com.google.firebase:firebase-analytics:21.2.1'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
firebase structure
users to phonenumber to -NT4APgDfX15GW0fi1pP which contain this data and others like it:
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
|
4a5b82babb82b5fe3f8a966f852eeaca
|
{
"intermediate": 0.44860929250717163,
"beginner": 0.3195479214191437,
"expert": 0.2318427711725235
}
|
1,060
|
I am using a recycleview to display data from firebase database so that i can create a history table but i am having trouble displaying it for context I will put the codes here
Result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<UserItem> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
};
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn't exist");
}
mData.clear();
// Add a condition to check if the dataSnapshot key is equal to your specific ID.
if (dataSnapshot.getKey().equals("-NT4APgDfX15GW0fi1pP")) {
UserData userData = dataSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data));
mData.add(new UserItem("GSR Data", userData.gsr_data));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data));
mData.add(new UserItem("GSR Data", userData.gsr_data));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
UserData.java
package com.example.profile;
public class UserData {
public String soreness_label;
public String emg_data;
public String gsr_data;
public String timestamp;
public UserData() {
}
}
UserItem.Java
package com.example.profile;
public class UserItem {
private String name;
private String data;
public UserItem(String name, String data) {
this.name = name;
this.data = data;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
recyclerviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UserItem> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<UserItem> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
UserItem userItem = mData.get(position);
holder.nameTextView.setText(userItem.getName());
holder.dataTextView.setText(userItem.getData());
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
build.gradle
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
namespace 'com.example.profile'
compileSdk 33
defaultConfig {
applicationId "com.example.profile"
minSdk 30
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.3.0'
implementation 'com.google.firebase:firebase-analytics:21.2.1'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
firebase structure
users to phonenumber to -NT4APgDfX15GW0fi1pP which contain this data and others like it:
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
|
a4a82469746c783fe8529ec49acdbf84
|
{
"intermediate": 0.39344844222068787,
"beginner": 0.357442170381546,
"expert": 0.2491094022989273
}
|
1,061
|
Please demonstrate exponential backoff in rust
|
0ee8db5769c1a4cfd755e9d66ed1653c
|
{
"intermediate": 0.2721746861934662,
"beginner": 0.23531578481197357,
"expert": 0.49250954389572144
}
|
1,062
|
What is the likelihood of the beta distribution?
|
4f17004f2675e9b2d5f36b6578e25b80
|
{
"intermediate": 0.4233424961566925,
"beginner": 0.18688736855983734,
"expert": 0.38977017998695374
}
|
1,063
|
create an app or a minigame with the purpose of publishing it and making some money
|
c0e394ed7b1bccb37a8f73e8f8f1b43f
|
{
"intermediate": 0.29485005140304565,
"beginner": 0.31180539727211,
"expert": 0.39334455132484436
}
|
1,064
|
How can the below class implement the IMap interface below?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
public class HashMap<K, V>
{
/* Properties */
public Entry<K, V>[] Table { get; set; }
public int Capacity { get; set; }
public double LoadFactor { get; set; }
public int size; // Field used since we need a Size() method to satisfy the tests.
public int Placeholders { get; set; } // Keeps track of the number of placeholders in the HashMap.
/* Constructors */
public HashMap()
{
this.Capacity = 11;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = 0.75;
this.size = 0;
}
public HashMap(int initialCapacity)
{
if (initialCapacity <= 0)
{
throw new ArgumentException();
}
this.Capacity = initialCapacity;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = 0.75;
this.size = 0;
}
public HashMap(int initialCapacity, double loadFactor)
{
if (initialCapacity <= 0 || loadFactor <= 0)
{
throw new ArgumentException();
}
this.Capacity = initialCapacity;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = loadFactor;
this.size = 0;
}
/* Methods */
public int Size()
{
return this.size;
}
public bool IsEmpty()
{
return this.size == 0;
}
public void Clear()
{
Array.Clear(this.Table, 0, this.Table.Length);
this.size = 0;
}
public int GetMatchingOrNextAvailableBucket(K key)
{
int startPosition = Math.Abs(key.GetHashCode()) % this.Table.Length;
for (int i = 0; i < this.Capacity; i++)
{
int bucket = (startPosition + i) % this.Capacity;
if (this.Table[bucket] == null || this.Table[bucket].Key.Equals(key))
{
return bucket;
}
}
throw new InvalidOperationException("“No available bucket found.");
}
public V Get(K key)
{
if (key == null)
{
throw new ArgumentNullException();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
if (this.Table[bucket] != null && this.Table[bucket].Key.Equals(key))
{
return this.Table[bucket].Value;
}
else
{
return default(V); // If no matching key is found, return the default value of the V type (usually null for reference types).
}
}
public V Put(K key, V value)
{
if (key == null)
{
throw new ArgumentNullException();
}
if (value == null)
{
throw new ArgumentNullException();
}
if ((this.size + this.Placeholders + 1) >= this.Capacity * this.LoadFactor)
{
ReHash();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
for (Entry<K, V> entry = this.Table[bucket]; entry != null; entry = entry.Next)
{
if (entry.Key.Equals(key))
{
V oldValue = entry.Value;
entry.Value = value;
return oldValue;
}
}
Entry<K, V> newEntry = new Entry<K, V>(key, value);
newEntry.Next = this.Table[bucket];
this.Table[bucket] = newEntry;
this.size++;
return default(V);
}
public V Remove(K key)
{
if (key == null)
{
throw new ArgumentNullException();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
if (this.Table[bucket] != null && this.Table[bucket].Key.Equals(key))
{
V removedValue = this.Table[bucket].Value;
this.Table[bucket].Value = default(V);
this.Placeholders++;
this.size--;
return removedValue;
}
else
{
return default(V); // If no matching key is found, return the default value of the V type (usually null for reference types).
}
}
private int ReSize()
{
int newCapacity = this.Capacity * 2;
while (!IsPrime(newCapacity))
{
newCapacity++;
}
return newCapacity;
}
public void ReHash()
{
Entry<K, V>[] oldTable = this.Table;
this.Capacity = ReSize(); // Update Capacity with the next appropriate prime number.
this.Table = new Entry<K, V>[this.Capacity]; // Create a new table with the updated Capacity.
this.size = 0; // Reset the size to 0 as we’ll be adding back all the elements.
this.Placeholders = 0;
// Rehash the entire hash map by iterating through the old table.
for (int i = 0; i < oldTable.Length; i++)
{
Entry<K, V> entry = oldTable[i];
while (entry != null)
{
Put(entry.Key, entry.Value); // Add to the new table.
entry = entry.Next;
}
}
}
public IEnumerator<V> Values()
{
List<V> valuesList = new List<V>();
for (int i = 0; i < this.Capacity; i++)
{
Entry<K, V> entry = this.Table[i];
if (entry != null && entry.Value != null)
{
valuesList.Add(entry.Value);
}
}
return valuesList.GetEnumerator();
}
public IEnumerator<K> Keys()
{
List<K> keysList = new List<K>();
for (int i = 0; i < this.Capacity; i++)
{
Entry<K, V> entry = this.Table[i];
if (entry != null && entry.Value != null)
{
keysList.Add(entry.Key);
}
}
return keysList.GetEnumerator();
}
private bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2 || number == 3) return true;
if (number % 2 == 0) return false;
for (int i = 3; i * i <= number; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
public interface IMap<K, V>
{
/* Properties */
public int Size { get; set; }
/* Methods */
public bool IsEmpty();
public void Clear();
public V Get(K key);
public V Put(K key, V value);
public IEnumerator<K> Keys();
public IEnumerator<V> Values();
}
}
|
ff442653a61e1ecfeb91f061fc25e0db
|
{
"intermediate": 0.42516884207725525,
"beginner": 0.4021981358528137,
"expert": 0.17263294756412506
}
|
1,065
|
Given a set of observations, obs, code an NR algorithm in R to find the MLEs of alpha and beta from a beta distribution.
|
cf39eabf70a7dc2da2e97bf28cdedda1
|
{
"intermediate": 0.12238378822803497,
"beginner": 0.048789385706186295,
"expert": 0.8288268446922302
}
|
1,066
|
I am using a recycleview to display data from firebase database so that i can create a history table but i am having trouble displaying it for context I will put the codes here
Result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<UserItem> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
};
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn't exist");
}
mData.clear();
// Add a condition to check if the dataSnapshot key is equal to your specific ID.
if (dataSnapshot.getKey().equals("-NT4APgDfX15GW0fi1pP")) {
UserData userData = dataSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data));
mData.add(new UserItem("GSR Data", userData.gsr_data));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data));
mData.add(new UserItem("GSR Data", userData.gsr_data));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
UserData.java
package com.example.profile;
public class UserData {
public String soreness_label;
public String emg_data;
public String gsr_data;
public String timestamp;
public UserData() {
}
}
UserItem.Java
package com.example.profile;
public class UserItem {
private String name;
private String data;
public UserItem(String name, String data) {
this.name = name;
this.data = data;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
recyclerviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UserItem> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<UserItem> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
UserItem userItem = mData.get(position);
holder.nameTextView.setText(userItem.getName());
holder.dataTextView.setText(userItem.getData());
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
build.gradle
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
namespace 'com.example.profile'
compileSdk 33
defaultConfig {
applicationId "com.example.profile"
minSdk 30
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.3.0'
implementation 'com.google.firebase:firebase-analytics:21.2.1'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
firebase structure
https://test1-5f6a3-default-rtdb.firebaseio.com/
users
09123456789
-NT4APgDfX15GW0fi1pP
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
-NT4APsSDZAVNkyvt--0
emg_data
:
Value
930
gsr_data
:
Value
393
soreness_label
:
Value
exhausted
timestamp
:
Value
2023-04-15 06:49:35
-NT4AQ3ZaaZb_LnzWmY-
emg_data
:
930
gsr_data
:
393
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:36"
-NT4AQFUNuS9PpwYkbAz
emg_data
:
929
gsr_data
:
395
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:37"
|
70e0957358d1a8593a9a88880ecf476e
|
{
"intermediate": 0.39344844222068787,
"beginner": 0.357442170381546,
"expert": 0.2491094022989273
}
|
1,067
|
I am using a recycleview to display data from firebase database so that i can create a history table but i am having trouble displaying it for context I will put the codes here
Result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<UserItem> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
// Load data based on the current EditText input
handleEditTextInput();
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
handleEditTextInput();
}
};
// Create a new method to handle EditText input
private void handleEditTextInput() {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn't exist");
}
mData.clear();
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Node Name",idSnapshot.getKey())); // Add this line
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data));
mData.add(new UserItem("GSR Data", userData.gsr_data));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
UserData.java
package com.example.profile;
public class UserData {
public String soreness_label;
public Object emg_data; // Changed to Object
public Object gsr_data; // Changed to Object
public String timestamp;
public UserData() {
}
}
UserItem.Java
package com.example.profile;
public class UserItem {
private String name;
private String data;
public UserItem(String name, Object data) {
this.name = name;
if (data instanceof String) {
this.data = (String) data;
} else if (data instanceof Integer) {
this.data = String.valueOf(data);
} else {
// Default or error behavior if invalid data type
throw new IllegalArgumentException("Invalid data type. Expected String or Integer");
}
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
recyclerviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UserItem> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<UserItem> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
UserItem userItem = mData.get(position);
holder.nameTextView.setText(userItem.getName());
holder.dataTextView.setText(userItem.getData());
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
build.gradle
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
namespace 'com.example.profile'
compileSdk 33
defaultConfig {
applicationId "com.example.profile"
minSdk 30
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.3.0'
implementation 'com.google.firebase:firebase-analytics:21.2.1'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
firebase structure
https://test1-5f6a3-default-rtdb.firebaseio.com/
users
09123456789
-NT4APgDfX15GW0fi1pP
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
-NT4APsSDZAVNkyvt--0
emg_data
:
Value
930
gsr_data
:
Value
393
soreness_label
:
Value
exhausted
timestamp
:
Value
2023-04-15 06:49:35
-NT4AQ3ZaaZb_LnzWmY-
emg_data
:
930
gsr_data
:
393
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:36"
-NT4AQFUNuS9PpwYkbAz
emg_data
:
929
gsr_data
:
395
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:37"
|
8322493d99e1d48eeaf3d00fe2f65759
|
{
"intermediate": 0.431136816740036,
"beginner": 0.3282252550125122,
"expert": 0.2406378984451294
}
|
1,068
|
import random
import math
# Beale Function
# https://www.sfu.ca/~ssurjano/beale.html
def beale(x1, x2):
term1 = math.pow(1.5 - x1 + x1*x2, 2)
term2 = math.pow(2.25 - x1 + x1*math.pow(x2, 2), 2)
term3 = math.pow(2.625 - x1 + x1*math.pow(x2, 3), 2)
return term1 + term2 + term3
# Configuration
config = {
"population_size": 10,
"x1_bounds": (-4.5, 3),
"x2_bounds": (-4.5, 0.5),
"seed": random.randint(0, 500),
}
# Representation Design Output
def init_population():
populations = []
for i in range(config["population_size"]):
x1 = random.uniform(*config["x1_bounds"])
x2 = random.uniform(*config["x2_bounds"])
chromosome = [x1, x2]
populations.append(chromosome)
print(f"Individual {i+1}: {chromosome}")
return populations
if __name__ == '__main__':
print("-----------------------------------------------------------------")
print("Assignment 1: Problem Identification & Representation Design (4%)")
print("-----------------------------------------------------------------")
print("-----------------------------------------------------------------")
# Custom seed input
user_seed = input("Enter a custom seed value (or press Enter to use the random seed): ")
if user_seed:
config["seed"] = int(user_seed)
# Seed
random.seed(config["seed"])
print(f"Current Seed: {config['seed']}")
# Initialize the population
population = init_population()
how can I make it so if the user press enter to use the random seed. It will output "Randomized Seed:" instead of "Current Seed"
|
f623b4cb491c07d741dce6b0feed4564
|
{
"intermediate": 0.3237590491771698,
"beginner": 0.4050924777984619,
"expert": 0.2711485028266907
}
|
1,069
|
angular — the templating syntax. make 50 questions about it. give me answers at the end of page
|
6d941c3f989b93f00de3dbbdc0522e4a
|
{
"intermediate": 0.3114735186100006,
"beginner": 0.5145735740661621,
"expert": 0.1739528924226761
}
|
1,070
|
Can you evaluate a class for me?
|
085223cc9b0085224180501a6272a601
|
{
"intermediate": 0.18535535037517548,
"beginner": 0.545016884803772,
"expert": 0.26962780952453613
}
|
1,071
|
test the code, check and fix until it's playable
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>
<title>Simple Platformer</title>
<style>
canvas {
display: block;
margin: 0 auto;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<canvas id=“gameCanvas” width=“800” height=“600”></canvas>
<script>
const canvas = document.getElementById(“gameCanvas”);
const ctx = canvas.getContext(“2d”);
let gameLoop;
function init() {
// Game Initialization logic here
gameLoop = setInterval(update, 1000 / 60); // 60 FPS
}
function update() {
// Game Update logic here
clearCanvas();
draw();
}
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function draw() {
// Drawing logic here
}
init();
// Game Objects
const player = {
x: 50,
y: 100,
width: 30,
height: 30,
velocityX: 0,
velocityY: 0
};
const platforms = [
{
x: 0,
y: canvas.height - 20,
width: canvas.width,
height: 20
}
];
function drawPlayer() {
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function drawPlatforms() {
platforms.forEach(platform => {
ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
});
}
function draw() {
drawPlayer();
drawPlatforms();
}
// Keyboard Input
const keys = {};
document.addEventListener(“keydown”, event => {
keys[event.code] = true;
});
document.addEventListener(“keyup”, event => {
keys[event.code] = false;
});
function updatePlayerVelocity() {
if (keys[“ArrowLeft”] || keys[“KeyA”]) {
player.velocityX = -4;
} else if (keys[“ArrowRight”] || keys[“KeyD”]) {
player.velocityX = 4;
} else {
player.velocityX = 0;
}
}
function update() {
updatePlayerVelocity();
// Update player positions
player.x += player.velocityX;
player.y += player.velocityY;
clearCanvas();
draw();
}
const gravity = 1;
const groundFriction = 0.8;
function applyGravity() {
player.velocityY += gravity;
}
function checkPlatformCollision() {
platforms.forEach(platform => {
if (
player.x < platform.x + platform.width &&
player.x + player.width > platform.x &&
player.y < platform.y + platform.height &&
player.y + player.height > platform.y
) {
// Colliding with platform
player.y = platform.y - player.height;
player.velocityY = 0;
}
});
}
function applyGroundFriction() {
if (player.velocityY === 0) {
player.velocityX *= groundFriction;
}
}
function update() {
updatePlayerVelocity();
// Apply gravity and friction
applyGravity();
applyGroundFriction();
// Update player positions
player.x += player.velocityX;
player.y += player.velocityY;
// Check for collisions
checkPlatformCollision();
clearCanvas();
draw();
}
</script>
</body>
</html>
|
59080663546eeadb428afbaf23331836
|
{
"intermediate": 0.3839346170425415,
"beginner": 0.419141560792923,
"expert": 0.19692383706569672
}
|
1,072
|
I am using a recycleview to display data from firebase database so that i can create a history table but i am having trouble displaying it for context I will put the codes here
Result.java
package com.example.profile;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.annotation.NonNull;
import android.util.Log;
import android.os.Bundle;
import android.widget.Toast;
import android.widget.EditText;
import android.text.TextWatcher;
import android.text.Editable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
DrawerLayout drawerLayout;
private static final String TAG = "Result";
private EditText mNodeNameEditText;
private DatabaseReference mDatabaseRef;
private RecyclerView mRecyclerView;
private RecyclerViewAdapter mAdapter;
private ArrayList<UserItem> mData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
drawerLayout = findViewById(R.id.drawer_activity);
mNodeNameEditText = findViewById(R.id.node_name_edit_text);
// Set up RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mData = new ArrayList<>();
mAdapter = new RecyclerViewAdapter(Result.this, mData);
mRecyclerView.setAdapter(mAdapter);
// Set default node of the database
mDatabaseRef = FirebaseDatabase.getInstance().getReference("users");
mNodeNameEditText.removeTextChangedListener(textWatcher);
mNodeNameEditText.addTextChangedListener(textWatcher);
// Load data based on the current EditText input
handleEditTextInput();
}
// TextWatcher implementation
private final TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
handleEditTextInput();
}
};
// Create a new method to handle EditText input
private void handleEditTextInput() {
String nodeName = mNodeNameEditText.getText().toString().trim();
if (!nodeName.isEmpty()) {
retrieveData(nodeName);
} else {
Toast.makeText(Result.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
}
}
private void retrieveData(String phoneNumber) {
DatabaseReference myRef = mDatabaseRef.child(phoneNumber);
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "Data snapshot exists: " + dataSnapshot.toString());
} else {
Log.d(TAG, "Data snapshot doesn't exist");
}
mData.clear();
for (DataSnapshot idSnapshot : dataSnapshot.getChildren()) {
UserData userData = idSnapshot.getValue(UserData.class);
if (userData != null) {
Log.d(TAG, "Data received: " + userData.toString());
mData.add(new UserItem("Node Name", idSnapshot.getKey())); // Add this line
mData.add(new UserItem("Soreness Label", userData.soreness_label));
mData.add(new UserItem("EMG Data", userData.emg_data));
mData.add(new UserItem("GSR Data", userData.gsr_data));
mData.add(new UserItem("Timestamp", userData.timestamp));
} else {
Log.d(TAG, "UserData object is null");
}
}
mAdapter.notifyDataSetChanged(); // Add this line
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.w(TAG, "Failed to read value.", databaseError.toException());
}
});
}
}
UserData.java
package com.example.profile;
public class UserData {
public String soreness_label;
public Object emg_data; // Changed to Object
public Object gsr_data; // Changed to Object
public String timestamp;
public UserData() {
}
}
UserItem.Java
package com.example.profile;
public class UserItem {
private String name;
private String data;
public UserItem(String name, Object data) {
this.name = name;
if (data instanceof String) {
this.data = (String) data;
} else if (data instanceof Integer) {
this.data = String.valueOf(data);
} else {
// Default or error behavior if invalid data type
throw new IllegalArgumentException("Invalid data type. Expected String or Integer");
}
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
recyclerviewadapter.java
package com.example.profile;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<UserItem> mData;
private LayoutInflater mInflater;
// data is passed into the constructor
public RecyclerViewAdapter(Context context, ArrayList<UserItem> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
// inflates the cell layout from xml when needed
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextViews in each cell
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
UserItem userItem = mData.get(position);
holder.nameTextView.setText(userItem.getName());
holder.dataTextView.setText(userItem.getData());
}
// total number of cells
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder {
TextView nameTextView;
TextView dataTextView;
ViewHolder(View itemView) {
super(itemView);
nameTextView = itemView.findViewById(R.id.textview_name);
dataTextView = itemView.findViewById(R.id.textview_data);
}
}
}
activity_result.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Result">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/node_name_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:hint="Enter node name"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="@+id/node_name_edit_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
<RelativeLayout
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="@color/white">
<include layout="@layout/main_navigation_drawer" />
</RelativeLayout>
</androidx.drawerlayout.widget.DrawerLayout>
recyclerview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/textview_data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Data"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
build.gradle
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
namespace 'com.example.profile'
compileSdk 33
defaultConfig {
applicationId "com.example.profile"
minSdk 30
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.3.0'
implementation 'com.google.firebase:firebase-analytics:21.2.1'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'com.google.firebase:firebase-database:20.1.0'
implementation 'com.google.firebase:firebase-database-ktx:20.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
firebase structure
https://test1-5f6a3-default-rtdb.firebaseio.com/
users
09123456789
-NT4APgDfX15GW0fi1pP
emg_data
:
930
gsr_data
:
394
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:33"
-NT4APsSDZAVNkyvt--0
emg_data
:
Value
930
gsr_data
:
Value
393
soreness_label
:
Value
exhausted
timestamp
:
Value
2023-04-15 06:49:35
-NT4AQ3ZaaZb_LnzWmY-
emg_data
:
930
gsr_data
:
393
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:36"
-NT4AQFUNuS9PpwYkbAz
emg_data
:
929
gsr_data
:
395
soreness_label
:
"exhausted"
timestamp
:
"2023-04-15 06:49:37"
|
f61c66542164195490eb4381f3a181b5
|
{
"intermediate": 0.431136816740036,
"beginner": 0.3282252550125122,
"expert": 0.2406378984451294
}
|
1,073
|
make a javascript window for a simple and light platformer game
|
7e04d513ba3b52d0069540d2094aec5f
|
{
"intermediate": 0.3705123960971832,
"beginner": 0.36148691177368164,
"expert": 0.26800063252449036
}
|
1,074
|
can you speak Chinese
|
f3242e55965ea3676cb451dca24fc4d1
|
{
"intermediate": 0.39879459142684937,
"beginner": 0.3530343770980835,
"expert": 0.24817103147506714
}
|
1,075
|
its showimg grey screen when i open app after flutter build apk but when i run it on emulator it doesnt show the grey screen. it only shows when i build apk and after login when im supposed to enter home page it shows grey screen // ignore_for_file: override_on_non_overriding_member, annotate_overrides, prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:healthchats/body.dart';
import 'package:healthchats/constants.dart';
import 'package:healthchats/navigationbar.dart';
import 'package:healthchats/service/auth-service.dart';
import 'helper/helperFunction.dart';
import 'backgroundgradient.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
String userName = "";
String email = "";
AuthService authService = AuthService();
@override
void initState() {
super.initState();
gettingUserData();
}
gettingUserData() async {
await helperFunctions.getUserEmailFromSF().then((value) {
setState(() {
email = value!;
});
});
await helperFunctions.getUserNameFromSF().then((val) {
setState(() {
userName = val!;
});
});
}
@override
static final scaffoldKey = GlobalKey<ScaffoldState>();
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
drawer: navbar(context, userName, email),
// bottomNavigationBar: bottomnav(),
// appBar: BuildAppBar(),
body: Container(
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: const [
kbackgroundColor2,
Color.fromARGB(255, 238, 236, 232)
],
)),
child: Body(
scaffoldKey: scaffoldKey,
),
),
backgroundColor:
Colors.transparent, // set background color to transparent
resizeToAvoidBottomInset: false);
}
}
|
0d5e9b8a7ad4ee0300d42fcd5cfd7cf2
|
{
"intermediate": 0.3976201117038727,
"beginner": 0.4208471477031708,
"expert": 0.18153266608715057
}
|
1,076
|
Create a public int GetMatchingOrNextAvailableBucket(K key) method for below class with the following requirements:
Looks for the next available bucket based on the key passed, (Uses linear probing for collision handling, will return to the 0 index and continue searching if array length is reached). Note, if the key exists, it returns the bucket of the matching key.
DO NOT LOOP THROUGH EVERY ENTRY FROM 0 TO ARRAY LENGTH IN THIS METHOD. Start from the starting bucket and use linear probing. It may end up going through many indexes, but in practice it will never do that because you have a threshold and there are many empty array spots.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Assignment_4
{
public class HashMap<K, V> : IMap<K, V>
{
/* Properties */
public Entry<K, V>[] Table { get; set; }
public int Capacity { get; set; }
public double LoadFactor { get; set; }
public int size; // Had to use a field to satisfy the IMap requirements of using the Size() method.
public int Placeholders { get; set; } // Keeps track of the number of placeholders in the HashMap.
/* Constructors */
public HashMap()
{
this.Capacity = 11;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = 0.75;
this.size = 0;
}
public HashMap(int initialCapacity)
{
if (initialCapacity <= 0)
{
throw new ArgumentException();
}
this.Capacity = initialCapacity;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = 0.75;
this.size = 0;
}
public HashMap(int initialCapacity, double loadFactor)
{
if (initialCapacity <= 0 || loadFactor <= 0)
{
throw new ArgumentException();
}
this.Capacity = initialCapacity;
this.Table = new Entry<K, V>[this.Capacity];
this.LoadFactor = loadFactor;
this.size = 0;
}
/* Methods */
public int Size()
{
return this.size;
}
public bool IsEmpty()
{
return this.size == 0;
}
public void Clear()
{
Array.Clear(this.Table, 0, this.Table.Length);
this.size = 0;
this.Placeholders = 0;
}
throw new InvalidOperationException("“No available bucket found.");
}
public V Get(K key)
{
if (key == null)
{
throw new ArgumentNullException();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
if (this.Table[bucket] != null && this.Table[bucket].Key.Equals(key))
{
return this.Table[bucket].Value;
}
else
{
return default(V); // If no matching key is found, return the default value of the V type (usually null for reference types).
}
}
public V Put(K key, V value)
{
if (key == null)
{
throw new ArgumentNullException();
}
if (value == null)
{
throw new ArgumentNullException();
}
if ((this.size + this.Placeholders + 1) >= this.Capacity * this.LoadFactor)
{
ReHash();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
for (Entry<K, V> entry = this.Table[bucket]; entry != null; entry = entry.Next)
{
if (entry.Key.Equals(key))
{
V oldValue = entry.Value;
entry.Value = value;
return oldValue;
}
}
Entry<K, V> newEntry = new Entry<K, V>(key, value);
newEntry.Next = this.Table[bucket];
this.Table[bucket] = newEntry;
this.size++;
return default(V);
}
public V Remove(K key)
{
if (key == null)
{
throw new ArgumentNullException();
}
int bucket = GetMatchingOrNextAvailableBucket(key);
if (this.Table[bucket] != null && this.Table[bucket].Key.Equals(key))
{
V removedValue = this.Table[bucket].Value;
this.Table[bucket].Value = default(V);
this.Placeholders++;
this.size--;
return removedValue;
}
else
{
return default(V); // If no matching key is found, return the default value of the V type (usually null for reference types).
}
}
private int ReSize()
{
int newCapacity = this.Capacity;
// Find the nearest prime number greater than or equal to double the current capacity.
if (newCapacity == 1)
{
newCapacity = 2;
}
else
{
newCapacity = this.Capacity * 2;
while (!IsPrime(newCapacity))
{
newCapacity++;
}
}
return newCapacity;
}
public void ReHash()
{
Entry<K, V>[] oldTable = this.Table;
int newCapacity = ReSize(); // Store the result of ReSize() in a local variable
Entry<K, V>[] newTable = new Entry<K, V>[newCapacity]; // Create a new table with the updated Capacity
this.size = 0; // Reset the size to 0 as we’ll be adding back all the elements.
this.Placeholders = 0;
// Rehash the entire hash map by iterating through the old table.
for (int i = 0; i < oldTable.Length; i++)
{
Entry<K, V> entry = oldTable[i];
while (entry != null)
{
Entry<K, V> nextEntry = entry.Next;
int startPosition = Math.Abs(entry.Key.GetHashCode()) % newTable.Length;
for (int j = 0; j < newCapacity; j++)
{
int bucket = (startPosition + j) % newCapacity;
if (newTable[bucket] == null)
{
newTable[bucket] = entry;
entry.Next = null;
this.size++;
break;
}
}
entry = nextEntry;
}
}
this.Table = newTable;
this.Capacity = newCapacity;
}
public IEnumerator<V> Values()
{
List<V> valuesList = new List<V>();
for (int i = 0; i < this.Capacity; i++)
{
Entry<K, V> entry = this.Table[i];
if (entry != null && entry.Value != null)
{
valuesList.Add(entry.Value);
}
}
return valuesList.GetEnumerator();
}
public IEnumerator<K> Keys()
{
List<K> keysList = new List<K>();
for (int i = 0; i < this.Capacity; i++)
{
Entry<K, V> entry = this.Table[i];
if (entry != null && entry.Value != null)
{
keysList.Add(entry.Key);
}
}
return keysList.GetEnumerator();
}
private bool IsPrime(int number)
{
if (number <= 1) return false;
if (number == 2 || number == 3) return true;
if (number % 2 == 0) return false;
for (int i = 3; i * i <= number; i += 2)
{
if (number % i == 0) return false;
}
return true;
}
}
}
|
a6436e4e61afbe6e06f97485f1183309
|
{
"intermediate": 0.4722936451435089,
"beginner": 0.2380642294883728,
"expert": 0.2896421551704407
}
|
1,077
|
hii
|
d6848eacf7e8ee8dae22f3d9cff08123
|
{
"intermediate": 0.3416314125061035,
"beginner": 0.27302300930023193,
"expert": 0.38534557819366455
}
|
1,078
|
im gettingg a grey screen error when i build apk and run the app it is running good until the login screen and after that its showing grey screen when im supposed to be on home screen, here is my shared presference code, update it to fix that so it wont throw me any error // ignore_for_file: file_names, camel_case_types
import 'package:shared_preferences/shared_preferences.dart';
class helperFunctions {
//keys
static String userLoggedInkey = "LOGGEDINKEY";
static String userNameKey = "USERNAMEKEY";
static String userEmailKey = "USEREMAILKEY";
// saving the data with the shared preferences
static Future<bool> saveUserLoggedInStatus(bool isUserLoggedIn) async {
SharedPreferences sf = await SharedPreferences.getInstance();
return await sf.setBool(userLoggedInkey, isUserLoggedIn);
}
static Future<bool> saveUsernameSF(String userName) async {
SharedPreferences sf = await SharedPreferences.getInstance();
return await sf.setString(userNameKey, userName);
}
static Future<bool> saveUserEmailSF(String userEmail) async {
SharedPreferences sf = await SharedPreferences.getInstance();
return await sf.setString(userEmailKey, userEmail);
}
//getting the data from the shared preferences
static Future<bool?> getUserLoggedInStatus() async {
SharedPreferences sf = await SharedPreferences.getInstance();
return sf.getBool(userLoggedInkey);
}
static Future<String?> getUserEmailFromSF() async {
SharedPreferences sf = await SharedPreferences.getInstance();
return sf.getString(userEmailKey);
}
static Future<String?> getUserNameFromSF() async {
SharedPreferences sf = await SharedPreferences.getInstance();
return sf.getString(userNameKey);
}
}
|
f0d200734dffd900e47bb87ed2f2b42b
|
{
"intermediate": 0.5331940054893494,
"beginner": 0.32367533445358276,
"expert": 0.1431305855512619
}
|
1,079
|
template: '<li class="red" (click)="selectPony()" >{{ pony.name }}</li>',
selector: 'ns-pony',
styles: [`li: {
color: red;
font-weight: bold;
}`],
encapsulation: ViewEncapsulation.ShadowDom
why doesnt color
|
c54911535e0471ec9c32e655c66676e6
|
{
"intermediate": 0.3884739279747009,
"beginner": 0.26855289936065674,
"expert": 0.34297311305999756
}
|
1,080
|
@Composable
fun ExpensesGraph(paddingValues: PaddingValues) {
val db = FirebaseFirestore.getInstance()
// Define your timeframes
val timeFrames = listOf("Daily", "Weekly", "Monthly", "Yearly")
val selectedIndex = remember { mutableStateOf(0) }
// Fetch and process the expenses data
val chartEntries = remember { mutableStateOf(entriesOf(*arrayOf<Float>())) }
val chartModelProducer = ChartEntryModelProducer(chartEntries.value)
val markers = remember { mutableStateOf<Map<Float, Marker>>(emptyMap()) }
fun fetchExpensesData(timeFrame: String) {
val startCalendar = Calendar.getInstance()
val endCalendar = Calendar.getInstance()
var dateFormat: SimpleDateFormat
when (timeFrame) {
"Daily" -> {
// Daily: Showing 7 days in a week
startCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1)
endCalendar.add(Calendar.DATE, 6)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault())
}
"Weekly" -> {
// Weekly: Showing 4 weeks in a month
startCalendar.set(Calendar.DAY_OF_MONTH, 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(
Calendar.DAY_OF_MONTH,
startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH),
)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("W_MMM_yyyy", Locale.getDefault())
}
"Monthly" -> {
// Monthly: Showing 12 months in a year
startCalendar.set(Calendar.MONTH, 0)
startCalendar.set(Calendar.DAY_OF_MONTH, 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.MONTH, 11)
endCalendar.set(
Calendar.DAY_OF_MONTH,
endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)
)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("MMM_yyyy", Locale.getDefault())
}
"Yearly" -> {
startCalendar.set(Calendar.MONTH, 0)
startCalendar.set(Calendar.DAY_OF_MONTH, -1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.MONTH, 11)
endCalendar.set(Calendar.DAY_OF_MONTH, 31)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("yyyy", Locale.getDefault())
}
else -> {
throw IllegalArgumentException("Unsupported time frame: $timeFrame")
}
}
val query = db.collection("expenses")
.document("Kantin")
.collection(timeFrame.lowercase())
query.get().addOnSuccessListener { result ->
val expenses = mutableListOf<Pair<Float, Date>>()
for (document in result) {
val total = document.getDouble("total")?.toFloat() ?: 0f
val date = dateFormat.parse(document.id) ?: Date()
expenses.add(total to date)
println("Document: ${document.id}, Total: $total, Date: $date")
}
println(startCalendar.time)
println(endCalendar.time)
expenses.retainAll { it.second >= startCalendar.time && it.second <= endCalendar.time }
// Sort the expenses by date
expenses.sortBy { it.second }
chartEntries.value =
entriesOf(*expenses.mapIndexed { index, expense -> index.toFloat() to expense.first }
.toTypedArray())
}
}
LaunchedEffect(Unit) { fetchExpensesData(timeFrames[selectedIndex.value]) }
Column(modifier = Modifier.padding(paddingValues)) {
timeFrames.forEachIndexed { index, timeFrame ->
Button(
onClick = {
selectedIndex.value = index
fetchExpensesData(timeFrame)
},
colors = ButtonDefaults.buttonColors(
containerColor = if (selectedIndex.value == index) DarkGray else LightGray
)
) {
Text(timeFrame)
}
}
ProvideChartStyle(chartStyle = m3ChartStyle()) {
Chart(
chart = columnChart(),
chartModelProducer = chartModelProducer,
startAxis = startAxis(),
bottomAxis = bottomAxis(),
)
}
}
}
this is my expenses graph screen, right now the amount of x axis will be dependent to the amount of document in the firestore, I want it to be persistent so for example in my daily timeframe it will always show Monday to Sunday in the x axis even though there is still no data for Wednesday to Sunday
|
d04a147b90969a851ac5303e79deae53
|
{
"intermediate": 0.34523671865463257,
"beginner": 0.4995669722557068,
"expert": 0.15519633889198303
}
|
1,081
|
ciao. Saresti in grado di scrivere un codice in c# da usare su Unity? Ho 2 script, uno è una mia classe, l'altro è una finestra editorwindow di unity. Vorrei che mi scrivessi un codice GUI da inserire nello script editorwindow. Il codice GUI deve mostrare nella finestra le proprietà della mia classe e deve permettere la loro modifica. Ti passo il codice della mia classe e della finestra:
public class _Map_IO_opt
{
public enum _Map_IO_typeofMap { Heightmap, Holemap, Alphamap, Detailmap };
public enum _Map_IO_typeofExport { Full, Area, Tiles};
public enum _Map_IO_typeofOutput { Png, Jpg, Tga, Txt, GameObject};
public Vector2Int startArea;
public Vector2Int endArea;
public Vector2Int tiles;
public bool withHole;
public bool invert;
public int index;
}
public class _Map_IO : EditorWindow
{
_Map_IO_opt opt;
Terrain terrain;
public void _show(Terrain t)
{
terrain = t;
this.Show();
}
private void OnGUI()
{
}
}
|
7b66df2df102f50d6f379d683c1ff1fa
|
{
"intermediate": 0.4599904417991638,
"beginner": 0.38693302869796753,
"expert": 0.15307654440402985
}
|
1,082
|
@Composable
fun ExpensesGraph(paddingValues: PaddingValues) {
val db = FirebaseFirestore.getInstance()
// Define your timeframes
val timeFrames = listOf("Daily", "Weekly", "Monthly", "Yearly")
val selectedIndex = remember { mutableStateOf(0) }
// Fetch and process the expenses data
val chartEntries = remember { mutableStateOf(entriesOf(*arrayOf<Float>())) }
val chartModelProducer = ChartEntryModelProducer(chartEntries.value)
val markers = remember { mutableStateOf<Map<Float, Marker>>(emptyMap()) }
fun fetchExpensesData(timeFrame: String) {
val startCalendar = Calendar.getInstance()
val endCalendar = Calendar.getInstance()
var dateFormat: SimpleDateFormat
when (timeFrame) {
"Daily" -> {
// Daily: Showing 7 days in a week
startCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1)
endCalendar.add(Calendar.DATE, 6)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault())
}
"Weekly" -> {
// Weekly: Showing 4 weeks in a month
startCalendar.set(Calendar.DAY_OF_MONTH, 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(
Calendar.DAY_OF_MONTH,
startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH),
)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("W_MMM_yyyy", Locale.getDefault())
}
"Monthly" -> {
// Monthly: Showing 12 months in a year
startCalendar.set(Calendar.MONTH, 0)
startCalendar.set(Calendar.DAY_OF_MONTH, 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.MONTH, 11)
endCalendar.set(
Calendar.DAY_OF_MONTH,
endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)
)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("MMM_yyyy", Locale.getDefault())
}
"Yearly" -> {
startCalendar.set(Calendar.MONTH, 0)
startCalendar.set(Calendar.DAY_OF_MONTH, -1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.MONTH, 11)
endCalendar.set(Calendar.DAY_OF_MONTH, 31)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("yyyy", Locale.getDefault())
}
else -> {
throw IllegalArgumentException("Unsupported time frame: $timeFrame")
}
}
val query = db.collection("expenses")
.document("Kantin")
.collection(timeFrame.lowercase())
query.get().addOnSuccessListener { result ->
val expenses = mutableListOf<Pair<Float, Date>>()
for (document in result) {
val total = document.getDouble("total")?.toFloat() ?: 0f
val date = dateFormat.parse(document.id) ?: Date()
expenses.add(total to date)
println("Document: ${document.id}, Total: $total, Date: $date")
}
println(startCalendar.time)
println(endCalendar.time)
expenses.retainAll { it.second >= startCalendar.time && it.second <= endCalendar.time }
// Sort the expenses by date
expenses.sortBy { it.second }
chartEntries.value =
entriesOf(*expenses.mapIndexed { index, expense -> index.toFloat() to expense.first }
.toTypedArray())
}
}
LaunchedEffect(Unit) { fetchExpensesData(timeFrames[selectedIndex.value]) }
Column(modifier = Modifier.padding(paddingValues)) {
timeFrames.forEachIndexed { index, timeFrame ->
Button(
onClick = {
selectedIndex.value = index
fetchExpensesData(timeFrame)
},
colors = ButtonDefaults.buttonColors(
containerColor = if (selectedIndex.value == index) DarkGray else LightGray
)
) {
Text(timeFrame)
}
}
ProvideChartStyle(chartStyle = m3ChartStyle()) {
Chart(
chart = columnChart(),
chartModelProducer = chartModelProducer,
startAxis = startAxis(),
bottomAxis = bottomAxis(),
)
}
}
}
this is my expenses graph screen, right now the amount of x axis will be dependent to the amount of document in the firestore, I want it to be persistent so for example in my daily timeframe it will always show Monday to Sunday in the x axis even though there is still no data for Wednesday to Sunday
this is the bottomAxis composable from the library
@Composable
public fun bottomAxis(
label: TextComponent? = axisLabelComponent(),
axis: LineComponent? = axisLineComponent(),
tick: LineComponent? = axisTickComponent(),
tickLength: Dp = currentChartStyle.axis.axisTickLength,
tickPosition: HorizontalAxis.TickPosition = HorizontalAxis.TickPosition.Edge,
guideline: LineComponent? = axisGuidelineComponent(),
valueFormatter: AxisValueFormatter<AxisPosition.Horizontal.Bottom> = DecimalFormatAxisValueFormatter(),
sizeConstraint: Axis.SizeConstraint = Axis.SizeConstraint.Auto(),
titleComponent: TextComponent? = null,
title: CharSequence? = null,
labelRotationDegrees: Float = currentChartStyle.axis.axisLabelRotationDegrees,
): HorizontalAxis<AxisPosition.Horizontal.Bottom> = createHorizontalAxis {
this.label = label
this.axis = axis
this.tick = tick
this.guideline = guideline
this.valueFormatter = valueFormatter
this.tickLengthDp = tickLength.value
this.tickPosition = tickPosition
this.sizeConstraint = sizeConstraint
this.labelRotationDegrees = labelRotationDegrees
this.titleComponent = titleComponent
this.title = title
}
|
e6cdfa2d38fe66ef7e66459374149156
|
{
"intermediate": 0.34523671865463257,
"beginner": 0.4995669722557068,
"expert": 0.15519633889198303
}
|
1,083
|
@Composable
fun ExpensesGraph(paddingValues: PaddingValues) {
val db = FirebaseFirestore.getInstance()
// Define your timeframes
val timeFrames = listOf("Daily", "Weekly", "Monthly", "Yearly")
val selectedIndex = remember { mutableStateOf(0) }
// Fetch and process the expenses data
val chartEntries = remember { mutableStateOf(entriesOf(*arrayOf<Float>())) }
val chartModelProducer = ChartEntryModelProducer(chartEntries.value)
val markers = remember { mutableStateOf<Map<Float, Marker>>(emptyMap()) }
fun fetchExpensesData(timeFrame: String) {
val startCalendar = Calendar.getInstance()
val endCalendar = Calendar.getInstance()
var dateFormat: SimpleDateFormat
when (timeFrame) {
"Daily" -> {
// Daily: Showing 7 days in a week
startCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1)
endCalendar.add(Calendar.DATE, 6)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault())
}
"Weekly" -> {
// Weekly: Showing 4 weeks in a month
startCalendar.set(Calendar.DAY_OF_MONTH, 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(
Calendar.DAY_OF_MONTH,
startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH),
)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("W_MMM_yyyy", Locale.getDefault())
}
"Monthly" -> {
// Monthly: Showing 12 months in a year
startCalendar.set(Calendar.MONTH, 0)
startCalendar.set(Calendar.DAY_OF_MONTH, 1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.MONTH, 11)
endCalendar.set(
Calendar.DAY_OF_MONTH,
endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH)
)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("MMM_yyyy", Locale.getDefault())
}
"Yearly" -> {
startCalendar.set(Calendar.MONTH, 0)
startCalendar.set(Calendar.DAY_OF_MONTH, -1)
startCalendar.set(Calendar.HOUR_OF_DAY, 0)
startCalendar.set(Calendar.MINUTE, 0)
startCalendar.set(Calendar.SECOND, 0)
startCalendar.set(Calendar.MILLISECOND, 0)
endCalendar.set(Calendar.MONTH, 11)
endCalendar.set(Calendar.DAY_OF_MONTH, 31)
endCalendar.set(Calendar.HOUR_OF_DAY, 0)
endCalendar.set(Calendar.MINUTE, 0)
endCalendar.set(Calendar.SECOND, 0)
endCalendar.set(Calendar.MILLISECOND, 0)
dateFormat = SimpleDateFormat("yyyy", Locale.getDefault())
}
else -> {
throw IllegalArgumentException("Unsupported time frame: $timeFrame")
}
}
val query = db.collection("expenses")
.document("Kantin")
.collection(timeFrame.lowercase())
query.get().addOnSuccessListener { result ->
val expenses = mutableListOf<Pair<Float, Date>>()
for (document in result) {
val total = document.getDouble("total")?.toFloat() ?: 0f
val date = dateFormat.parse(document.id) ?: Date()
expenses.add(total to date)
println("Document: ${document.id}, Total: $total, Date: $date")
}
println(startCalendar.time)
println(endCalendar.time)
expenses.retainAll { it.second >= startCalendar.time && it.second <= endCalendar.time }
// Sort the expenses by date
expenses.sortBy { it.second }
chartEntries.value =
entriesOf(*expenses.mapIndexed { index, expense -> index.toFloat() to expense.first }
.toTypedArray())
}
}
LaunchedEffect(Unit) { fetchExpensesData(timeFrames[selectedIndex.value]) }
Column(modifier = Modifier.padding(paddingValues)) {
timeFrames.forEachIndexed { index, timeFrame ->
Button(
onClick = {
selectedIndex.value = index
fetchExpensesData(timeFrame)
},
colors = ButtonDefaults.buttonColors(
containerColor = if (selectedIndex.value == index) DarkGray else LightGray
)
) {
Text(timeFrame)
}
}
ProvideChartStyle(chartStyle = m3ChartStyle()) {
Chart(
chart = columnChart(),
chartModelProducer = chartModelProducer,
startAxis = startAxis(),
bottomAxis = bottomAxis(),
)
}
}
}
this is my expenses graph screen, right now the amount of x axis will be dependent to the amount of document in the firestore, I want it to be persistent so for example in my daily timeframe it will always show Monday to Sunday in the x axis even though there is still no data for Wednesday to Sunday
this is the bottomAxis composable
@Composable
public fun bottomAxis(
label: TextComponent? = axisLabelComponent(),
axis: LineComponent? = axisLineComponent(),
tick: LineComponent? = axisTickComponent(),
tickLength: Dp = currentChartStyle.axis.axisTickLength,
tickPosition: HorizontalAxis.TickPosition = HorizontalAxis.TickPosition.Edge,
guideline: LineComponent? = axisGuidelineComponent(),
valueFormatter: AxisValueFormatter<AxisPosition.Horizontal.Bottom> = DecimalFormatAxisValueFormatter(),
sizeConstraint: Axis.SizeConstraint = Axis.SizeConstraint.Auto(),
titleComponent: TextComponent? = null,
title: CharSequence? = null,
labelRotationDegrees: Float = currentChartStyle.axis.axisLabelRotationDegrees,
): HorizontalAxis<AxisPosition.Horizontal.Bottom> = createHorizontalAxis {
this.label = label
this.axis = axis
this.tick = tick
this.guideline = guideline
this.valueFormatter = valueFormatter
this.tickLengthDp = tickLength.value
this.tickPosition = tickPosition
this.sizeConstraint = sizeConstraint
this.labelRotationDegrees = labelRotationDegrees
this.titleComponent = titleComponent
this.title = title
}
please provide the answers in full code
|
387b8dc03b7a0b372f73698c13ac32c2
|
{
"intermediate": 0.34523671865463257,
"beginner": 0.4995669722557068,
"expert": 0.15519633889198303
}
|
1,084
|
Write a python program which generate text documents using a doc file template from a data taken from xls file
|
fddf4a66aeae4abb167d51e864ef78b2
|
{
"intermediate": 0.4449298679828644,
"beginner": 0.14679494500160217,
"expert": 0.40827521681785583
}
|
1,085
|
Как изменить шаг, чтобы я мог менять вермя, но дата оставалась та, которая на устройстве
@When("Изменили время на устройстве на |any|")
def step(context, timeType):
time = '`date +%m%d%H%M%Y.%S`' if timeType == 'верное' else '`date -u +%m%d%H%M%Y.%S`'
osOperarion.setDateTime(time)
Код для изменения времени вышлядит следующим образом
def setDateTime(dateTime):
result = str(subprocess.run(f'adb shell date {dateTime}', capture_output=True, shell=True))
test.log(result)
|
9cdaa3fc451662485d2a26ad61409502
|
{
"intermediate": 0.33804258704185486,
"beginner": 0.4654853940010071,
"expert": 0.19647209346294403
}
|
1,086
|
Hello, I'd like to ask you something.
Do you have advice on how to make a boxing routine without a partner to train with ?
|
aca811052ad7622c0a6f7a13e830e365
|
{
"intermediate": 0.331053227186203,
"beginner": 0.37314167618751526,
"expert": 0.29580503702163696
}
|
1,087
|
I am going to provide you with a coding request. Make sure to follow these instructions when responding:
Be concise
Just show the code
Only show a single answer, but you can always chain code together
Think step by step
Do not return multiple solutions
Do not show html, styled, colored formatting
Do not create invalid syntax
Do not add unnecessary text in the response
Do not add notes or intro sentences
Do not explain the code
Do not show multiple distinct solutions to the question
Do not add explanations on what the code does
Do not return what the question was
Do not reconfirm the question
Do not repeat or paraphrase the question in your response
Do not cause syntax errors
Do not rush to a conclusion
|
6c3626a9dec1a9ec3523eaac8f1b1a41
|
{
"intermediate": 0.2393035590648651,
"beginner": 0.40456196665763855,
"expert": 0.35613441467285156
}
|
1,088
|
python selenium firefox use proxy
|
ff43b2d9e2512e3f80debb0f08b2bff2
|
{
"intermediate": 0.3626652657985687,
"beginner": 0.39067965745925903,
"expert": 0.24665506184101105
}
|
1,089
|
Here's the code (R) I have so far:
__________
library(rvest)
# specify the base URL of the protocol page
url <- "https://www.clinicaltrialsregister.eu/ctr-search/trial/2015-003589-10/GR"
# read in the HTML content of the page
page <- read_html(url)
________________
I want to extract all the class="tricell" values in the HTML.
Make it in a dataframe with one line per "tricell" with 3 columns.
|
fe4810044e78996bec4c4bc281333305
|
{
"intermediate": 0.5356751084327698,
"beginner": 0.24655404686927795,
"expert": 0.21777084469795227
}
|
1,090
|
I am going to provide you with a coding request. Make sure to follow these instructions when responding:
Be concise
Just show the code
Only show a single answer, but you can always chain code together
Think step by step
Do not return multiple solutions
Do not show html, styled, colored formatting
Do not create invalid syntax
Do not add unnecessary text in the response
Do not add notes or intro sentences
Do not explain the code
Do not show multiple distinct solutions to the question
Do not add explanations on what the code does
Do not return what the question was
Do not reconfirm the question
Do not repeat or paraphrase the question in your response
Do not cause syntax errors
Do not rush to a conclusion
|
8d10ef51e0d3f079f0280d9a7bf9abe9
|
{
"intermediate": 0.2393035590648651,
"beginner": 0.40456196665763855,
"expert": 0.35613441467285156
}
|
1,091
|
I am in a docker container with ubuntu and i am logged in as root user and i have installed ufw (sudo apt install ufw)
And i am trying to run: sudo ufw status
But getting error: ERROR: problem running iptables: iptables v1.8.7 (nf_tables): Could not fetch rule set generation id: Permission denied (you must be root)
I have tried:
1. sudo service ufw start
2. sudo ufw enable
So, can you please tell help me figure out the issue here and resolve it
|
32d1bf04e2f85a801712d53ff2141728
|
{
"intermediate": 0.4677991569042206,
"beginner": 0.3034568428993225,
"expert": 0.2287440001964569
}
|
1,092
|
None of the following functions can be called with the arguments supplied:
public fun entriesOf(vararg yValues: Number): List<FloatEntry> defined in com.patrykandpatrick.vico.core.entry
public fun entriesOf(vararg pairs: Pair<Number, Number>): List<FloatEntry> defined in com.patrykandpatrick.vico.core.entry
Variable 'xAxisLabels' must be initialized
Type mismatch: inferred type is SimpleDateFormat but DateTimeFormatter! was expected
Type mismatch: inferred type is Serializable but Float was expected
4 errors in this block of code
chartEntries.value = entriesOf(
*xAxisLabels.mapIndexed { index, label ->
Entry(
LocalDate.parse(label, dateFormat),
index.toFloat(),
expenses[label] ?: 0f
)
}.toTypedArray()
)
|
76acb02798bb652d5929d43fb8391227
|
{
"intermediate": 0.3540395200252533,
"beginner": 0.44643673300743103,
"expert": 0.19952374696731567
}
|
1,093
|
hi
|
a938c19ed038a9d103e6ae1fb1b6301b
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
1,094
|
Hi! I want to create a website for learning the language in reading. A duolingo clone, for example. HTML+JS. Let's get started.
|
18344bf44592261fadbed47d56eb718f
|
{
"intermediate": 0.4353158175945282,
"beginner": 0.2986394166946411,
"expert": 0.2660447955131531
}
|
1,095
|
用glsl编写早上描述一块大陆的海拔值,要求大陆上有山脊有平原 还有3个小湖泊
|
843084d43e7100a852b851e6efc4ff8c
|
{
"intermediate": 0.2805815637111664,
"beginner": 0.29538214206695557,
"expert": 0.42403629422187805
}
|
1,096
|
You are a Python programmer. Your main goal is to write optimal, reliable code
|
a295bada611f1f2415df80b415275f00
|
{
"intermediate": 0.1916275918483734,
"beginner": 0.4287510812282562,
"expert": 0.37962135672569275
}
|
1,097
|
Fix the code.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
openImage();
} else if (e.getSource() == processButton) {
processImage();
} else if (e.getSource() == brightnessButton) {
brightnessImage();
}
else if (e.getSource() == contrastButton) {
contrastImage();
}
else if (e.getSource() == sawtoothButton) {
sawtoottImage();
}
else if (e.getSource() == gaussButton) {
gaussImage();
}
else if (e.getSource() == cannyButton) {
cannyImage();
}
}
private void processImage() {
if (image != null) {
BufferedImage binarizedImage = binarizeImage(image);
setImageIcon(binarizedImage);
}
}
private void brightnessImage() {
if (image != null) {
BufferedImage brightnessSliceImage = brightnessSlice(image, 100, 200); // яркость в диапазоне [100, 200]
setImageIcon(brightnessSliceImage);
}
}
private void contrastImage() {
if (image != null) {
BufferedImage contrastStretchedImage = linearContrastStretch(image);
setImageIcon(contrastStretchedImage);
}
}
private void sawtoottImage() {
if (image != null) {
BufferedImage[] sawtoothContrastImages = new BufferedImage[4];
sawtoothContrastImages[0] = sawtoothContrast(image, 0.2f, 0.8f, 1f);
// Пилообразное контрастирование с различными значениями коэффициента наклона
sawtoothContrastImages[1] = sawtoothContrast(image, 0.5f, 0.5f, 1f);
sawtoothContrastImages[2] = sawtoothContrast(image, 0.75f, 0.25f, 1f);
sawtoothContrastImages[3] = sawtoothContrast(image, 0.9f, 0.1f, 1f);
// Выводим четыре пилообразных контраста
for(int i=0;i<4;i++) {
ImageIcon icon = new ImageIcon(sawtoothContrastImages[i]);
JOptionPane.showMessageDialog(this, icon, "Sawtooth Contrast "+(i+1), JOptionPane.INFORMATION_MESSAGE);
}
setImageIcon(sawtoothContrastImages[0]);
}
}
private void gaussImage() {
if (image != null) {
String inputMask = JOptionPane.showInputDialog(this, "Enter a mask size (odd number):");
int maskSize = Integer.parseInt(inputMask);
float[][] mask = gaussianMask(maskSize, maskSize/2);
BufferedImage gaussImage = applyMask(image, mask);
setImageIcon(gaussImage);
}
}
private void cannyImage() {
if (image != null) {
String inputMask = JOptionPane.showInputDialog(this, "Enter a mask size (odd number):");
int maskSize = Integer.parseInt(inputMask);
float[][] mask = Mask(maskSize, maskSize/2);
BufferedImage cannyImage = applyCannyEdgeDetector(image, mask);
setImageIcon(cannyImage);
}
}
private BufferedImage applyCannyEdgeDetector(BufferedImage image) {
int lowThreshold = 20;
int highThreshold = 60;
int kernelSize = 3;
boolean applyMask = false;
int width = image.getWidth();
int height = image.getHeight();
BufferedImage resultImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
int[] pixels = new int[width * height];
int[] edges = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
if (applyMask) {
for (int i = 0; i < pixels.length; i++) {
int x = i % width;
int y = i / width;
if (mask[x][y] == 0) {
pixels[i] = 0xFFFFFF;
}
}
}
int[][] sobelX = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
int[][] sobelY = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
int[] grayPixels = convertToGrayscale(pixels);
int[] gradientX = getConvolution(grayPixels, sobelX, width, height, kernelSize);
int[] gradientY = getConvolution(grayPixels, sobelY, width, height, kernelSize);
for (int i = 0; i < pixels.length; i++) {
int gx = gradientX[i];
int gy = gradientY[i];
edges[i] = (int) Math.sqrt(gx * gx + gy * gy);
}
int[] thresholdEdges = applyHysteresis(edges, lowThreshold, highThreshold, width, height);
for (int i = 0; i < pixels.length; i++) {
if (thresholdEdges[i] != 0) {
resultImage.setRGB(i % width, i / width, 0);
} else {
resultImage.setRGB(i % width, i / width, 0xFFFFFF);
}
}
return resultImage;
}
private int[] applyHysteresis(int[] edges, int low, int high, int width, int height) {
int[] result = new int[edges.length];
Arrays.fill(result, 0);
for (int i = 0; i < edges.length; i++) {
if (edges[i] >= high && result[i] == 0) {
trace(result, edges, low, high, i, width, height);
}
}
return result;
}
private void trace(int[] result, int[] edges, int low, int high, int i, int width, int height) {
result[i] = 255;
for (int j = -1; j <= 1; j++) {
for (int k = -1; k <= 1; k++) {
int neighborIndex = i + j * width + k;
if (neighborIndex >= 0 && neighborIndex <
edges.length && result[neighborIndex] == 0 && edges[neighborIndex] >= low) {
trace(result, edges, low, high, neighborIndex, width, height);
}
}
}
}
private int[] getConvolution(int[] pixels, int[][] filter, int width, int height, int kernelSize) {
int[] result = new int[pixels.length];
int radius = kernelSize / 2;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double sum = 0.0;
for (int ky = -radius; ky <= radius; ky++) {
for (int kx = -radius; kx <= radius; kx++) {
int px = x + kx;
int py = y + ky;
if (px >= 0 && px < width && py >= 0 && py < height) {
int i = py * width + px;
double value = (double) pixels[i];
sum += value * filter[ky + radius][kx + radius];
}
}
}
int i = y * width + x;
result[i] = (int) sum;
}
}
return result;
}
|
09fc1df00ef01912f634799580317b1d
|
{
"intermediate": 0.2892190217971802,
"beginner": 0.40730342268943787,
"expert": 0.30347755551338196
}
|
1,098
|
задание: Исправить ошибку «Access violation at adress 006FF486 in module 'Project101.exe. Read of address 00000000» в предоставленном коде C++. Я выяснил, что ошибка появляется при выполнении функций: OpenConnection(), CreateProductsTable(), LoadDataFromDB().
Реализуйте решение для исправления ошибки «Нарушение прав доступа» в предоставленном коде C++.
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include “Unit108.h”
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource “*.dfm”
TForm108 *Form108;
TEdit *Edit1;
TADOQuery *ADOQuery1;
TADOConnection *ADOConnection1;
TEdit *Edit2;
TEdit *Edit3;
TMemo *Memo1;
TImage Image1;
TDataSource DataSource1;
TButton Button1;
TButton Button2;
TButton Button3;
TButton Button4;
TDBGrid DBGrid1;
TOpenDialog OpenDialog1;
// функция создания бд, таблицы
void CreateProductsTable()
{
String s;
s=“CREATE DATABASE IF NOT EXISTS catalog”;
ADOQuery1->SQL->Text=s;
//Добавлена проверка соединения перед выполнением запроса
if (ADOConnection1->Connected) {
ADOQuery1->ExecSQL();
}
s=“CREATE TABLE IF NOT EXISTS catalog.products (ID INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, Temp DOUBLE NOT NULL, price FLOAT(8, 2) NOT NULL, description TEXT NOT NULL, image MEDIUMBLOB NOT NULL, PRIMARY KEY (ID))”;
ADOQuery1->SQL->Text=s;
if (ADOConnection1->Connected) {
ADOQuery1->ExecSQL();
}
}
//Функция для открытия соединения с базой данных
void OpenConnection()
{
String c = “Provider=MSDASQL.1;Persist Security Info=False;Data Source=catalog”; //параметры подключения
try {
ADOConnection1->ConnectionString = c;
ADOConnection1->LoginPrompt = false;
ADOConnection1->Open(); //попытка открыть соединение
}
catch (EBcdException &e) //обработка исключения при ошибке в подключении к БД
{
ShowMessage(“Ошибка подключения к базе данных. Проверьте параметры подключения.”);
}
}
// функция загрузки данных из базы данных
void LoadDataFromDB()
{
if (ADOConnection1->Connected)
{
if (ADOQuery1->Active)
ADOQuery1->Close();
ADOQuery1->SQL->Clear();
ADOQuery1->SQL->Add(“SELECT * FROM catalog.products”);
if (ADOConnection1->Connected) {
ADOQuery1->Open();
}
}
}
// функция очистки формы после добавления или удаления товара
void ClearData()
{
Edit1->Text = “”;
Edit2->Text = “”;
Memo1->Text = “”;
Image1->Picture->LoadFromFile(“_blank.png”);
}
// функция добавления товара в базу данных
void AddProduct()
{
// проверка, что все поля заполнены
if (Edit1->Text == “” || Edit2->Text == “” || Memo1->Text == “”)
{
ShowMessage(“Заполните все поля!”);
return;
}
// подготовка запроса на добавление товара
ADOQuery1->SQL->Clear();
ADOQuery1->SQL->Add(“INSERT INTO catalog.products(name, price, description, image) VALUES(:name, :price, :description, :image)”);
ADOQuery1->Parameters->ParamByName(“name”)->Value = Edit1->Text;
ADOQuery1->Parameters->ParamByName(“price”)->Value = Edit2->Text;
ADOQuery1->Parameters->ParamByName(“description”)->Value = Memo1->Text;
TMemoryStream stream = new TMemoryStream();
Image1->Picture->Bitmap->SaveToStream(stream);
ADOQuery1->Parameters->ParamByName(“image”)->LoadFromStream(stream, ftGraphic);
ADOQuery1->ExecSQL();
// очистка формы и обновление каталога косметики
ClearData();
ADOQuery1->Close();
LoadDataFromDB();
}
// функция сохранения изменений в базе данных
void UpdateProduct()
{
// Проверка на незаполненость всех полей
if (Edit1->Text == “” || Edit2->Text == “” || Memo1->Text == “”)
{
ShowMessage(“Заполните все поля!”);
return;
}
if (ADOQuery1->State != dsEdit)
ADOQuery1->Edit();
// Сохранение изменений
ADOQuery1->FieldByName(“Name”)->AsString = Edit1->Text;
ADOQuery1->FieldByName(“Price”)->AsFloat = StrToFloatDef(Edit2->Text, 0);
ADOQuery1->FieldByName(“Description”)->AsString = Memo1->Text;
// Обновление изображения, если пользователь выбрал новое
if (Image1->Picture != nullptr)
{
ADOQuery1->FieldByName(“Image”)->Assign(Image1->Picture->Graphic);
}
// Закрытие и обновление данных
ADOQuery1->Post();
ADOQuery1->Close();
LoadDataFromDB();
// Очистка формы
ClearData();
}
// функция удаления товара из базы данных
void DeleteProduct()
{
// проверка, что выбран хотя бы один товар
if (DBGrid1->SelectedRows->Count == 0)
{
ShowMessage(“Выберите товар, который необходимо удалить!”);
return;
}
// удаление выбранных товаров
for (int i = 0; i < DBGrid1->SelectedRows->Count; i++)
{
DBGrid1->DataSource->DataSet->Bookmark = DBGrid1->SelectedRows->Items[i];
DBGrid1->DataSource->DataSet->Delete();
}
// сброс выбранных товаров и обновление каталога косметики
DBGrid1->DataSource->DataSet->First();
LoadDataFromDB();
}
//---------------------------------------------------------------------------
__fastcall TForm108::TForm108(TComponent Owner)
: TForm(Owner)
{
OpenConnection();
// создание таблицы products при запуске программы
CreateProductsTable();
// загрузка данных из базы данных при запуске программы
LoadDataFromDB();
}
//---------------------------------------------------------------------------
void __fastcall TForm108::Button1Click(TObject Sender)
{
AddProduct();
}
//---------------------------------------------------------------------------
void __fastcall TForm108::Button2Click(TObject Sender)
{
DeleteProduct();
}
//---------------------------------------------------------------------------
void __fastcall TForm108::Button3Click(TObject Sender)
{
UpdateProduct();
}
//---------------------------------------------------------------------------
void __fastcall TForm108::Button4Click(TObject Sender)
{
// Открытие диалога выбора файла
OpenDialog1->Filter = "Image Files (.bmp;.jpg;.jpeg;.png)|.bmp;.jpg;.jpeg;.png";
if (OpenDialog1->Execute())
{
// Загрузка выбранного изображения в TImage компонент
Image1->Picture->LoadFromFile(OpenDialog1->FileName);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm108::DBGrid1CellClick(TColumn Column)
{
// Заполнение полей данными выбранного товара
Edit1->Text = ADOQuery1->FieldByName(“Name”)->AsString;
Edit2->Text = FloatToStr(ADOQuery1->FieldByName(“Price”)->AsFloat);
Memo1->Text = ADOQuery1->FieldByName(“Description”)->AsString;
// Отображение изображения выбранного товара
if (ADOQuery1->FieldByName(“Image”)->IsBlob)
{
TMemoryStream stream = new TMemoryStream();
TBlobField field = dynamic_cast<TBlobField>(ADOQuery1->FieldByName(“Image”));
field->SaveToStream(stream);
if (stream->Size > 0)
{
stream->Position = 0;
Image1->Picture->LoadFromStream(stream);
}
delete stream;
}
else
{
Image1->Picture->LoadFromFile(“_blank.png”);
}
}
//------
|
2bd1c6c1c9ffbec669eae18e5ae359b6
|
{
"intermediate": 0.39182043075561523,
"beginner": 0.31309056282043457,
"expert": 0.2950889766216278
}
|
1,099
|
hey
|
b826b2cc7addfb402be4c3c05a2da35d
|
{
"intermediate": 0.33180856704711914,
"beginner": 0.2916048467159271,
"expert": 0.3765866458415985
}
|
1,100
|
Добавь в код реализацию детектора границ Канни с возможностью самому задавать маску и
основные параметры.
private void cannyImage() {
if (image != null) {
}
}
private BufferedImage applyCannyEdgeDetector(BufferedImage image, float[][] mask) {
}
|
7694ebe93018d0ce97aa38e744efbaa3
|
{
"intermediate": 0.4463304281234741,
"beginner": 0.29265522956848145,
"expert": 0.26101434230804443
}
|
1,101
|
library(rvest)
# create data frames for each section of data
data_A <- data.frame(
protocol_url_segment = character(),
A.1 = character(), A.2 = character(), A.3 = character(), A.3.1 = character(), A.3.2 = character(), A.4.1 = character(), A.5.1 = character(), A.5.2 = character(), A.5.3 = character(), A.5.4 = character(), A.7 = character(), A.8 = character(),
stringsAsFactors = FALSE
)
data_B <- data.frame(
protocol_url_segment = character(),
B.1.1 = character(), B.1.3.4 = character(), B.3.1.and.B.3.2 = character(), B.4.1 = character(), B.4.2 = character(), B.5.1 = character(),
B.5.2 = character(), B.5.3.1 = character(), B.5.3.2 = character(), B.5.3.3 = character(), B.5.3.4 = character(), B.5.4 = character(),
B.5.5 = character(), B.5.6 = character(),
stringsAsFactors = FALSE
)
data_D <- data.frame(
protocol_url_segment = character(),
IMP_number = character(),
D.1.2andD.1.3 = character(), D.2.1 = character(), D.2.1.1.1 = character(), D.2.1.1.2 = character(), D.2.1.2 = character(),
D.2.5 = character(), D.2.5.1 = character(), D.3.1 = character(), D.3.10.1 = character(), D.3.10.2 = character(), D.3.10.3 = character(),
D.3.11.1 = character(), D.3.11.10 = character(), D.3.11.11 = character(), D.3.11.12 = character(), D.3.11.13 = character(), D.3.11.13.1 = character(),
D.3.11.2 = character(), D.3.11.3 = character(), D.3.11.3.1 = character(), D.3.11.3.2 = character(),
D.3.11.3.3 = character(), D.3.11.3.4 = character(), D.3.11.3.5 = character(), D.3.11.3.5.1 = character(), D.3.11.4 = character(), D.3.11.5 = character(), D.3.11.6 = character(),
D.3.11.7 = character(), D.3.11.8 = character(), D.3.11.9 = character(), D.3.2 = character(),
D.3.4 = character(), D.3.4.1 = character(), D.3.7 = character(), D.3.8 = character(), D.3.9.1 = character(), D.3.9.2 = character(), D.3.9.3 = character(),
D.3.9.4 = character(), D.8.1 = character(), D.8.3 = character(), D.8.4 = character(), stringsAsFactors = FALSE
)
data_E <- data.frame(
protocol_url_segment = character(),
E.1.1 = character(), E.1.1.1 = character(), E.1.1.2 = character(), E.1.2A = character(), E.1.2B = character(), E.1.2C = character(), E.1.2D = character(), E.1.2E = character(), E.1.3 = character(),
E.2.1 = character(), E.2.2 = character(), E.2.3 = character(), E.2.3.1 = character(), E.3 = character(), E.4 = character(),
E.5.1 = character(), E.5.1.1 = character(), E.5.2 = character(), E.5.2.1 = character(),
E.6.1 = character(), E.6.10 = character(), E.6.11 = character(), E.6.12 = character(), E.6.13 = character(), E.6.13.1 = character(),
E.6.2 = character(), E.6.3 = character(), E.6.4 = character(), E.6.5 = character(), E.6.6 = character(), E.6.7 = character(), E.6.8 = character(), E.6.9 = character(),
E.7.1 = character(), E.7.1.1 = character(), E.7.1.2 = character(), E.7.1.3 = character(), E.7.1.3.1 = character(), E.7.2 = character(), E.7.3 = character(), E.7.4 = character(),
E.8.1 = character(), E.8.1.1 = character(), E.8.1.2 = character(), E.8.1.3 = character(), E.8.1.4 = character(), E.8.1.5 = character(), E.8.1.6 = character(), E.8.1.7 = character(), E.8.1.7.1 = character(),
E.8.2.1 = character(), E.8.2.2 = character(), E.8.2.3 = character(), E.8.2.3.1 = character(), E.8.2.4 = character(), E.8.3 = character(), E.8.4 = character(), E.8.4.1 = character(),
E.8.5 = character(), E.8.5.1 = character(), E.8.6.1 = character(), E.8.6.2 = character(), E.8.6.3 = character(), E.8.7 = character(), E.8.8 = character(),
E.8.9.1D = character(), E.8.9.1M = character(), E.8.9.1Y = character(), E.8.9.2D = character(), E.8.9.2M = character(), E.8.9.2Y = character(),
stringsAsFactors = FALSE
)
data_F <- data.frame(
protocol_url_segment = character(),
F.1.1A = character(), F.1.1B = character(), F.1.1.1 = character(), F.1.1.1.1 = character(), F.1.1.2 = character(), F.1.1.2.1 = character(),
F.1.1.3 = character(), F.1.1.3.1 = character(), F.1.1.4 = character(), F.1.1.4.1 = character(), F.1.1.5 = character(), F.1.1.5.1 = character(),
F.1.1.6 = character(), F.1.1.6.1 = character(), F.1.2 = character(), F.1.2.1 = character(), F.1.3 = character(), F.1.3.1 = character(),
F.2.1 = character(), F.2.2 = character(), F.3.1 = character(), F.3.2 = character(), F.3.3 = character(), F.3.3.1 = character(),
F.3.3.2 = character(), F.3.3.3 = character(), F.3.3.4 = character(), F.3.3.5 = character(), F.3.3.6 = character(),
F.3.3.6.1 = character(), F.3.3.7 = character(), F.3.3.7.1 = character(), F.4.1 = character(), F.4.2.1 = character(), F.4.2.2 = character(),
F.5 = character(),
stringsAsFactors = FALSE
)
data_G <- data.frame(
protocol_url_segment = character(),
network_number = character(),
G.4.1 = character(), G.4.3.4 = character(),
stringsAsFactors = FALSE
)
data_H <- data.frame(
protocol_url_segment = character(),
H.4.1 = character(),
stringsAsFactors = FALSE
)
data_N <- data.frame(
protocol_url_segment = character(),
N.A = character(), N.B = character(), N.C = character(), N.D = character(), N.E = character(),
stringsAsFactors = FALSE
)
data_P <- data.frame(
protocol_url_segment = character(),
P.A = character(), P.B = character(),
stringsAsFactors = FALSE
)
# specify the base URL of the protocol page
protocol_url_segment <- "2015-003589-10/GR"
base_url <- "https://www.clinicaltrialsregister.eu/ctr-search/trial/"
url <- paste0(base_url, protocol_url_segment)
# read in the HTML content of the page
page <- read_html(url)
# extract the tricell rows as a list of nodes
tricell_rows <- page %>% html_nodes("tr.tricell")
# function to extract the text from row td elements and create a row vector
extract_td_text <- function(row) {
td_elements <- html_children(row)
td_texts <- sapply(td_elements, html_text)
td_texts <- trimws(td_texts)
return(as.vector(td_texts))
}
# extract the text from the td elements in each row and store them in rows_list
rows_list <- lapply(tricell_rows, extract_td_text)
# create a data frame from the rows_list
tricell_df <- do.call(rbind.data.frame, c(rows_list, stringsAsFactors = FALSE))
colnames(tricell_df) <- c("Column1", "Column2", "Column3")
# Create a data frame with the codes and their corresponding replacements
lookup_df <- data.frame(
code = c("E.8.9.1", "E.8.9.1", "E.8.9.1", "E.8.9.2", "E.8.9.2", "E.8.9.2", "F.1.1", "F.1.1", "N.", "N.", "N.", "N.", "N.", "P.", "P.", "E.1.2", "E.1.2", "E.1.2", "E.1.2", "E.1.2", "B.3.1 and B.3.2", "D.1.2 and D.1.3"),
value = c("In the Member State concerned days", "In the Member State concerned months", "In the Member State concerned years", "In all countries concerned by the trial days", "In all countries concerned by the trial months", "In all countries concerned by the trial years", "Trial has subjects under 18", "Number of subjects for this age range:", "Competent Authority Decision", "Date of Competent Authority Decision", "Date of Ethics Committee Opinion", "Ethics Committee Opinion of the trial application", "Ethics Committee Opinion: Reason(s) for unfavourable opinion", "Date of the global end of the trial", "End of Trial Status", "Classification code", "Level", "System Organ Class", "Term", "Version", "Status of the sponsor", "IMP Role"),
replacement = c("E.8.9.1D", "E.8.9.1M", "E.8.9.1Y", "E.8.9.2D", "E.8.9.2M", "E.8.9.2Y", "F.1.1A", "F.1.1B", "N.A", "N.B", "N.C", "N.D", "N.E", "P.A", "P.B", "E.1.2A", "E.1.2B", "E.1.2C", "E.1.2D", "E.1.2E", "B.3.1andB.3.2", "D.1.2andD.1.3")
)
# Loop through each row in the target data frame and check if the code and value match
for (i in 1:nrow(tricell_df)) {
code <- tricell_df[i, 1]
value <- tricell_df[i, 2]
replacement <- lookup_df[lookup_df$code == code & lookup_df$value == value, "replacement"]
# If a match is found, replace the code with the corresponding replacement
if (length(replacement) > 0) {
tricell_df[i, 1] <- replacement
}
}
# Function that filters dataframe by the first letter in ‘Column1’ and returns the filtered dataframe
filter_by_first_letter <- function(df, letter) {
index <- grep(paste0("^", letter), df$Column1)
filtered_df <- df[index,]
return(filtered_df)
}
# Filter the dataframe for each letter, then create separate dataframes
df_A <- filter_by_first_letter(tricell_df, "A")
df_B <- filter_by_first_letter(tricell_df, "B")
df_D <- filter_by_first_letter(tricell_df, "D")
df_E <- filter_by_first_letter(tricell_df, "E")
df_F <- filter_by_first_letter(tricell_df, "F")
df_G <- filter_by_first_letter(tricell_df, "G")
df_H <- filter_by_first_letter(tricell_df, "H")
df_N <- filter_by_first_letter(tricell_df, "N")
df_P <- filter_by_first_letter(tricell_df, "P")
_____________
That's my code so far. I now want it to input the data in the "df_" dataframes (df_A, df_B, etc) into the "data_" dataframes. But these two sets of dataframes are structured differently.
"data_" dataframes have headers with each code.
"df_" dataframes, have these codes in the first column and the values in the third column.
The values in the "df_" dataframes should be inserted as a row in the "data_" dataframe.
|
42c9589278924efe2f2b39eb850b27ac
|
{
"intermediate": 0.561129093170166,
"beginner": 0.2883993089199066,
"expert": 0.15047158300876617
}
|
1,102
|
In python, make a machine learning model to predict a 5x5 minesweeper game. You can’t make it random or make it predict 2 same results in a row if a new game is started. You have data for the past 30 games [5, 12, 13, 4, 17, 19, 4, 18, 21, 1, 6, 11, 7, 15, 22, 14, 18, 19, 1, 19, 20, 9, 16, 17, 1, 19, 20, 6, 14, 24, 15, 20, 22, 7, 18, 21, 4, 16, 23, 5, 11, 19, 5, 6, 23, 6, 12, 13, 0, 5, 15, 1, 5, 22, 0, 2, 23, 5, 10, 13, 5, 12, 17, 1, 7, 22, 7, 11, 18, 7, 8, 9, 17, 21, 24, 13, 14, 16, 2, 3, 11, 7, 17, 18, 7, 14, 21, 2, 5, 9] and you need to predict x safe spots that are giving by the user and x possible bomb locations that amount is the giving mines amount.The data lenght changes by the selected mines. It's mines x 30, = all mine past data. So 3 mines becomes 90 past mines. You need to use the list raw and it needs to get the same data if the mine locations are not changed. It also needs to the accuracy
|
75740d2a905e18233297be9dd2310af3
|
{
"intermediate": 0.13684402406215668,
"beginner": 0.06368330121040344,
"expert": 0.7994726896286011
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.