问:
First Couple of Elements in a RecyclerView not Populating
needing some help fixing a bug with a personal project. My RecyclerView is not populating the first page of elements until I scroll down and scroll back up.

im not sure why it doing this because it loads the other elements just fine. would i need to limit the amount of elements that come into the recyclerview?

SchoolListAdapter.kt

```<code>package com.example.nycschools.view

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.nycschools.R
import com.example.nycschools.databinding.SchoolItemBinding
import com.example.nycschools.model.NYCSchools

/**
 * this class implements a [RecyclerView] [ListAdapter] which uses DataBinding to present [List] of [NYCSchools] data
 */

class SchoolListAdapter : ListAdapter<NYCSchools, SchoolListAdapter.SchoolListViewHolder>(DiffCallBack) {

    /**
     * Creates new [RecyclerView] item views
     */

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SchoolListAdapter.SchoolListViewHolder {
        return SchoolListViewHolder(SchoolItemBinding.inflate(LayoutInflater.from(parent.context)))
    }

    /**
     * Allows the [RecyclerView] to determine which items have changed when the [List] of [NYCSchools] has updated
     */

    companion object DiffCallBack: DiffUtil.ItemCallback<NYCSchools>() {
        override fun areItemsTheSame(oldItem: NYCSchools, newItem: NYCSchools): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: NYCSchools, newItem: NYCSchools): Boolean {
            return oldItem.schoolName == newItem.schoolName
        }
    }

    /**
     * Replaces the contents of a view
     */
    override fun onBindViewHolder(holder: SchoolListAdapter.SchoolListViewHolder, position: Int) {
        val nycSchools = getItem(position)
        holder.bind(nycSchools)
    }

    /**
     * This takes the binding variable from the associated [SchoolItemBinding], which gives it access to the full [NYCSchools] information
     * This also sends the databaseName to the schoolInfoFragment through Jetpack Navigation actions + arguments so the look up for the SAT Scores can be done
     */

    class SchoolListViewHolder(private val binding: SchoolItemBinding):
        RecyclerView.ViewHolder(binding.root) {
            fun bind(nycSchools: NYCSchools) {
                binding.buttonItem.text = nycSchools.schoolName
                binding.buttonItem.setOnClickListener {
                    binding.buttonItem.findNavController().navigate(R.id.action_schoolListFragment_to_schoolInfoFragment,
                        Bundle().apply {
                            putString("databaseName",nycSchools.id)
                        }
                    )
                }
                binding.executePendingBindings()
            }
    }
}
</code>```

SchoolListFragment.kt

```<code>package com.example.nycschools.view

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.example.nycschools.R
import com.example.nycschools.databinding.FragmentSchoolListBinding
import com.example.nycschools.viewmodels.NYCSchoolViewModel

class SchoolListFragment: Fragment() {

    private val viewModel: NYCSchoolViewModel by activityViewModels()
    private var binding: FragmentSchoolListBinding? = null

    /**
     * Creates the View, and inflates it on to the MainActivity
     */

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val fragmentBinding = FragmentSchoolListBinding.inflate(inflater,container,false)
        binding = fragmentBinding
        return fragmentBinding.root
    }

    /**
     * Called after the onCreateView to make sure the Fragments root is non-null
     */

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.viewModel = viewModel
        binding?.schoolListFragment = this
        binding?.lifecycleOwner = this
        binding?.schoolList?.adapter = SchoolListAdapter()
    }

    /**
     * This fragment lifecycle method is called when the view hierarchy associated with the fragment
     * is being removed. As a result, clear out the binding object.
     */

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }
}
</code>```

BindingAdapter.kt

```<code>package com.example.nycschools.view

import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.nycschools.model.NYCSchools

/**
 * Updates the data shown in the [RecyclerView]
 */

@BindingAdapter("schoolListData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<NYCSchools>?) {
    val adapter = recyclerView.adapter as SchoolListAdapter
    adapter.submitList(data)
}
</code>```

NYCSchools.kt

```<code>data class NYCSchools (
    @Json(name = "dbn") val id: String,
    @Json(name = "school_name") val schoolName: String)
</code>```

NYCSchoolsAPIService.kt

```<code>package com.example.nycschools.API

import com.example.nycschools.model.NYCSchools
import com.example.nycschools.model.NYCSchoolsWithSAT
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET

private const val BASE_URL = "https://data.cityofnewyork.us/resource/"

/**
 * Building a Moshi object with a Kotlin adapter factory that retrofit will be using
 */

private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

/**
 * Building the retrofit object with the moshi converter
 */

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(BASE_URL)
    .build()

/**
 * A Public interface that is used to get the Json Data for our Models
 *  NYCSchools
 *  NYCSchoolsWithSAT
 */

interface NYCSchoolsApiService {
    @GET("s3k6-pzi2")
    suspend fun getNYCSchools(): List<NYCSchools>

    @GET("f9bf-2cp4")
    suspend fun getNYCSchoolsWithSAT(): List<NYCSchoolsWithSAT>
}

/**
 * A public Api object that exposes the lazy-initialized Retrofit service
 * Basically a Singleton object (only gets called once)
 */

object NYCSchoolsAPI {
    val retrofitService: NYCSchoolsApiService by lazy { retrofit.create(NYCSchoolsApiService::class.java) }
}
</code>```

Fragment_school_list.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="viewModel"
            type="com.example.nycschools.viewmodels.NYCSchoolViewModel" />
        <variable
            name="schoolListFragment"
            type="com.example.nycschools.view.SchoolListFragment" />
    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".view.SchoolListFragment">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/schoolList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:schoolListData="@{viewModel.nycSchools}"
            android:clipToPadding="false"
            android:padding="16dp"
            tools:itemCount="12"
            tools:listitem="@layout/school_item"/>

    </FrameLayout>
</layout>
</code>```

Body:
needing some help fixing a bug with a personal project. My RecyclerView is not populating the first page of elements until I scroll down and scroll back up.

im not sure why it doing this because it loads the other elements just fine. would i need to limit the amount of elements that come into the recyclerview?

SchoolListAdapter.kt

package com.example.nycschools.view

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.navigation.findNavController
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.nycschools.R
import com.example.nycschools.databinding.SchoolItemBinding
import com.example.nycschools.model.NYCSchools

/**
 * this class implements a [RecyclerView] [ListAdapter] which uses DataBinding to present [List] of [NYCSchools] data
 */

class SchoolListAdapter : ListAdapter<NYCSchools, SchoolListAdapter.SchoolListViewHolder>(DiffCallBack) {

    /**
     * Creates new [RecyclerView] item views
     */

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SchoolListAdapter.SchoolListViewHolder {
        return SchoolListViewHolder(SchoolItemBinding.inflate(LayoutInflater.from(parent.context)))
    }

    /**
     * Allows the [RecyclerView] to determine which items have changed when the [List] of [NYCSchools] has updated
     */

    companion object DiffCallBack: DiffUtil.ItemCallback<NYCSchools>() {
        override fun areItemsTheSame(oldItem: NYCSchools, newItem: NYCSchools): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: NYCSchools, newItem: NYCSchools): Boolean {
            return oldItem.schoolName == newItem.schoolName
        }
    }

    /**
     * Replaces the contents of a view
     */
    override fun onBindViewHolder(holder: SchoolListAdapter.SchoolListViewHolder, position: Int) {
        val nycSchools = getItem(position)
        holder.bind(nycSchools)
    }

    /**
     * This takes the binding variable from the associated [SchoolItemBinding], which gives it access to the full [NYCSchools] information
     * This also sends the databaseName to the schoolInfoFragment through Jetpack Navigation actions + arguments so the look up for the SAT Scores can be done
     */

    class SchoolListViewHolder(private val binding: SchoolItemBinding):
        RecyclerView.ViewHolder(binding.root) {
            fun bind(nycSchools: NYCSchools) {
                binding.buttonItem.text = nycSchools.schoolName
                binding.buttonItem.setOnClickListener {
                    binding.buttonItem.findNavController().navigate(R.id.action_schoolListFragment_to_schoolInfoFragment,
                        Bundle().apply {
                            putString("databaseName",nycSchools.id)
                        }
                    )
                }
                binding.executePendingBindings()
            }
    }
}

SchoolListFragment.kt

package com.example.nycschools.view

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.example.nycschools.R
import com.example.nycschools.databinding.FragmentSchoolListBinding
import com.example.nycschools.viewmodels.NYCSchoolViewModel

class SchoolListFragment: Fragment() {

    private val viewModel: NYCSchoolViewModel by activityViewModels()
    private var binding: FragmentSchoolListBinding? = null

    /**
     * Creates the View, and inflates it on to the MainActivity
     */

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val fragmentBinding = FragmentSchoolListBinding.inflate(inflater,container,false)
        binding = fragmentBinding
        return fragmentBinding.root
    }

    /**
     * Called after the onCreateView to make sure the Fragments root is non-null
     */

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.viewModel = viewModel
        binding?.schoolListFragment = this
        binding?.lifecycleOwner = this
        binding?.schoolList?.adapter = SchoolListAdapter()
    }

    /**
     * This fragment lifecycle method is called when the view hierarchy associated with the fragment
     * is being removed. As a result, clear out the binding object.
     */

    override fun onDestroyView() {
        super.onDestroyView()
        binding = null
    }
}

BindingAdapter.kt

package com.example.nycschools.view

import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.nycschools.model.NYCSchools

/**
 * Updates the data shown in the [RecyclerView]
 */

@BindingAdapter("schoolListData")
fun bindRecyclerView(recyclerView: RecyclerView, data: List<NYCSchools>?) {
    val adapter = recyclerView.adapter as SchoolListAdapter
    adapter.submitList(data)
}

NYCSchools.kt

data class NYCSchools (
    @Json(name = "dbn") val id: String,
    @Json(name = "school_name") val schoolName: String)

NYCSchoolsAPIService.kt

package com.example.nycschools.API

import com.example.nycschools.model.NYCSchools
import com.example.nycschools.model.NYCSchoolsWithSAT
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET

private const val BASE_URL = "https://data.cityofnewyork.us/resource/"

/**
 * Building a Moshi object with a Kotlin adapter factory that retrofit will be using
 */

private val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .build()

/**
 * Building the retrofit object with the moshi converter
 */

private val retrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(BASE_URL)
    .build()

/**
 * A Public interface that is used to get the Json Data for our Models
 *  NYCSchools
 *  NYCSchoolsWithSAT
 */

interface NYCSchoolsApiService {
    @GET("s3k6-pzi2")
    suspend fun getNYCSchools(): List<NYCSchools>

    @GET("f9bf-2cp4")
    suspend fun getNYCSchoolsWithSAT(): List<NYCSchoolsWithSAT>
}

/**
 * A public Api object that exposes the lazy-initialized Retrofit service
 * Basically a Singleton object (only gets called once)
 */

object NYCSchoolsAPI {
    val retrofitService: NYCSchoolsApiService by lazy { retrofit.create(NYCSchoolsApiService::class.java) }
}

Fragment_school_list.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>
        <variable
            name="viewModel"
            type="com.example.nycschools.viewmodels.NYCSchoolViewModel" />
        <variable
            name="schoolListFragment"
            type="com.example.nycschools.view.SchoolListFragment" />
    </data>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".view.SchoolListFragment">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/schoolList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:schoolListData="@{viewModel.nycSchools}"
            android:clipToPadding="false"
            android:padding="16dp"
            tools:itemCount="12"
            tools:listitem="@layout/school_item"/>

    </FrameLayout>
</layout>


来源: stackexchange

问:
is there any way to use localStorage.getItem in Next js with redux toolkit?
I used localStorage.setItem() inside the redux toolkit slice it does work but when I want to use localStorage.getItem() in the side redux toolkit slice it does not work and it says local storage is not defined

```<code>import { createSlice } from "@reduxjs/toolkit";

const users=localStorage.getItem('users')!==null ?JSON.parse(localStorage.getItem("users")):[];
const initialState = { value: users };
const Users = createSlice({
  name: "users",
  initialState,
  reducers: {
    addUser: (state, action) => {
      state.value.push(action.payload);
      localStorage.setItem("users",JSON.stringify(state.value.map(item=>item)))
    },},});

export const { addUser} = Users.actions;
export default Users.reducer;
</code>```

But it says

ContentLicense: CC BY-SA 4.0

Body:
I used localStorage.setItem() inside the redux toolkit slice it does work but when I want to use localStorage.getItem() in the side redux toolkit slice it does not work and it says local storage is not defined

import { createSlice } from "@reduxjs/toolkit";

const users=localStorage.getItem('users')!==null ?JSON.parse(localStorage.getItem("users")):[];
const initialState = { value: users };
const Users = createSlice({
  name: "users",
  initialState,
  reducers: {
    addUser: (state, action) => {
      state.value.push(action.payload);
      localStorage.setItem("users",JSON.stringify(state.value.map(item=>item)))
    },},});

export const { addUser} = Users.actions;
export default Users.reducer;

But it says


问:
Lua not working, when trying to use Packer on Windows 10
I use nvim for my web development on my mac and I would love to do the same on my windows pc. I'm having problems installing the plugins with lua & packer for nvim though.

I have my init.lua in .config/nvim/ directory. I have Lua 5.1.5 installed on my PC, but I think it doesn't run when I open init.lua in vim. For example if I have print('init.lua loaded') in my init.lua file and open it in VIM. It doesn't notify it. But when I print in vim console it works...

I came upon this lua problem when debugging why my system doesn't recognize :PackerInstall or :Packer commands when trying to install plugins for nvim.

I'm totally new to lua on windows and don't really know how Packer should work on PC, but would love if someone could share experiences and solutions to this problem.


问:
Why is Scipy.linalg.eigh much slower when using np.complex64?
I have a large Hermitian matrix of which I need to calculate the eigenvalues and eigenvectors. For this I use scipy.linalg.eigh. Above a certain size of the matrix, scipy is much faster if np.complex128 is used as data type instead of np.complex64.

If I use np.complex64, the CPU load drops after some time and only one core is used. I checked the SciPy source and SciPy seems to use the cheevr or zheevr methods from lapack. I use SciPy with openblas-0.3.20. Is this a bug in openblas?

If I run the following code with 32 cores, it takes about 13 minutes with np.complex128 but more than 2 hours with np.complex64.

```<code>import numpy as np
import scipy.linalg
import time

n = 27
shape = (n**3, n**3)
dtype = np.complex64

H = np.random.uniform(-1, 1, shape) + 1.j * np.random.uniform(-1, 1, shape)
H = np.asarray(H, dtype=dtype)
start = time.time()
values, vectors = scipy.linalg.eigh(H)
print(f"It took {time.time() - start} seconds.")
</code>```

Body:
I have a large Hermitian matrix of which I need to calculate the eigenvalues and eigenvectors. For this I use scipy.linalg.eigh. Above a certain size of the matrix, scipy is much faster if np.complex128 is used as data type instead of np.complex64.

If I use np.complex64, the CPU load drops after some time and only one core is used. I checked the SciPy source and SciPy seems to use the cheevr or zheevr methods from lapack. I use SciPy with openblas-0.3.20. Is this a bug in openblas?

If I run the following code with 32 cores, it takes about 13 minutes with np.complex128 but more than 2 hours with np.complex64.

import numpy as np
import scipy.linalg
import time

n = 27
shape = (n**3, n**3)
dtype = np.complex64

H = np.random.uniform(-1, 1, shape) + 1.j * np.random.uniform(-1, 1, shape)
H = np.asarray(H, dtype=dtype)
start = time.time()
values, vectors = scipy.linalg.eigh(H)
print(f"It took {time.time() - start} seconds.")


问:
I have this problem: java.sql.SQLNonTransientConnectionException: Connection could not be authenticated. Reason: User ID or password invalid
So as shown above I get this error message while trying to add values to my Java derby Database. Full error-message is as shown:
run:

```<code>    at java.sql.SQLNonTransientConnectionException: Verbindung konnte nicht authentifiziert werden. Grund: Benutzer-ID oder Kennwort ungültig.org.apache.derby.client.am.SQLExceptionFactory.getSQLException(SQLExceptionFactory.java:74)
    at org.apache.derby.client.am.SqlException.getSQLException(SqlException.java:325)
    at org.apache.derby.client.ClientAutoloadedDriver.connect(ClientAutoloadedDriver.java:177)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:681)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
    at supermarket1.Seller.AddBtnMouseClicked(Seller.java:294)
    at supermarket1.Seller$1.mouseClicked(Seller.java:111)
    at java.desktop/java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:278)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6629)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
    at java.desktop/java.awt.Component.processEvent(Component.java:6391)
    at java.desktop/java.awt.Container.processEvent(Container.java:2266)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4584)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: ERROR 08004: Verbindung konnte nicht authentifiziert werden. Grund: Benutzer-ID oder Kennwort ungültig.
    at org.apache.derby.client.net.NetConnection.mapSecchkcd(NetConnection.java:1158)
    at org.apache.derby.client.net.NetConnection.securityCheckComplete(NetConnection.java:947)
    at org.apache.derby.client.net.NetConnectionReply.parseSECCHKRM(NetConnectionReply.java:582)
    at org.apache.derby.client.net.NetConnectionReply.parseSECCHKreply(NetConnectionReply.java:235)
    at org.apache.derby.client.net.NetConnectionReply.readSecurityCheck(NetConnectionReply.java:74)
    at org.apache.derby.client.net.NetConnection.readSecurityCheckAndAccessRdb(NetConnection.java:787)
    at org.apache.derby.client.net.NetConnection.flowSecurityCheckAndAccessRdb(NetConnection.java:724)
    at org.apache.derby.client.net.NetConnection.flowUSRIDPWDconnect(NetConnection.java:553)
    at org.apache.derby.client.net.NetConnection.flowConnect(NetConnection.java:355)
    at org.apache.derby.client.net.NetConnection.<init>(NetConnection.java:210)
    at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl.newNetConnection(ClientJDBCObjectFactoryImpl.java:278)
    at org.apache.derby.client.ClientAutoloadedDriver.connect(ClientAutoloadedDriver.java:170)
</code>```

First sentence of error message means:'Connection could not be authenticated. Reason: user ID or password invalid. '
I don't know where to type in user id or password and the program doesn't ask me to as well.
The source code is underneath, any help would be greeeaaatlyy appreciated.
Since im a total programming noob and im doing this after a yt-tutorial (https://www.youtube.com/watch?v=ByLOrDhn7B0&t=15277s    timestamp: 1:26:00), there might be an easy answer to this problem.

package supermarket1;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class Seller extends javax.swing.JFrame {

    public Seller() {
        initComponents();
    }
Connection Con = null;
Statement St = null;
ResultSet Rs = null;
public void SelectSeller()
{
        try {
            Con = DriverManager.getConnection("jdbc:derby://localhost:1527/SuperMarketdb","User1","1234");
            St = Con.createStatement();
            Rs = St.executeQuery("Select * from User1.SELLERTBL");
            SellerTable.setModel(null);

        } catch (Exception e) {
           e.printStackTrace();
        }
}

    // "Generated Code">  is not shown here because of Redundancy

    private void DeleteBtnActionPerformed(java.awt.event.ActionEvent evt) {

    }

    private void ClearBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void AddBtnMouseClicked(java.awt.event.MouseEvent evt) {

        if(SellId.getText().isEmpty() || SellName.getText().isEmpty() || SellPas.getText().isEmpty() )
        {
            JOptionPane.showMessageDialog(this, "Fehlende Informationen");
        }
        else{
        try{
    Con = DriverManager.getConnection("jdbc:derby://localhost:1527/SuperMarketdb","User1","1234");
    PreparedStatement add = Con.prepareStatement("insert into SELLERTBL values(?,?,?,?)");

            add.setInt(1, Integer.valueOf(SellId.getText()));
            add.setString(2, SellName.getText());
            add.setString(3, SellPas.getText());
            add.setString(4, GenderCb.getSelectedItem().toString());
            int row = add.executeUpdate();
            JOptionPane.showMessageDialog(this, "Verkäufer erfolgreich hinzugefügt!");

        }catch(Exception e)
        {
            e.printStackTrace();
        }
        }
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Seller().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton AddBtn;
    private javax.swing.JButton ClearBtn;
    private javax.swing.JButton DeleteBtn;
    private javax.swing.JButton EditBtn;
    private javax.swing.JComboBox<String> GenderCb;
    private javax.swing.JTextField SellId;
    private javax.swing.JTextField SellName;
    private javax.swing.JTextField SellPas;
    private javax.swing.JTable SellerTable;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
}
```

I tried everything but since im not an expert I don't know where to start.

Body:
So as shown above I get this error message while trying to add values to my Java derby Database. Full error-message is as shown:
run:

    at java.sql.SQLNonTransientConnectionException: Verbindung konnte nicht authentifiziert werden. Grund: Benutzer-ID oder Kennwort ungültig.org.apache.derby.client.am.SQLExceptionFactory.getSQLException(SQLExceptionFactory.java:74)
    at org.apache.derby.client.am.SqlException.getSQLException(SqlException.java:325)
    at org.apache.derby.client.ClientAutoloadedDriver.connect(ClientAutoloadedDriver.java:177)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:681)
    at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
    at supermarket1.Seller.AddBtnMouseClicked(Seller.java:294)
    at supermarket1.Seller$1.mouseClicked(Seller.java:111)
    at java.desktop/java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:278)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6629)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3389)
    at java.desktop/java.awt.Component.processEvent(Component.java:6391)
    at java.desktop/java.awt.Container.processEvent(Container.java:2266)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:5001)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2324)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4948)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4584)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4516)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2310)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2780)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4833)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:773)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:97)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:746)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:744)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:743)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: ERROR 08004: Verbindung konnte nicht authentifiziert werden. Grund: Benutzer-ID oder Kennwort ungültig.
    at org.apache.derby.client.net.NetConnection.mapSecchkcd(NetConnection.java:1158)
    at org.apache.derby.client.net.NetConnection.securityCheckComplete(NetConnection.java:947)
    at org.apache.derby.client.net.NetConnectionReply.parseSECCHKRM(NetConnectionReply.java:582)
    at org.apache.derby.client.net.NetConnectionReply.parseSECCHKreply(NetConnectionReply.java:235)
    at org.apache.derby.client.net.NetConnectionReply.readSecurityCheck(NetConnectionReply.java:74)
    at org.apache.derby.client.net.NetConnection.readSecurityCheckAndAccessRdb(NetConnection.java:787)
    at org.apache.derby.client.net.NetConnection.flowSecurityCheckAndAccessRdb(NetConnection.java:724)
    at org.apache.derby.client.net.NetConnection.flowUSRIDPWDconnect(NetConnection.java:553)
    at org.apache.derby.client.net.NetConnection.flowConnect(NetConnection.java:355)
    at org.apache.derby.client.net.NetConnection.<init>(NetConnection.java:210)
    at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl.newNetConnection(ClientJDBCObjectFactoryImpl.java:278)
    at org.apache.derby.client.ClientAutoloadedDriver.connect(ClientAutoloadedDriver.java:170)

First sentence of error message means:'Connection could not be authenticated. Reason: user ID or password invalid. '
I don't know where to type in user id or password and the program doesn't ask me to as well.
The source code is underneath, any help would be greeeaaatlyy appreciated.
Since im a total programming noob and im doing this after a yt-tutorial (https://www.youtube.com/watch?v=ByLOrDhn7B0&t=15277s    timestamp: 1:26:00), there might be an easy answer to this problem.

package supermarket1;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class Seller extends javax.swing.JFrame {

    public Seller() {
        initComponents();
    }
Connection Con = null;
Statement St = null;
ResultSet Rs = null;
public void SelectSeller()
{
        try {
            Con = DriverManager.getConnection("jdbc:derby://localhost:1527/SuperMarketdb","User1","1234");
            St = Con.createStatement();
            Rs = St.executeQuery("Select * from User1.SELLERTBL");
            SellerTable.setModel(null);

        } catch (Exception e) {
           e.printStackTrace();
        }
}

    // "Generated Code">  is not shown here because of Redundancy

    private void DeleteBtnActionPerformed(java.awt.event.ActionEvent evt) {

    }

    private void ClearBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    private void AddBtnMouseClicked(java.awt.event.MouseEvent evt) {

        if(SellId.getText().isEmpty() || SellName.getText().isEmpty() || SellPas.getText().isEmpty() )
        {
            JOptionPane.showMessageDialog(this, "Fehlende Informationen");
        }
        else{
        try{
    Con = DriverManager.getConnection("jdbc:derby://localhost:1527/SuperMarketdb","User1","1234");
    PreparedStatement add = Con.prepareStatement("insert into SELLERTBL values(?,?,?,?)");

            add.setInt(1, Integer.valueOf(SellId.getText()));
            add.setString(2, SellName.getText());
            add.setString(3, SellPas.getText());
            add.setString(4, GenderCb.getSelectedItem().toString());
            int row = add.executeUpdate();
            JOptionPane.showMessageDialog(this, "Verkäufer erfolgreich hinzugefügt!");

        }catch(Exception e)
        {
            e.printStackTrace();
        }
        }
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Seller().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton AddBtn;
    private javax.swing.JButton ClearBtn;
    private javax.swing.JButton DeleteBtn;
    private javax.swing.JButton EditBtn;
    private javax.swing.JComboBox<String> GenderCb;
    private javax.swing.JTextField SellId;
    private javax.swing.JTextField SellName;
    private javax.swing.JTextField SellPas;
    private javax.swing.JTable SellerTable;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
}

I tried everything but since im not an expert I don't know where to start.


Title: Classification using python

Body:
[[ 82  32  14 ...   8 113 128]
 [  2  32  70 ...   8 113 128]
 [ 18  32  78 ...   8 113 128]
 ...
 [ 92  48 249 ... 240   7 115]
 [ 24 141  11 ... 170 176 168]
 [188 165   8 ... 203 144 128]]

I got this type of data and i want to classify the data and get the accuracy of them by using Python.


问:
best strategy apply a hot fix to two different release versions, that have version tags and their own changelogs
The background:

The background context is that two release branches can exist at once. One will be in 'prod' environment and one in 'alpha'.

Let's say the two branches are release/1.1.0 (which is in prod) and release/1.2.0 (which is in alpha). release/1.1.0 is still completely in the history of release/1.2.0. In fact, let's say release/1.2.0 is just one additional feature commit ahead of release/1.1.0. The tip of release/1.1.0 is commit 123abc and the tip of release/1.2.0 is 456def,

A semantic versioning tool is used that can bump the version by traversing the commits and bumping based on conventional commit formats (feat/fix/etc...).  The tool updates the changelog and applies a tag to the commit at the tip of the branch.

Right now, the tip of release/1.1.0 has been tagged v1.1.0 and the tip of release/1.2.0 has been tagged v1.2.0.

The problem:

An error is detected in v1.1.0 while it is running in prod. To fix the issue, a hotfix branch is created off of release/1.1.0, the code is fixed and that branch is merged into release/1.1.0 and release/1.2.0 (and also the dev branch). The versioning tool is run on both branches, and their version have changes to v1.1.1 and v1.2.0.  Nothing has 'broken' yet...but I think those steps I just described are wrong and set us up for what I am about to describe in the paragraph below. The branches have now diverged - they both have the same commits, but the fix order is wrong. What I mean is release/1.2.0 does not have a version 1.1.1 in it's history. Also, the branch names are still release/1.1.0 and release/1.2.0 even though those are no longer their versions, which seems wrong.

Now, lets' say, another error is detected in prod. So we make another hotfix branch off of release/1.1.0. We then merge that in to release/1.1.0 and release/1.2.0. Now we have problem. First off, there are merge conflicts between the changelogs, and release/1.2.0 will look like it went from version 1.2.0 to 1.2.1 to 1.1.1 because the hotfix branch contains the commit that has been tagged as 1.1.1. It's a mess.

Is there a better way to apply the fix to both releases without destroying the version history and have changelog merge hell? I had thought of rebasing release/1.2.0 onto the hotfix branch. But I think there are problems with that... maybe I would first have to destroy all version tags that are > 1.1.1 and also undo the changelog commits before rebasing, and then rerun the version tool after rebasing

Another thought is to checkout the dev branch at the commit where release/1.1.0 was branched off. Write a test and fix the code, then commit that (I will refer to this commit as the fix_commit in the next lines). Rebase the rest of dev back on to the fix_commit, so that dev now has that commit in its history. Then, branch off a new release/1.1.1 at the fix_commit. Then, branch off a new release/1.2.0 from the same commit that is was originally branched off from. What is odd here is that release/1.2.0 would still be 1.2.0 because the fix is in it's history before the feat commit that causes the bump from 1.1.x -> 1.2.0. Maybe that is good? I like this idea because it is closer to trunk-based dev in that work is always done on the dev branch

Another thought: fix release/1.1.0 directly, no hotfix branch, just commit the fix and increment the version (if I want, I could then branch off release/1.1.1 and deploy that, and delete release/1.1.0). Then cherry pick the commit to release/1.2.0, and increment the version to 1.2.1. (and then also apply the cherry picked commit to dev).

What is the best strategy?

More background:
We are moving to trunk based dev. I understand, in trunk based dev, you only ever have one release live. If an issue is detected, your write a test for it on the dev and then make a new release. You are never branching off of a release, for a hot fix, and the merging that back into your release and dev.

However, we have alpha and prod environments and we usually have one version in prod and a version that is further ahead in alpha. So, we can not follow the pattern of only every having one release. I suspect a suggestion would be to not use two releases to differentiate between what is in prod and alpha and to, instead, use feature flags. The flags would be on in alpha and off in prod (and the flag could be set by an environment variable). That way, we really only have one release.  That could be great also, but that would require some other changes in our dev process.


问:
CustomPainter's paint method is not getting called before WidgetsBinding.instance.addPostFrameCallback in case of Multiple navigation
I have a Flutter StatefulWidget and in initState() method I am using WidgetsBinding.instance.addPostFrameCallback to use one instance variable (late List _tracks). like -

```<code>WidgetsBinding.instance.addPostFrameCallback((_) {
      for(itr = 0; itr<_tracks.length; itr++){
         // some logic
      }
    });
</code>```

As this would get invoked after all Widgets are done. In one of the CustomPaint's painter class I am initializing that variable.

```<code>SizedBox.expand(
       child: CustomPaint(
            painter: TrackPainter(
                   trackCalculationListener: (tracks) {
                     _tracks = tracks;
              }),
           ),
        ),
</code>```

It is working fine when I have one screen, i.e the same class. But, When I am adding one screen before that and trying to navigate to this screen from the new screen it is throwing _tracks is not initialized exception.
new screen is very basic -

```<code>class MainMenu extends StatefulWidget {
  const MainMenu({super.key});

  @override
  State<MainMenu> createState() => _MainMenuState();
}

class _MainMenuState extends State<MainMenu> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => const Play(),
                    maintainState: false));
          },
          child: const Text('play game'),
        ),
      ),
    );
  }
}
</code>```

In single screen case the paint method of painter is getting called before postFrameCallback but in case of multiple it is not getting before postFrameCallback and because of that the variable is not getting initialized.

reproducible code -

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/mainMenu': (context) => const MainMenu(),
        '/game': (context) => const MyHomePage(title: 'game'),
      },
      initialRoute: '/mainMenu',
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late List<Rect> _playerTracks;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      print(_playerTracks.length);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              color: Colors.white,
              margin: const EdgeInsets.all(20),
              child: AspectRatio(
                aspectRatio: 1,
                child: SizedBox.expand(
                  child: CustomPaint(
                    painter: RectanglePainter(
                        trackCalculationListener: (playerTracks) =>
                            _playerTracks = playerTracks),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class MainMenu extends StatefulWidget {
  static String route = '/mainMenu';
  const MainMenu({super.key});

  @override
  State<MainMenu> createState() => _MainMenuState();
}

class _MainMenuState extends State<MainMenu> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          height: 200.0,
          color: Colors.white,
          child: ElevatedButton(
            onPressed: () {
              Navigator.pushNamed(context, '/game');
            },
            child: const Text('play game'),
          ),
        ),
      ),
    );
  }
}

class RectanglePainter extends CustomPainter {
  Function(List<Rect>) trackCalculationListener;

  RectanglePainter({required this.trackCalculationListener});

  @override
  void paint(Canvas canvas, Size size) {
    final Rect rect = Offset.zero & size;
    const RadialGradient gradient = RadialGradient(
      center: Alignment(0.7, -0.6),
      radius: 0.2,
      colors: <Color>[Color(0xFFFFFF00), Color(0xFF0099FF)],
      stops: <double>[0.4, 1.0],
    );
    canvas.drawRect(
      rect,
      Paint()..shader = gradient.createShader(rect),
    );
    List<Rect> _playerTracks = [];
    _playerTracks.add(rect);
    trackCalculationListener(_playerTracks);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}
</code>```

I am very new to flutter and would highly appreciate if someone could help me figure out what I am doing wrong here.

Body:
I have a Flutter StatefulWidget and in initState() method I am using WidgetsBinding.instance.addPostFrameCallback to use one instance variable (late List _tracks). like -

WidgetsBinding.instance.addPostFrameCallback((_) {
      for(itr = 0; itr<_tracks.length; itr++){
         // some logic
      }
    });

As this would get invoked after all Widgets are done. In one of the CustomPaint's painter class I am initializing that variable.

SizedBox.expand(
       child: CustomPaint(
            painter: TrackPainter(
                   trackCalculationListener: (tracks) {
                     _tracks = tracks;
              }),
           ),
        ),

It is working fine when I have one screen, i.e the same class. But, When I am adding one screen before that and trying to navigate to this screen from the new screen it is throwing _tracks is not initialized exception.
new screen is very basic -

class MainMenu extends StatefulWidget {
  const MainMenu({super.key});

  @override
  State<MainMenu> createState() => _MainMenuState();
}

class _MainMenuState extends State<MainMenu> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => const Play(),
                    maintainState: false));
          },
          child: const Text('play game'),
        ),
      ),
    );
  }
}

In single screen case the paint method of painter is getting called before postFrameCallback but in case of multiple it is not getting before postFrameCallback and because of that the variable is not getting initialized.

reproducible code -

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/mainMenu': (context) => const MainMenu(),
        '/game': (context) => const MyHomePage(title: 'game'),
      },
      initialRoute: '/mainMenu',
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late List<Rect> _playerTracks;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      print(_playerTracks.length);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Container(
              color: Colors.white,
              margin: const EdgeInsets.all(20),
              child: AspectRatio(
                aspectRatio: 1,
                child: SizedBox.expand(
                  child: CustomPaint(
                    painter: RectanglePainter(
                        trackCalculationListener: (playerTracks) =>
                            _playerTracks = playerTracks),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class MainMenu extends StatefulWidget {
  static String route = '/mainMenu';
  const MainMenu({super.key});

  @override
  State<MainMenu> createState() => _MainMenuState();
}

class _MainMenuState extends State<MainMenu> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          height: 200.0,
          color: Colors.white,
          child: ElevatedButton(
            onPressed: () {
              Navigator.pushNamed(context, '/game');
            },
            child: const Text('play game'),
          ),
        ),
      ),
    );
  }
}

class RectanglePainter extends CustomPainter {
  Function(List<Rect>) trackCalculationListener;

  RectanglePainter({required this.trackCalculationListener});

  @override
  void paint(Canvas canvas, Size size) {
    final Rect rect = Offset.zero & size;
    const RadialGradient gradient = RadialGradient(
      center: Alignment(0.7, -0.6),
      radius: 0.2,
      colors: <Color>[Color(0xFFFFFF00), Color(0xFF0099FF)],
      stops: <double>[0.4, 1.0],
    );
    canvas.drawRect(
      rect,
      Paint()..shader = gradient.createShader(rect),
    );
    List<Rect> _playerTracks = [];
    _playerTracks.add(rect);
    trackCalculationListener(_playerTracks);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

I am very new to flutter and would highly appreciate if someone could help me figure out what I am doing wrong here.


问:
TFGPT2LMHeadModel to TFLite changes the input and output shape
The TFGPT2LMHeadModel convertion to TFlite renders unexpected input and output shape
as oppoed to the pre trained model gpt2-64.tflite , how can we fix the same ?

```<code>!wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-64.tflite

import numpy as np
import tensorflow as tf

tflite_model_path = 'gpt2-64.tflite'
# Load the TFLite model and allocate tensors
interpreter = tf.lite.Interpreter(model_path=tflite_model_path)
interpreter.allocate_tensors()

# Get input and output tensors
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_shape = input_details[0]['shape']

#print the output
input_data = np.array(np.random.random_sample((input_shape)), dtype=np.int32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data.shape)
print(input_shape)
</code>```

Gives output as

```<code>>(1, 64, 50257)

> [ 1 64]
</code>```

which is as expected

but when we try to convert TFGPT2LMHeadModel to TFLITE , we get different output as below

```<code>import tensorflow as tf
from transformers import TFGPT2LMHeadModel
import numpy as np

model = TFGPT2LMHeadModel.from_pretrained('gpt2') # or 'distilgpt2'

input_spec = tf.TensorSpec([1, 64], tf.int32)
model._set_inputs(input_spec, training=False)

converter = tf.lite.TFLiteConverter.from_keras_model(model)

# For FP16 quantization:
# converter.optimizations = [tf.lite.Optimize.DEFAULT]
# converter.target_spec.supported_types = [tf.float16]

tflite_model = converter.convert()

open("gpt2-64-2.tflite", "wb").write(tflite_model)

tflite_model_path = 'gpt2-64-2.tflite'
# Load the TFLite model and allocate tensors
interpreter = tf.lite.Interpreter(model_path=tflite_model_path)
interpreter.allocate_tensors()

# Get input and output tensors
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_shape = input_details[0]['shape']

#print the output
input_data = np.array(np.random.random_sample((input_shape)), dtype=np.int32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data.shape)
print(input_shape)
</code>```

Output:

```<code>>(2, 1, 12, 1, 64)
>[1 1]
</code>```

How can we fix the same ?

Body:
The TFGPT2LMHeadModel convertion to TFlite renders unexpected input and output shape
as oppoed to the pre trained model gpt2-64.tflite , how can we fix the same ?

!wget https://s3.amazonaws.com/models.huggingface.co/bert/gpt2-64.tflite

import numpy as np
import tensorflow as tf

tflite_model_path = 'gpt2-64.tflite'
# Load the TFLite model and allocate tensors
interpreter = tf.lite.Interpreter(model_path=tflite_model_path)
interpreter.allocate_tensors()

# Get input and output tensors
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_shape = input_details[0]['shape']

#print the output
input_data = np.array(np.random.random_sample((input_shape)), dtype=np.int32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data.shape)
print(input_shape)

Gives output as

>(1, 64, 50257)

> [ 1 64]

which is as expected

but when we try to convert TFGPT2LMHeadModel to TFLITE , we get different output as below

import tensorflow as tf
from transformers import TFGPT2LMHeadModel
import numpy as np

model = TFGPT2LMHeadModel.from_pretrained('gpt2') # or 'distilgpt2'

input_spec = tf.TensorSpec([1, 64], tf.int32)
model._set_inputs(input_spec, training=False)

converter = tf.lite.TFLiteConverter.from_keras_model(model)

# For FP16 quantization:
# converter.optimizations = [tf.lite.Optimize.DEFAULT]
# converter.target_spec.supported_types = [tf.float16]

tflite_model = converter.convert()

open("gpt2-64-2.tflite", "wb").write(tflite_model)

tflite_model_path = 'gpt2-64-2.tflite'
# Load the TFLite model and allocate tensors
interpreter = tf.lite.Interpreter(model_path=tflite_model_path)
interpreter.allocate_tensors()

# Get input and output tensors
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

input_shape = input_details[0]['shape']

#print the output
input_data = np.array(np.random.random_sample((input_shape)), dtype=np.int32)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data.shape)
print(input_shape)

Output:

>(2, 1, 12, 1, 64)
>[1 1]

How can we fix the same ?


问:
Auth0 Real-time Webtask Logs Extension not working and user not getting stored in database
I am using the Auth0 Real-time Webtask Logs Extension to debug the create action script of my custom database. I have placed a few console log statements in the script, but nothing is being outputted in the Real-time Webtask Logs. I have already installed and configured the extension in my Auth0 dashboard, and I have selected the correct tenant in the Real-time Webtask Logs Extension console. I have also checked the logs in the Auth0 dashboard to make sure that the script is being executed and that there are no errors. However, the output from the console log statements is still not being displayed in the Real-time Webtask Logs Extension console.

The other problem is that the user is not getting stored in the database after registration. The script seems to be executing correctly as I am able to receive the authResult that is returned by the callback of auth0.WebAuth.signup() method, but the user is not being added to the database. I am not sure if these two issues are related or if there is a separate issue with the database connection or the insert query.

Here's what my signup code looks like:

```<code>const auth0 = new auth0.WebAuth({
  clientID: 'MY_CLIENT_ID',
  domain: 'MY_AUTH0_DOMAIN'
});

auth0.WebAuth.signup({
  connection: 'Username-Password-Authentication',
  email: 'user@example.com',
  password: 'password',
  userMetadata: { // this will be stored in user_metadata
    firstName: 'John',
    lastName: 'Doe'
  }
}, function(err, result) {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});
</code>```

Here is what my create action script looks like:

```<code>function create(user, callback) {
  const mysql = require('mysql');
  const bcrypt = require('bcrypt');

  const connection = mysql.createConnection({
        host: 'host',
    user: 'user',
    password: 'pwd',
    database: 'database',
    port: 8000,
  });

  console.log("test");

  connection.connect();

  const query = 'INSERT INTO users SET ?';

  bcrypt.hash(user.password, 10, function(err, hash) {
    const insert = {
      fname: user.firstName,
      lname: user.lastName,
      email: user.email,
      password: hash,
    };

    connection.query(query, insert, function (err, results) {
      console.log("saving");
      if (err) return callback(err);
      if (results.length === 0) return callback();
      console.log("success");
      callback(null);
    });
  });
}
</code>```

FYI, when I test the script using Auth0's Save and Try feature, the user gets stored in the database. Also, the login script works without any issues.

How can I fix these issues and ensure that the Real-time Webtask Logs Extension works and the user gets stored in the database after registration?

Body:
I am using the Auth0 Real-time Webtask Logs Extension to debug the create action script of my custom database. I have placed a few console log statements in the script, but nothing is being outputted in the Real-time Webtask Logs. I have already installed and configured the extension in my Auth0 dashboard, and I have selected the correct tenant in the Real-time Webtask Logs Extension console. I have also checked the logs in the Auth0 dashboard to make sure that the script is being executed and that there are no errors. However, the output from the console log statements is still not being displayed in the Real-time Webtask Logs Extension console.

The other problem is that the user is not getting stored in the database after registration. The script seems to be executing correctly as I am able to receive the authResult that is returned by the callback of auth0.WebAuth.signup() method, but the user is not being added to the database. I am not sure if these two issues are related or if there is a separate issue with the database connection or the insert query.

Here's what my signup code looks like:

const auth0 = new auth0.WebAuth({
  clientID: 'MY_CLIENT_ID',
  domain: 'MY_AUTH0_DOMAIN'
});

auth0.WebAuth.signup({
  connection: 'Username-Password-Authentication',
  email: 'user@example.com',
  password: 'password',
  userMetadata: { // this will be stored in user_metadata
    firstName: 'John',
    lastName: 'Doe'
  }
}, function(err, result) {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});

Here is what my create action script looks like:

function create(user, callback) {
  const mysql = require('mysql');
  const bcrypt = require('bcrypt');

  const connection = mysql.createConnection({
        host: 'host',
    user: 'user',
    password: 'pwd',
    database: 'database',
    port: 8000,
  });

  console.log("test");

  connection.connect();

  const query = 'INSERT INTO users SET ?';

  bcrypt.hash(user.password, 10, function(err, hash) {
    const insert = {
      fname: user.firstName,
      lname: user.lastName,
      email: user.email,
      password: hash,
    };

    connection.query(query, insert, function (err, results) {
      console.log("saving");
      if (err) return callback(err);
      if (results.length === 0) return callback();
      console.log("success");
      callback(null);
    });
  });
}

FYI, when I test the script using Auth0's Save and Try feature, the user gets stored in the database. Also, the login script works without any issues.

How can I fix these issues and ensure that the Real-time Webtask Logs Extension works and the user gets stored in the database after registration?


问:
Is there a better approach to "grab" every database row as one unique variable for it in Laravel?
In my controller I need to pick all of these rows and doing like this currently:

```<code>$policy1 = GlobalVariable::findOrFail(1);
$policy2 = GlobalVariable::findOrFail(2);
$policy3 = GlobalVariable::findOrFail(3);
$policy4 = GlobalVariable::findOrFail(4);
</code>```

Is there a better approach to grab these four rows and assign variable row key names for them?

Body:
In my controller I need to pick all of these rows and doing like this currently:

$policy1 = GlobalVariable::findOrFail(1);
$policy2 = GlobalVariable::findOrFail(2);
$policy3 = GlobalVariable::findOrFail(3);
$policy4 = GlobalVariable::findOrFail(4);

Is there a better approach to grab these four rows and assign variable row key names for them?


问:
From features to sequence
I want to create a model that start with some features (like mean, std and more) and it ends to recreate the signal. Looking on the internet i understood that if i want to create this kind of model i have to use LSTM, but the only example that i find (for time series) are forecasting models.

I tried to create a model with a single LSTM neuron, and as input the n features but it didnt give me the hopped results. My questions are : Can you suggest me a paper that can explain me better what i want to accomplish ? There are other different ways to proceed ?

Title: From features to sequence


问:
How to run javascript with flutter Windows
Is there any way to use flutter in Windows in order to call javascript methods that would require a browser? For example if I use a js method that does a simple task as return a + b it works, but if i try to use browser methods like window.open() it does not

Things I tried:

InAppWebView, but does not support Windows

flutter_html, i could make a page according to a given html code, but the javascripts functions would not run


问:
Events with EthersJS are fired multiple times
I have a simple DApp in which I can deposit and withdraw Ethers

But when executing the following code :

```<code>useEffect(() => {
        const contract = new ethers.Contract(contractAddress, Contract.abi, provider)
        contract.on("etherDeposited", (account, amount) => {
            toast({
                title: 'Deposit Event',
                description: "Account : " + account + " - amount " + amount,
                status: 'success',
                duration: 5000,
                isClosable: true,
            })
        })
    }, [])
</code>```

We can see that there is some bad rendering there or something like this, I don't understand.

I've tried to remove the listener by doing

```<code>useEffect(() => {
        const contract = new ethers.Contract(contractAddress, Contract.abi, provider)
        contract.on("etherDeposited", (account, amount) => {
            toast({
                title: 'Deposit Event',
                description: "Account : " + account + " - amount " + amount,
                status: 'success',
                duration: 5000,
                isClosable: true,
            })
        })
        return () => {
            contract.removeAllListeners();
        };
    }, [])
</code>```

But it doesn't change anything, it's even worse. What did I do wrong there ?

Thank you for your answers !

Body:
I have a simple DApp in which I can deposit and withdraw Ethers

But when executing the following code :

useEffect(() => {
        const contract = new ethers.Contract(contractAddress, Contract.abi, provider)
        contract.on("etherDeposited", (account, amount) => {
            toast({
                title: 'Deposit Event',
                description: "Account : " + account + " - amount " + amount,
                status: 'success',
                duration: 5000,
                isClosable: true,
            })
        })
    }, [])

We can see that there is some bad rendering there or something like this, I don't understand.

I've tried to remove the listener by doing

useEffect(() => {
        const contract = new ethers.Contract(contractAddress, Contract.abi, provider)
        contract.on("etherDeposited", (account, amount) => {
            toast({
                title: 'Deposit Event',
                description: "Account : " + account + " - amount " + amount,
                status: 'success',
                duration: 5000,
                isClosable: true,
            })
        })
        return () => {
            contract.removeAllListeners();
        };
    }, [])

But it doesn't change anything, it's even worse. What did I do wrong there ?

Thank you for your answers !


问:
ChromeDriverManager().install() is giving error while running through Jenkins
I am working on Python BDD with selenium, and I am using

```<code>self.driver = webdriver.Chrome(
    service=ChromeService(
        ChromeDriverManager().install()
    ),
    options=chrome_options
)
</code>```

to launch the chrome browser.
This is working fine when it is running in local but when I try to run it through Jenkins I get the following error:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
    raise err
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable
</code>```

I tried to change the proxy setting in Jenkins but still facing the problem.

Body:
I am working on Python BDD with selenium, and I am using

self.driver = webdriver.Chrome(
    service=ChromeService(
        ChromeDriverManager().install()
    ),
    options=chrome_options
)

to launch the chrome browser.
This is working fine when it is running in local but when I try to run it through Jenkins I get the following error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/urllib3/connection.py", line 174, in _new_conn
    conn = connection.create_connection(
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 95, in create_connection
    raise err
  File "/usr/local/lib/python3.10/site-packages/urllib3/util/connection.py", line 85, in create_connection
    sock.connect(sa)
OSError: [Errno 101] Network is unreachable

I tried to change the proxy setting in Jenkins but still facing the problem.


问:
Not able receive any inbound sms in twilio
I'm using python to create sms service using twilio . I've done with sms sending part but not able to receive reply back (inbound sms). How to fix this?

Using twilio api , but not able to see inbound sms in logs


问:
Webgpu shows scripting in Idle state
I've been tinkering with WebGPU and, when profiling the page on a couple different pages, I see that the script is marked as Idle. This makes it hard to estimate the actual rendering budget, as the time that the JS is executing is actually quite small but it looks much larger due to the Idle marking. Is there anyway to clear up this Idle when using WebGPU? Thanks!

Title: Webgpu shows scripting in Idle state


问:
Can't get the default controller of codeigniter to work in IIS
I am trying to host a codeigniter project on IIS Server but I can't get even the default controller to show instead what I receive is this below

```<code>A PHP Error was encountered
Severity: 8192

Message: Creation of dynamic property CI_URI::$config is deprecated

Filename: core/URI.php

Line Number: 101

Backtrace:

File: C:\inetpub\wwwroot\app\index.php
Line: 315
Function: require_once
</code>```

I have web.config file, HTTP mappings, ISAPI, URL rewrite module and FastCGI all set but still the problem persist.
I will be very grateful if you guys can help me, am stranded.

Body:
I am trying to host a codeigniter project on IIS Server but I can't get even the default controller to show instead what I receive is this below

A PHP Error was encountered
Severity: 8192

Message: Creation of dynamic property CI_URI::$config is deprecated

Filename: core/URI.php

Line Number: 101

Backtrace:

File: C:\inetpub\wwwroot\app\index.php
Line: 315
Function: require_once

I have web.config file, HTTP mappings, ISAPI, URL rewrite module and FastCGI all set but still the problem persist.
I will be very grateful if you guys can help me, am stranded.


问:
SourceBuffer's appendBuffer() not appending arrayBuffer
Context:

1.) Confirmed that the backend is returning a range of bytes using StreamingResponseBody (I'm using spring boot) via 206 response code

2.) Confirmed that the received data makes sense, I think, by comparing the logs displayed here chrome://media-internals/ with the logs displayed when I play any YouTube video. I attached some pictures to show this.

3.) On the frontend, byte stream gets converted into an arrayBuffer via response.arrayBuffer()

4.) Confirmed that the video's codec profile is video/mp4; codecs="avc1.64002a,mp4a.40.2"; profiles="mp42,mp41" . Used mp4box (https://github.com/gpac/mp4box.js) to get the codec and profile and confirmed that the browser supports this MediaSource.isTypeSupported('video/mp4; codecs="avc1.64002a"; profiles="mp42,mp41"'); I'm using google chrome to test this.

Issue:

1.) It looks like buffered isn't getting updated, because it's TimeRange length is not changing and that sourceBuffer.buffered.end(0) and sourceBuffer.buffered.start(0) remains undefined

2.) And because of the previous issue, <video /> doesn't play.

Using a callback getVideoStreamResourceAPI to receive the arrayBuffer, the following is my code

```<code>getVideoStreamResourceAPI(pathVariables, identityPayload, resp => {
                    const mediaSource = new MediaSource();
                    videoRef.current.src = URL.createObjectURL(mediaSource);
                    mediaSource.addEventListener('sourceopen', sourceOpen, {once: true});

                    function sourceOpen() {
                        URL.revokeObjectURL(videoRef.current.src);
                        var sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.64002a,mp4a.40.2"; profiles="mp42,mp41"');

                        sourceBuffer.addEventListener('update', sourceBufferUpdate, { once: true });
                        sourceBuffer.appendBuffer(resp);
                        sourceBuffer.addEventListener('updateend', updateEnd, { once: true });
                    }

                    function sourceBufferUpdate(e) {
                        console.log("updated: ", e);
                    }

                    function updateEnd(e) {
                        console.log("updatedEnded: ", e);
                        console.log("buffered: ", videoRef.current.buffered);
                        videoRef.current.addEventListener('playing', fetchNextSegment, { once: true });
                    }

                    function fetchNextSegment() {
                        console.log("fetching next segment");
                    }

                    setSpinner(null);
                });
</code>```

NOTE:
resp contains the arrayBuffer and fetchNextSegment() isn't getting called.

Any suggestions, ideas, and help would be greatly appreciated. Thanks for taking the time to read this.

Body:
Context:

1.) Confirmed that the backend is returning a range of bytes using StreamingResponseBody (I'm using spring boot) via 206 response code

2.) Confirmed that the received data makes sense, I think, by comparing the logs displayed here chrome://media-internals/ with the logs displayed when I play any YouTube video. I attached some pictures to show this.

3.) On the frontend, byte stream gets converted into an arrayBuffer via response.arrayBuffer()

4.) Confirmed that the video's codec profile is video/mp4; codecs="avc1.64002a,mp4a.40.2"; profiles="mp42,mp41" . Used mp4box (https://github.com/gpac/mp4box.js) to get the codec and profile and confirmed that the browser supports this MediaSource.isTypeSupported('video/mp4; codecs="avc1.64002a"; profiles="mp42,mp41"'); I'm using google chrome to test this.

Issue:

1.) It looks like buffered isn't getting updated, because it's TimeRange length is not changing and that sourceBuffer.buffered.end(0) and sourceBuffer.buffered.start(0) remains undefined

2.) And because of the previous issue, <video /> doesn't play.

Using a callback getVideoStreamResourceAPI to receive the arrayBuffer, the following is my code

getVideoStreamResourceAPI(pathVariables, identityPayload, resp => {
                    const mediaSource = new MediaSource();
                    videoRef.current.src = URL.createObjectURL(mediaSource);
                    mediaSource.addEventListener('sourceopen', sourceOpen, {once: true});

                    function sourceOpen() {
                        URL.revokeObjectURL(videoRef.current.src);
                        var sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.64002a,mp4a.40.2"; profiles="mp42,mp41"');

                        sourceBuffer.addEventListener('update', sourceBufferUpdate, { once: true });
                        sourceBuffer.appendBuffer(resp);
                        sourceBuffer.addEventListener('updateend', updateEnd, { once: true });
                    }

                    function sourceBufferUpdate(e) {
                        console.log("updated: ", e);
                    }

                    function updateEnd(e) {
                        console.log("updatedEnded: ", e);
                        console.log("buffered: ", videoRef.current.buffered);
                        videoRef.current.addEventListener('playing', fetchNextSegment, { once: true });
                    }

                    function fetchNextSegment() {
                        console.log("fetching next segment");
                    }

                    setSpinner(null);
                });

NOTE:
resp contains the arrayBuffer and fetchNextSegment() isn't getting called.

Any suggestions, ideas, and help would be greatly appreciated. Thanks for taking the time to read this.


问:
MongoDB accessing array fields
As the title says I am trying to access an array field from a query. The query works fine and can both console log and returning it works fine but when I try to access it I get undefined. Here is how I access it:
Creation of a query

```<code>async getTrack(id, type: String) : Promise<Track[]> {
if(type=='id'){
    const query = this.trackModel.find(
    { id : id },
    {_id:0}
  ).limit(100);
return query;
}
if(type=='name'){
    const query = this.trackModel.find(
  { name : id },
  {_id:0}
).limit(100);
return query;
}
}

let json = await this.trackService.getTrack(id, type);
json[0].artist_name

console.log(json[0].artist_name)

console.log(json[0])
</code>```

The second console logs works fine while the first one fails and prints undefined.I have tried adding await inside as well as outside of the console.log to no avail as well as to try and put into string and nothing worked.

Title: MongoDB accessing array fields

Body:
As the title says I am trying to access an array field from a query. The query works fine and can both console log and returning it works fine but when I try to access it I get undefined. Here is how I access it:
Creation of a query

async getTrack(id, type: String) : Promise<Track[]> {
if(type=='id'){
    const query = this.trackModel.find(
    { id : id },
    {_id:0}
  ).limit(100);
return query;
}
if(type=='name'){
    const query = this.trackModel.find(
  { name : id },
  {_id:0}
).limit(100);
return query;
}
}

let json = await this.trackService.getTrack(id, type);
json[0].artist_name

console.log(json[0].artist_name)

console.log(json[0])

The second console logs works fine while the first one fails and prints undefined.I have tried adding await inside as well as outside of the console.log to no avail as well as to try and put into string and nothing worked.


问:
How can I pass a buffer, consisting of uniform arrays, from Three JS into the vertex shader?
I am using React, React Three Fiber

I have been passing along uniforms from javascript in the following way:

```<code>  const uniforms = useMemo(() => ({

    uTime: {
      value: 0.0
    },
    uRadius: {
      value: radius
    },
    uPointSizes: {
      value: pointSizes
    },
    uRandomValuesX: {
      value: randomValuesX
    },
    uRandomValuesY: {
      value: randomValuesY
    },
    uRandomValuesZ: {
      value: randomValuesZ
    },
    uResolutionWidth: {
      value: screen.width
    },
    uResolutionHeight: {
      value: screen.height
    }

  }), [])

...

      <points ref={gPoints}>
        <bufferGeometry attach="geometry">
            <bufferAttribute
                attach="attributes-position"
                count={positions.length / 3}
                array={positions}
                itemSize={3}
                usage={THREE.DynamicDrawUsage}
            />
        </bufferGeometry>
        <shaderMaterial
            depthWrite={false}
            fragmentShader={fragmentShader}
            vertexShader={vertexShader}
            uniforms={uniforms}
            blending={THREE.AdditiveBlending}
        />
      </points>
</code>```

And below is how I imported the uniforms in the vertex shader section:

```<code>const vertexShader = `
#define PI 3.14159265358979323846

uniform float uTime;
uniform float uPointSizes[1000];
uniform float uRandomValuesX[1000];
uniform float uRandomValuesY[1000];
uniform float uRandomValuesZ[1000];
uniform float uRadius;
</code>```

I have hit a problem though where the max amount of uniforms I can pass over is 4095. I want to pass over large float arrays, I have read in other places that I need to pass along several buffers, because each buffer also has a maximum size. So if I have 4 arrays and each is 10,000 in length I would want to pass along 4 buffers? Any help is appreciated, thank you!

Body:
I am using React, React Three Fiber

I have been passing along uniforms from javascript in the following way:

  const uniforms = useMemo(() => ({

    uTime: {
      value: 0.0
    },
    uRadius: {
      value: radius
    },
    uPointSizes: {
      value: pointSizes
    },
    uRandomValuesX: {
      value: randomValuesX
    },
    uRandomValuesY: {
      value: randomValuesY
    },
    uRandomValuesZ: {
      value: randomValuesZ
    },
    uResolutionWidth: {
      value: screen.width
    },
    uResolutionHeight: {
      value: screen.height
    }

  }), [])

...

      <points ref={gPoints}>
        <bufferGeometry attach="geometry">
            <bufferAttribute
                attach="attributes-position"
                count={positions.length / 3}
                array={positions}
                itemSize={3}
                usage={THREE.DynamicDrawUsage}
            />
        </bufferGeometry>
        <shaderMaterial
            depthWrite={false}
            fragmentShader={fragmentShader}
            vertexShader={vertexShader}
            uniforms={uniforms}
            blending={THREE.AdditiveBlending}
        />
      </points>

And below is how I imported the uniforms in the vertex shader section:

const vertexShader = `
#define PI 3.14159265358979323846

uniform float uTime;
uniform float uPointSizes[1000];
uniform float uRandomValuesX[1000];
uniform float uRandomValuesY[1000];
uniform float uRandomValuesZ[1000];
uniform float uRadius;

I have hit a problem though where the max amount of uniforms I can pass over is 4095. I want to pass over large float arrays, I have read in other places that I need to pass along several buffers, because each buffer also has a maximum size. So if I have 4 arrays and each is 10,000 in length I would want to pass along 4 buffers? Any help is appreciated, thank you!


问:
How do I send the outputs of one program to another program so it can execute accordingly
I want to use my e-guitar as a controller for a game so I came up with the Idea to use the pitch that gets picked up by a recording software to simulate pressing a key

for example: if int(pitch) = 150hz
keyboard.press(a)

but I don't know how to make my program read what the recording software displays. How can I make my program read what is displays. I would rather use python than any C language because I understand Python better

i tried making the recording program write a the pitch on a notepad that my program has access to but for some reason i just got no results on the notepad or in the Python console


问:
APIs for redirecting to live TV channels of sonyliv, zee5, voot, and other OTT apps?
I am trying to search for any APIs or deep links that can allow me to redirect to specific live TV channels in the OTT apps like Sonyliv, Zee5, Voot, etc.

Any help is appreciated

This is still a new topic and couldn't find information


Title: Leaflet Countries JSON Collection


问:
Kivy kv creating toolbar with active buttons which change window when pressed
Basically I've created a toolbar with two widgets. One widget (account) should change to a new window when pressed. The other (menu) should open three buttons when it is pressed. When you press on of the three buttons it should also change to a new window.

I don't know how to implement that...
Can anyone help me?

Here's my code:

kv = """

<MenuScreen>:
    name: 'mainmenu'
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'background.jpg'

    Screen:
        BoxLayout:
            orientation: 'vertical'
            MDTopAppBar:
                title: 'Fitness App'
                left_action_items: [["menu", lambda x: app.navigation_draw()]]
                right_action_items: [["account", lambda x: app.callback()]]
                elevation:5

            MDLabel:
                text: 'hello world'
                halign: 'center'

    BoxLayout:
        spacing: 1
        orientation: "vertical"

        Label:
            text: "Welcome back"
            font_size: 100
            color : 0,0,0,1

        Button:
            text: 'Get Started'
            font_size:100
            color: 0, 0, 1, 1
            background_color: 0, 0, 0, 1
            size_hint: 1, 1
            pos_hint: {"x":0, "top":1}
            on_release:
                root.manager.current = 'screen2'
                root.manager.transition.direction = "left"

        Button:
            text: 'Leave App'
            font_size: 100
            color: 0, 0, 1, 1
            background_color: 0, 0, 0, 1
            size_hint: 1, 1
            pos_hint: {"x":0, "top":0}
            on_release: root.manager.current = app.exit_software()

<Screen2>:
    name: 'screen2'
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'background.jpg'
    BoxLayout:
        spacing: 1
        orientation: "vertical"

        ScrollView:
            id: scroll_view
            always_overscroll: False
            BoxLayout:
                size_hint_y: None
                height: self.minimum_height
                orientation: 'vertical'
                Label:
                    id: label
                    text: "Please choose your problem Area"
                    color : 0,0,0,1
                    size_hint: None, None
                    pos_hint: {"x":0, "top":1}
                    font_size: 50
                    size: self.texture_size

        Button:
            text: 'Shoulders'
            font_size: 30
            color : 0,0,1,1

            on_release:
                root.manager.current = 'shoulders'
                root.manager.transition.direction = "left"

        Button:
            text: 'Knees'
            font_size: 30
            color : 0,0,1,1
            background_color: 0, 0, 0, 1
            size_hint_y: 1
            on_release:
                root.manager.current = 'knees'
                root.manager.transition.direction = "left"

        Button:
            text: 'Back'
            font_size: 30
            color : 0,0,1,1
            background_color: 0, 0, 0, 1
            size_hint_y: 1
            on_release:
                root.manager.current = 'back'
                root.manager.transition.direction = "left"

        Button:
            text: 'Back to main menu'
            font_size: 30
            color : 0,0,1,1
            background_color: 0, 0, 0, 1
            size_hint_y: 1
            on_release:
                root.manager.current = 'mainmenu'
                root.manager.transition.direction = "right"

<Screen_shoulders>:
    name: 'shoulders'

    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'shoulders.png'

    BoxLayout:
        spacing: 1
        orientation: "vertical"

        ScrollView:
            id: scroll_view
            always_overscroll: False
            BoxLayout:
                size_hint_y: None
                height: self.minimum_height
                orientation: 'vertical'
                Label:
                    id: label
                    text: "Choose an activity"
                    font_size: 50
                    color : 0,0,0,1

                    size: self.texture_size
        Button:
            text: 'Activity1'
            font_size: 50
            color : 0,0,0,1
            size_hint_y: 0.3
            on_release:
                root.manager.current = 'shouldersActivity1'
                root.manager.transition.direction = "right"

        Button:
            text: 'Activity2'
            font_size: 50
            color : 0,0,0,1
            size_hint_y: 0.3
            on_release: app.add_text()

        Button:
            text: 'Back to main menu'
            font_size: 20
            color : 0,0,0,1
            size_hint_y: 0.1
            on_release:
                root.manager.current = 'screen2'
                root.manager.transition.direction = "right"

ScreenManager:
    id: screen_manager

    MenuScreen:
        id: menu_scr

    Screen2:
        id: scr_2

"""

class MenuScreen(Screen):
    pass

class Screen2(Screen):
    pass

class AddTextApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def build(self):
        return Builder.load_string(kv)

    def add_text(self):
        self.root.ids.scr_2.ids.label.text += f"Some new Text\n"
        self.root.ids.scr_2.ids.scroll_view.scroll_y = 0

    def callback(self, instance_action_top_appbar_button):
        print(instance_action_top_appbar_button)

    @staticmethod
    def exit_software():
        App.get_running_app().stop()

    def navigation_draw(self):

    # open new window

    def callback(self):

    # open new window

if __name__ == '__main__':
    AddTextApp().run()
```

I don't know how to make the widgets change window when they're pressed.

Body:
Basically I've created a toolbar with two widgets. One widget (account) should change to a new window when pressed. The other (menu) should open three buttons when it is pressed. When you press on of the three buttons it should also change to a new window.

I don't know how to implement that...
Can anyone help me?

Here's my code:

kv = """

<MenuScreen>:
    name: 'mainmenu'
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'background.jpg'

    Screen:
        BoxLayout:
            orientation: 'vertical'
            MDTopAppBar:
                title: 'Fitness App'
                left_action_items: [["menu", lambda x: app.navigation_draw()]]
                right_action_items: [["account", lambda x: app.callback()]]
                elevation:5

            MDLabel:
                text: 'hello world'
                halign: 'center'

    BoxLayout:
        spacing: 1
        orientation: "vertical"

        Label:
            text: "Welcome back"
            font_size: 100
            color : 0,0,0,1

        Button:
            text: 'Get Started'
            font_size:100
            color: 0, 0, 1, 1
            background_color: 0, 0, 0, 1
            size_hint: 1, 1
            pos_hint: {"x":0, "top":1}
            on_release:
                root.manager.current = 'screen2'
                root.manager.transition.direction = "left"

        Button:
            text: 'Leave App'
            font_size: 100
            color: 0, 0, 1, 1
            background_color: 0, 0, 0, 1
            size_hint: 1, 1
            pos_hint: {"x":0, "top":0}
            on_release: root.manager.current = app.exit_software()

<Screen2>:
    name: 'screen2'
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'background.jpg'
    BoxLayout:
        spacing: 1
        orientation: "vertical"

        ScrollView:
            id: scroll_view
            always_overscroll: False
            BoxLayout:
                size_hint_y: None
                height: self.minimum_height
                orientation: 'vertical'
                Label:
                    id: label
                    text: "Please choose your problem Area"
                    color : 0,0,0,1
                    size_hint: None, None
                    pos_hint: {"x":0, "top":1}
                    font_size: 50
                    size: self.texture_size

        Button:
            text: 'Shoulders'
            font_size: 30
            color : 0,0,1,1

            on_release:
                root.manager.current = 'shoulders'
                root.manager.transition.direction = "left"

        Button:
            text: 'Knees'
            font_size: 30
            color : 0,0,1,1
            background_color: 0, 0, 0, 1
            size_hint_y: 1
            on_release:
                root.manager.current = 'knees'
                root.manager.transition.direction = "left"

        Button:
            text: 'Back'
            font_size: 30
            color : 0,0,1,1
            background_color: 0, 0, 0, 1
            size_hint_y: 1
            on_release:
                root.manager.current = 'back'
                root.manager.transition.direction = "left"

        Button:
            text: 'Back to main menu'
            font_size: 30
            color : 0,0,1,1
            background_color: 0, 0, 0, 1
            size_hint_y: 1
            on_release:
                root.manager.current = 'mainmenu'
                root.manager.transition.direction = "right"

<Screen_shoulders>:
    name: 'shoulders'

    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'shoulders.png'

    BoxLayout:
        spacing: 1
        orientation: "vertical"

        ScrollView:
            id: scroll_view
            always_overscroll: False
            BoxLayout:
                size_hint_y: None
                height: self.minimum_height
                orientation: 'vertical'
                Label:
                    id: label
                    text: "Choose an activity"
                    font_size: 50
                    color : 0,0,0,1

                    size: self.texture_size
        Button:
            text: 'Activity1'
            font_size: 50
            color : 0,0,0,1
            size_hint_y: 0.3
            on_release:
                root.manager.current = 'shouldersActivity1'
                root.manager.transition.direction = "right"

        Button:
            text: 'Activity2'
            font_size: 50
            color : 0,0,0,1
            size_hint_y: 0.3
            on_release: app.add_text()

        Button:
            text: 'Back to main menu'
            font_size: 20
            color : 0,0,0,1
            size_hint_y: 0.1
            on_release:
                root.manager.current = 'screen2'
                root.manager.transition.direction = "right"

ScreenManager:
    id: screen_manager

    MenuScreen:
        id: menu_scr

    Screen2:
        id: scr_2

"""

class MenuScreen(Screen):
    pass

class Screen2(Screen):
    pass

class AddTextApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def build(self):
        return Builder.load_string(kv)

    def add_text(self):
        self.root.ids.scr_2.ids.label.text += f"Some new Text\n"
        self.root.ids.scr_2.ids.scroll_view.scroll_y = 0

    def callback(self, instance_action_top_appbar_button):
        print(instance_action_top_appbar_button)

    @staticmethod
    def exit_software():
        App.get_running_app().stop()

    def navigation_draw(self):

    # open new window

    def callback(self):

    # open new window

if __name__ == '__main__':
    AddTextApp().run()

I don't know how to make the widgets change window when they're pressed.


问:
Exporting text from cells to separate txt files
I'm trying to export the content of each cell on a Column to single txt files. I'm using this code but I get a

run-time error '76': Path not found.

And it points to the line Open FileName For Output As #1

I'm working on a Mac and I granted disk permissions to Excel, and I enabled the macros after a warning. What am I doing wrong? Any help would be appreciate it.

I tried this:

```<code>Sub ExportToText()
Dim cell As Range
Dim outputFolder As String
outputFolder = "\~/Desktop/textexport"
For Each cell In Worksheets("Sheet1").Range("A1:A13")
Dim FileName As String
FileName = outputFolder & "/" & cell.Address & ".txt"
Open FileName For Output As #1
Print #1, cell.Value
Close #1
Next cell
End Sub
</code>```

Body:
I'm trying to export the content of each cell on a Column to single txt files. I'm using this code but I get a

run-time error '76': Path not found.

And it points to the line Open FileName For Output As #1

I'm working on a Mac and I granted disk permissions to Excel, and I enabled the macros after a warning. What am I doing wrong? Any help would be appreciate it.

I tried this:

Sub ExportToText()
Dim cell As Range
Dim outputFolder As String
outputFolder = "\~/Desktop/textexport"
For Each cell In Worksheets("Sheet1").Range("A1:A13")
Dim FileName As String
FileName = outputFolder & "/" & cell.Address & ".txt"
Open FileName For Output As #1
Print #1, cell.Value
Close #1
Next cell
End Sub


问:
PHP Warning: Cannot modify header information - headers already sent in
having difficulty trying to change the code below for PHP 8.0 which has the above error message:

```<code>    public function sendNoCacheHeaders()
{
    header_remove('Last-Modified');
    header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
    header('Cache-Control: no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
}
</code>```

}

Body:
having difficulty trying to change the code below for PHP 8.0 which has the above error message:

    public function sendNoCacheHeaders()
{
    header_remove('Last-Modified');
    header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
    header('Cache-Control: no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
}

}