问:
'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
Hi experts I am new to android studio and currently watching tutorials. Right now I encountered

'java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference

error even after following the tutorial. I've also searched for same issue and found that this can be solved by initializing the recyclerview and providing the right layout name. I'm pretty sure I've met both solution but I am still facing the same issue. Please guide me on this.

MainActivity.java

package com.example.cart;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.SearchView;

import com.example.cart.adapter.MyProductAdapter;
import com.example.cart.listener.CartLoadListener;
import com.example.cart.listener.ProductLoadListener;
import com.example.cart.model.CartModel;
import com.example.cart.model.ProductModel;
import com.example.cart.utils.SpaceItemDecoration;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nex3z.notificationbadge.NotificationBadge;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements ProductLoadListener, CartLoadListener {
    @BindView(R.id.rv)
    RecyclerView rviewer;
    @BindView(R.id.mainLayout)
    RelativeLayout mainLayout;
    @BindView(R.id.badge)
    NotificationBadge badge;
    @BindView(R.id.btnCart)
    FrameLayout btnCart;
    @BindView(R.id.search)
    SearchView search;

    ProductLoadListener productLoadListener;
    CartLoadListener cartLoadListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        loadProductFromFirebase();
    }

    private void loadProductFromFirebase() {
        List<ProductModel> productModels = new ArrayList<>();
        FirebaseDatabase.getInstance()
                .getReference("product")
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if(snapshot.exists()) {
                            for(DataSnapshot productSnapshot:snapshot.getChildren()){
                                ProductModel productModel = productSnapshot.getValue(ProductModel.class);
                                productModel.setKey(productSnapshot.getKey());
                                productModels.add(productModel);

                            }
                            productLoadListener.onProductLoadSuccess(productModels);
                        } else {
                            productLoadListener.onProductLoadFail("Can't Find Product");
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        productLoadListener.onProductLoadFail(error.getMessage());
                    }
                });
    }

    private void init() {
        ButterKnife.bind(this);

        productLoadListener = this;
        cartLoadListener = this;

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        rviewer.setLayoutManager(gridLayoutManager);
        rviewer.addItemDecoration(new SpaceItemDecoration());
    }

    @Override
    public void onProductLoadSuccess(List<ProductModel> productModelList) {
        MyProductAdapter adapter = new MyProductAdapter(this, productModelList);
        rviewer.setAdapter(adapter);
    }

    @Override
    public void onProductLoadFail(String message) {
        Snackbar.make(mainLayout, message, Snackbar.LENGTH_LONG).show();
    }

    @Override
    public void onCartLoadSuccess(List<CartModel> cartModelList) {

    }

    @Override
    public void onCartLoadFail(String message) {

    }
}
```
<p><strong>MyProductAdapter.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package com.example.cart.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.cart.R;
import com.example.cart.model.ProductModel;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MyProductAdapter extends RecyclerView.Adapter<MyProductAdapter.MyProductViewHolder> {

    private Context context;
    private List<ProductModel> productModelList;

    public MyProductAdapter(Context context, List<ProductModel> productModelList) {
        this.context = context;
        this.productModelList = productModelList;
    }

    @NonNull
    @Override
    public MyProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyProductViewHolder(LayoutInflater.from(context)
                .inflate(R.layout.product_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyProductViewHolder holder, int position) {
        Glide.with(context)
                .load(productModelList.get(position).getImage())
                .into(holder.img1);
        holder.productPrice.setText(new StringBuilder("$").append(productModelList.get(position).getPrice()));
        holder.productName.setText(new StringBuilder().append(productModelList.get(position).getName()));
        holder.productDescription.setText(new StringBuilder().append(productModelList.get(position).getDescription()));
    }

    @Override
    public int getItemCount() {
        return productModelList.size();
    }

    public class MyProductViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.img1)
        RoundedImageView img1;
        @BindView(R.id.productName)
        TextView productName;
        @BindView(R.id.productDescription)
        TextView productDescription;
        @BindView(R.id.productPrice)
        TextView productPrice;

        private Unbinder unbinder;

        public MyProductViewHolder(@NonNull View itemView) {
            super(itemView);
            unbinder = ButterKnife.bind(this, itemView);
        }
    }
}

</code>```

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#3BE838"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/searchCartLayout"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:orientation="horizontal"
        android:weightSum="16"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0">

        <TextView
            android:id="@+id/search"
            android:layout_width="0dp"
            android:layout_weight="11"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="center"
            android:textStyle="bold"
            android:textSize="30sp"/>

        <androidx.appcompat.widget.SearchView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="start|center_vertical"
            android:layout_weight="2"
            android:src="@drawable/ic_baseline_search_24"/>

        <FrameLayout
            android:id="@+id/btnCart"
            android:layout_width="0dp"
            android:layout_weight="3"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/cartButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:src="@drawable/ic_baseline_shopping_cart_24" />

            <com.nex3z.notificationbadge.NotificationBadge
                android:id="@+id/badge"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginLeft="10dp"
                app:nbMaxTextLength="2"/>
        </FrameLayout>

    </LinearLayout>

    <TextView
        android:id="@+id/breadCrumb"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:background="@drawable/rounded_corner_view"
        android:padding="2dp"
        android:text="  App/Page name : Products / Services"
        app:layout_constraintBottom_toTopOf="@id/rv"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.6" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="750dp"
            android:gravity="center"
            android:orientation="vertical"
            app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@id/breadCrumb"
            app:layout_constraintVertical_bias="1.0" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1"
        app:menu="@menu/bottom_nav_menu" />

</RelativeLayout>
```

Body:
Hi experts I am new to android studio and currently watching tutorials. Right now I encountered

'java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference

error even after following the tutorial. I've also searched for same issue and found that this can be solved by initializing the recyclerview and providing the right layout name. I'm pretty sure I've met both solution but I am still facing the same issue. Please guide me on this.

MainActivity.java

package com.example.cart;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.SearchView;

import com.example.cart.adapter.MyProductAdapter;
import com.example.cart.listener.CartLoadListener;
import com.example.cart.listener.ProductLoadListener;
import com.example.cart.model.CartModel;
import com.example.cart.model.ProductModel;
import com.example.cart.utils.SpaceItemDecoration;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nex3z.notificationbadge.NotificationBadge;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements ProductLoadListener, CartLoadListener {
    @BindView(R.id.rv)
    RecyclerView rviewer;
    @BindView(R.id.mainLayout)
    RelativeLayout mainLayout;
    @BindView(R.id.badge)
    NotificationBadge badge;
    @BindView(R.id.btnCart)
    FrameLayout btnCart;
    @BindView(R.id.search)
    SearchView search;

    ProductLoadListener productLoadListener;
    CartLoadListener cartLoadListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        loadProductFromFirebase();
    }

    private void loadProductFromFirebase() {
        List<ProductModel> productModels = new ArrayList<>();
        FirebaseDatabase.getInstance()
                .getReference("product")
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        if(snapshot.exists()) {
                            for(DataSnapshot productSnapshot:snapshot.getChildren()){
                                ProductModel productModel = productSnapshot.getValue(ProductModel.class);
                                productModel.setKey(productSnapshot.getKey());
                                productModels.add(productModel);

                            }
                            productLoadListener.onProductLoadSuccess(productModels);
                        } else {
                            productLoadListener.onProductLoadFail("Can't Find Product");
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {
                        productLoadListener.onProductLoadFail(error.getMessage());
                    }
                });
    }

    private void init() {
        ButterKnife.bind(this);

        productLoadListener = this;
        cartLoadListener = this;

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        rviewer.setLayoutManager(gridLayoutManager);
        rviewer.addItemDecoration(new SpaceItemDecoration());
    }

    @Override
    public void onProductLoadSuccess(List<ProductModel> productModelList) {
        MyProductAdapter adapter = new MyProductAdapter(this, productModelList);
        rviewer.setAdapter(adapter);
    }

    @Override
    public void onProductLoadFail(String message) {
        Snackbar.make(mainLayout, message, Snackbar.LENGTH_LONG).show();
    }

    @Override
    public void onCartLoadSuccess(List<CartModel> cartModelList) {

    }

    @Override
    public void onCartLoadFail(String message) {

    }
}

MyProductAdapter.java

package com.example.cart.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.cart.R;
import com.example.cart.model.ProductModel;
import com.makeramen.roundedimageview.RoundedImageView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MyProductAdapter extends RecyclerView.Adapter<MyProductAdapter.MyProductViewHolder> {

    private Context context;
    private List<ProductModel> productModelList;

    public MyProductAdapter(Context context, List<ProductModel> productModelList) {
        this.context = context;
        this.productModelList = productModelList;
    }

    @NonNull
    @Override
    public MyProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyProductViewHolder(LayoutInflater.from(context)
                .inflate(R.layout.product_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyProductViewHolder holder, int position) {
        Glide.with(context)
                .load(productModelList.get(position).getImage())
                .into(holder.img1);
        holder.productPrice.setText(new StringBuilder("$").append(productModelList.get(position).getPrice()));
        holder.productName.setText(new StringBuilder().append(productModelList.get(position).getName()));
        holder.productDescription.setText(new StringBuilder().append(productModelList.get(position).getDescription()));
    }

    @Override
    public int getItemCount() {
        return productModelList.size();
    }

    public class MyProductViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.img1)
        RoundedImageView img1;
        @BindView(R.id.productName)
        TextView productName;
        @BindView(R.id.productDescription)
        TextView productDescription;
        @BindView(R.id.productPrice)
        TextView productPrice;

        private Unbinder unbinder;

        public MyProductViewHolder(@NonNull View itemView) {
            super(itemView);
            unbinder = ButterKnife.bind(this, itemView);
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#3BE838"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/searchCartLayout"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:orientation="horizontal"
        android:weightSum="16"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0">

        <TextView
            android:id="@+id/search"
            android:layout_width="0dp"
            android:layout_weight="11"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:gravity="center"
            android:textStyle="bold"
            android:textSize="30sp"/>

        <androidx.appcompat.widget.SearchView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="start|center_vertical"
            android:layout_weight="2"
            android:src="@drawable/ic_baseline_search_24"/>

        <FrameLayout
            android:id="@+id/btnCart"
            android:layout_width="0dp"
            android:layout_weight="3"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/cartButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:src="@drawable/ic_baseline_shopping_cart_24" />

            <com.nex3z.notificationbadge.NotificationBadge
                android:id="@+id/badge"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:layout_marginLeft="10dp"
                app:nbMaxTextLength="2"/>
        </FrameLayout>

    </LinearLayout>

    <TextView
        android:id="@+id/breadCrumb"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:background="@drawable/rounded_corner_view"
        android:padding="2dp"
        android:text="  App/Page name : Products / Services"
        app:layout_constraintBottom_toTopOf="@id/rv"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.6" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="750dp"
            android:gravity="center"
            android:orientation="vertical"
            app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@id/breadCrumb"
            app:layout_constraintVertical_bias="1.0" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigationView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1"
        app:menu="@menu/bottom_nav_menu" />

</RelativeLayout>


来源: stackexchange

问:
Is possible to combine tobit and ridge in one model?
I wonder if it is possible to combine tobit and ridge in one model specification in R. I have read some papers about that possible combination, but I don't know if it is possible in R or if there is already a library or someway to combine existing functions/libraries.</p>

ContentLicense: CC BY-SA 4.0


问:
Python formatting bytes in csv writer
I've written a script that captures three data elements from a bus every 10 seconds and writes them to a csv file with date and time. The elements are flow_temp, return_temp and flame. The first two are floating point numbers and flame is bytes. The possible values of flame are 'on' and 'off' and I'm having trouble formatting the output. Here is the code:

```<code>from subprocess import check_output
import csv
from datetime import datetime
import threading

cmd = ['/usr/bin/ebusctl', 'read', '-f']
header = ['Date','Time','Flow','Return','Flame']

with open('sandbox.csv', 'w', newline = '') as f:
    writer = csv.writer(f)
    writer.writerow(header)

def read_ebus():
  threading.Timer(10.0, read_ebus).start()

  date = datetime.today().strftime('%Y-%m-%d')
  time = datetime.today().strftime('%H:%M:%S')
  flow_temp =  float(check_output([*cmd, 'FlowTemp', 'temp']))
  return_temp =  float(check_output([*cmd, 'ReturnTemp', 'temp']))
  flame =  check_output([*cmd, 'Flame'])

  data = [date,time,flow_temp,return_temp,flame]

  with open('sandbox.csv', 'a', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(data)
read_ebus()

</code>```

And here is the output when flame = on:

```<code>Date,Time,Flow,Return,Flame
2022-12-05,19:55:42,69.0,56.56,b'on\n\n'
2022-12-05,19:55:52,69.0,56.56,b'on\n\n'

</code>```

I tried defining flame as a string:

```<code>flame =  str(check_output([*cmd, 'Flame']), encoding = 'utf-8')

</code>```

This gives me:

```<code>Date,Time,Flow,Return,Flame
2022-12-05,20:05:26,69.0,58.19,"on

"
2022-12-05,20:05:36,69.0,58.19,"on

"
</code>```

How can I adjust the code so that flame appears as 'on' or 'off' in the csv file with no spaces between the lines?

Thanks,

Mike

Title: Python formatting bytes in csv writer

Body:
I've written a script that captures three data elements from a bus every 10 seconds and writes them to a csv file with date and time. The elements are flow_temp, return_temp and flame. The first two are floating point numbers and flame is bytes. The possible values of flame are 'on' and 'off' and I'm having trouble formatting the output. Here is the code:

from subprocess import check_output
import csv
from datetime import datetime
import threading

cmd = ['/usr/bin/ebusctl', 'read', '-f']
header = ['Date','Time','Flow','Return','Flame']

with open('sandbox.csv', 'w', newline = '') as f:
    writer = csv.writer(f)
    writer.writerow(header)

def read_ebus():
  threading.Timer(10.0, read_ebus).start()

  date = datetime.today().strftime('%Y-%m-%d')
  time = datetime.today().strftime('%H:%M:%S')
  flow_temp =  float(check_output([*cmd, 'FlowTemp', 'temp']))
  return_temp =  float(check_output([*cmd, 'ReturnTemp', 'temp']))
  flame =  check_output([*cmd, 'Flame'])

  data = [date,time,flow_temp,return_temp,flame]

  with open('sandbox.csv', 'a', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(data)
read_ebus()

And here is the output when flame = on:

Date,Time,Flow,Return,Flame
2022-12-05,19:55:42,69.0,56.56,b'on\n\n'
2022-12-05,19:55:52,69.0,56.56,b'on\n\n'

I tried defining flame as a string:

flame =  str(check_output([*cmd, 'Flame']), encoding = 'utf-8')

This gives me:

Date,Time,Flow,Return,Flame
2022-12-05,20:05:26,69.0,58.19,"on

"
2022-12-05,20:05:36,69.0,58.19,"on

"

How can I adjust the code so that flame appears as 'on' or 'off' in the csv file with no spaces between the lines?

Thanks,

Mike


问:
Python Function to return upcoming birthyear using birth date and birth month
I am writing a program which will print the upcoming birth year by using birth date and birth month.
The problem is the condition related to leap year.

I have wrote this python function but I am not sure if it is totally correct.

There maybe some test case dates which might fail it.

```<code>from calendar import isleap

currentDate = 29
currentMonth = 2
currentyear = 2024

def nextLeap(year):
    while True:
        year += 1
        if isleap(year) == True:
            break
    return year

def nextpcurLeap(year):
    if isleap(year) == False:
        return nextLeap(year)
    else:
        return year

def findYear(date,month):
    year = currentyear
    if month < currentMonth:
        if date == 29 and month == 2:
            year = nextLeap(year)
        else:
            year = year+1
    elif month == currentMonth:
        if date <= currentDate:
            if date == 29 and month == 2:
                year = nextLeap(year)
            else :
                year += 1
        else:
            if date == 29 and month == 2:
                year = nextpcurLeap(year)
            else:
                if date <= currentDate:
                    year = year+1
    return year

print(findYear(29, 2))

</code>```

Even if there are no test cases that fail the program... I am expecting to have a better and small approach.. I don't know if it is possible using any python library. If so I a glad to know.

Body:
I am writing a program which will print the upcoming birth year by using birth date and birth month.
The problem is the condition related to leap year.

I have wrote this python function but I am not sure if it is totally correct.

There maybe some test case dates which might fail it.

from calendar import isleap

currentDate = 29
currentMonth = 2
currentyear = 2024

def nextLeap(year):
    while True:
        year += 1
        if isleap(year) == True:
            break
    return year

def nextpcurLeap(year):
    if isleap(year) == False:
        return nextLeap(year)
    else:
        return year

def findYear(date,month):
    year = currentyear
    if month < currentMonth:
        if date == 29 and month == 2:
            year = nextLeap(year)
        else:
            year = year+1
    elif month == currentMonth:
        if date <= currentDate:
            if date == 29 and month == 2:
                year = nextLeap(year)
            else :
                year += 1
        else:
            if date == 29 and month == 2:
                year = nextpcurLeap(year)
            else:
                if date <= currentDate:
                    year = year+1
    return year

print(findYear(29, 2))

Even if there are no test cases that fail the program... I am expecting to have a better and small approach.. I don't know if it is possible using any python library. If so I a glad to know.


问:
split_on_silence values for detect breathing
I want to split a monolog parliement speech to segments sepereted by speeker's breeth. What are the suitable
values for min_silence_len and silence_thresh? Thank you!

I entered these values-
audio_chunks = split_on_silence(sound, min_silence_len=250, silence_thresh=-40)
I wonder if there are suitable.


问:
DeepFace verify giving a 'can only concatenate str (not "list") to str' error
I am using DeepFace Verify, however I seem to be always getting a  'can only concatenate str (not "list") to str' error, I am following this github tutorial exactly.

```<code>df.file_x = "D:/AI_FACIAL/QUERY/"+df.file_x
df.file_y = "D:/AI_FACIAL/frames/"+df.file_y
instances = df[["file_x", "file_y"]].values.tolist()
resp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, detector_backend ='retinaface')

</code>```

Error on:

```<code>
  File "D:\Anaconda\lib\site-packages\pandas\core\roperator.py", line 9, in radd
    return right + left

TypeError: can only concatenate str (not "list") to str
</code>```

I do not know what else I could provide to clarify this problem, any help is appreciated. Please ask if theres anything that needs clarification.

Body:
I am using DeepFace Verify, however I seem to be always getting a  'can only concatenate str (not "list") to str' error, I am following this github tutorial exactly.

df.file_x = "D:/AI_FACIAL/QUERY/"+df.file_x
df.file_y = "D:/AI_FACIAL/frames/"+df.file_y
instances = df[["file_x", "file_y"]].values.tolist()
resp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, detector_backend ='retinaface')

Error on:

  File "D:\Anaconda\lib\site-packages\pandas\core\roperator.py", line 9, in radd
    return right + left

TypeError: can only concatenate str (not "list") to str

I do not know what else I could provide to clarify this problem, any help is appreciated. Please ask if theres anything that needs clarification.


问:
Using HTML user input as a JavaScript variable
I am trying to write a simple JavaScript function which should do the following:

User enters a number in a HTML input field

When the submit button is clicked, A JavaScript function alerts the user input on the screen.

For some reason the code does not run.

function calcGuess() {
  var value = document.getElementById('userValue').value;
  alert(value);
}

document.getElementById("subButton").onclick = calcGuess();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='wrapper'>
  <form id='userInput'>
    <label id='numLabel' for='userValue'>Enter a Number:</label>
    <input id='userValue' type='number'></input>
    <button id='subButton' type='button'>Enter</button>
  </form>
</div></code>```

Body:
I am trying to write a simple JavaScript function which should do the following:

User enters a number in a HTML input field

When the submit button is clicked, A JavaScript function alerts the user input on the screen.

For some reason the code does not run.

function calcGuess() {
  var value = document.getElementById('userValue').value;
  alert(value);
}

document.getElementById("subButton").onclick = calcGuess();

  <form id='userInput'>
    Enter a Number:
    <input id='userValue' type='number'></input>
    <button id='subButton' type='button'>Enter</button>
  </form>


问:
Float point placement with anti aliasing
Copy from here for larger exposure:

I have an image of size H,W, and I would like to draw a point on this image at (x,y), where those values are floats.
I tried bi-linear interpretation but that didn't give satisfactory results (smeared each pixel on 4 pixel according to the floating point weight), but when I generated a hi-res image (e.g. of size 4H,4W, and placed the point at (4x,4y)), and then downsampled it with AA filter (or just cv2.area), I got much better quality.
Is there a way to get the same results without generating the hi-res image?


问:
Glue dynamic frame on Docker local returns an error of Py4JJavaError('An error occurred while calling o766.getDynamicFrame.\n', JavaObject id=o767)
```<code>datasource11 = glueContext.create_dynamic_frame_from_options(
                          connection_type="s3",
                          connection_options={"paths": [raw_data_input_path],
                          "recurse": True},
                          format="parquet",
                          transformation_ctx="21_query")
</code>```

throws

Py4JJavaError('An error occurred while calling o766.getDynamicFrame.\n', JavaObject id=o767)

I'm running the glue 2.0 docker image locally, i've passed the aws profile as config.
within this script in glue container, i was able to fetch ssm params.

i used a random string in...
job.init("random_job_id", args) -> could this be the issue?

on my local terminal i was able to do aws s3 sync successfully for this s3 dir raw_data_input_path.

but on my glue container i'm not able to getobject on s3.. what permission could this be? and could it be relevant to this glueContext issue?

I'm able to make a gluecontext dynamic frame using dummy data.. wondering what to do here.

the same glue code as a job runs fine on UI

Body:
datasource11 = glueContext.create_dynamic_frame_from_options(
                          connection_type="s3",
                          connection_options={"paths": [raw_data_input_path],
                          "recurse": True},
                          format="parquet",
                          transformation_ctx="21_query")

throws

Py4JJavaError('An error occurred while calling o766.getDynamicFrame.\n', JavaObject id=o767)

I'm running the glue 2.0 docker image locally, i've passed the aws profile as config.
within this script in glue container, i was able to fetch ssm params.

i used a random string in...
job.init("random_job_id", args) -> could this be the issue?

on my local terminal i was able to do aws s3 sync successfully for this s3 dir raw_data_input_path.

but on my glue container i'm not able to getobject on s3.. what permission could this be? and could it be relevant to this glueContext issue?

I'm able to make a gluecontext dynamic frame using dummy data.. wondering what to do here.

the same glue code as a job runs fine on UI


问:
Grafana Alert migration (from Legacy to Unified-Alerting): How do I get/export alert-rules, contactPoints and policies in NEW format?
Edit: I also posted this question, which describes the problem in a much more concise manner. I feel I might be missing something basic, but I just don't know. Any help would be appreciated. Thanks.

Searching StackOverflow, I cam across this post, and I have a very similar problem:

I do have the older format of "notifiers" (in the same exact format of Atom 7k, in above post). However, it looks like in the new way (Unified Alerting), the content and format of contactPoints is different from "notifiers" (For example, in "contactPoints", there is a receivers key, where there is no such key in "notifiers"). Same goes with alert-rules, meaning the format of alert-rules in new way (i.e. Unified Alerting), is different from Legacy format.

So, my question is how do I convert the old format to new? (or get the new format perhaps from API or something)?

I'm using HTTP API to get the contactPoints (api/v1/provisioning/contact-points), and rules (api/ruler/grafana/api/v1/rules/), but they are still in the old format. How can I get/export my alert-rules and contactPoints in new format? It's not practical to convert them from old to new by hand manually. The reason I need the new format, is so I can use provision my alerting resources using file-provisioning. Apparently (I tested), provisioning fails if I use old format, but succeeds with new format, naturally.

I saw this post too, but as I mentioned the API gives me the "old" definitions. I feel I'm missing something, but don't know what exactly.

I'm using Grafana V9.x, and I'm using following setting for migration (migrating from V7.x):

```<code>[alerting]
enabled = false
[unified alerting]
enabled = true
</code>```

I do see alert-rules and contactPoints being populated in Grafana UI as expected. Next, following this post. in step 2, what I get back from API is the "old" content/format, which apparently I can't use for provisioning. How can I get back my alert-rules, contactPoints, etc... in new format, so I can use it for provisioning?

Body:
Edit: I also posted this question, which describes the problem in a much more concise manner. I feel I might be missing something basic, but I just don't know. Any help would be appreciated. Thanks.

Searching StackOverflow, I cam across this post, and I have a very similar problem:

I do have the older format of "notifiers" (in the same exact format of Atom 7k, in above post). However, it looks like in the new way (Unified Alerting), the content and format of contactPoints is different from "notifiers" (For example, in "contactPoints", there is a receivers key, where there is no such key in "notifiers"). Same goes with alert-rules, meaning the format of alert-rules in new way (i.e. Unified Alerting), is different from Legacy format.

So, my question is how do I convert the old format to new? (or get the new format perhaps from API or something)?

I'm using HTTP API to get the contactPoints (api/v1/provisioning/contact-points), and rules (api/ruler/grafana/api/v1/rules/), but they are still in the old format. How can I get/export my alert-rules and contactPoints in new format? It's not practical to convert them from old to new by hand manually. The reason I need the new format, is so I can use provision my alerting resources using file-provisioning. Apparently (I tested), provisioning fails if I use old format, but succeeds with new format, naturally.

I saw this post too, but as I mentioned the API gives me the "old" definitions. I feel I'm missing something, but don't know what exactly.

I'm using Grafana V9.x, and I'm using following setting for migration (migrating from V7.x):

[alerting]
enabled = false
[unified alerting]
enabled = true

I do see alert-rules and contactPoints being populated in Grafana UI as expected. Next, following this post. in step 2, what I get back from API is the "old" content/format, which apparently I can't use for provisioning. How can I get back my alert-rules, contactPoints, etc... in new format, so I can use it for provisioning?


问:
Using Transform, Scale and Translate to Optimize Mobile Responsiveness
I am trying mobile optimize my website beyond media query breakpoints. I found a website (image below) that somehow scaling the entire webpage (image and text) using Transform(scale, translate) attached to each element. I've seen this primarily used on Showit websites but cannot figure out how it is applied to the HTML/CSS. Is there are a form of JQuery being used to scale in addition to the media query breakpoints? Any help or codepen is appreciated!

I have attempted to use aspect ratios in CSS to create this, however I did not work.

https://i.stack.imgur.com/YN5A3.gif


问:
Can I add method suggestions to VSCode?
I wanted to know if there is a way to add a feature I had in IntelliJ where you could write the name of a class and a dot after it and you'd have a roll down menu with all the attributes and methods available in that class.

Like this for example: Console. and then the IDE will show me all the methods available like WriteLine if I'm coding in C#.

Is there anyway to do this with VSCode?

Title: Can I add method suggestions to VSCode?


问:
Sonarquebe codesmell 'Track uses of “TODO” tags' doesnot work for Test Java Classes
Is there a way  to enable detection of TODOs as codesmell in Java test classes ?

The java:S1135 codesmell specification says that it should be detected for Test classes.

https://rules.sonarsource.com/java/type/Code%20Smell/RSPEC-1135

However , when I add a simple //TODO in a test classes and run analyze with Sonarlint it doesnot detect the code smell , while other codesmells like @Disabled get detected.

TodoTagPresenceCheck-Github Source code


问:
Alert based on GCP logs with MQL
So, from my understanding MQL is used for advanced metrics and not something simple like Log based alert but is it possible to Alert from GCP log. The log comes as output of cronjob running in Kubernetes.</p>

Title: Alert based on GCP logs with MQL


问:
unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat in Teamcity root folder
I am trying to run command on my fresh Ubuntu 20.04 home server:

```<code>docker build -t docker-test -f Dockerfile .
</code>```

in root directory of my own home teamcity server. I am trying to run temcity agent, which build docker image for me. Test directory:

```<code>/opt/teamcity/test
</code>```

In docker file I have only one single line

```<code>FROM mcr.microsoft.com/dotnet/sdk:3.1-focal AS build-env
</code>```

but after executing command I have this error:

unable to prepare context: unable to evaluate symlinks in Dockerfile
path: lstat  /var/lib/snapd/void/Dockerfile: no such file or directory

I create user teamcity, grand access to folder and created group docker and add users to group. How can I solve problem?

Body:
I am trying to run command on my fresh Ubuntu 20.04 home server:

docker build -t docker-test -f Dockerfile .

in root directory of my own home teamcity server. I am trying to run temcity agent, which build docker image for me. Test directory:

/opt/teamcity/test

In docker file I have only one single line

FROM mcr.microsoft.com/dotnet/sdk:3.1-focal AS build-env

but after executing command I have this error:

unable to prepare context: unable to evaluate symlinks in Dockerfile
path: lstat  /var/lib/snapd/void/Dockerfile: no such file or directory

I create user teamcity, grand access to folder and created group docker and add users to group. How can I solve problem?


问:
Is there a way to listen for keyboard input without pausing the loop of a program in C?
Okay, so i'm currently working on a duplicate of T-Rex game from Chrome, the one that is available if you do not have internet access. I am trying to do it in C language and use ncurses library for this purpose. So far i have a jumping dinosaur in static world, but i encoutered a problem i cannot solve for life. I need the world to loop, possibly endlessly but even a limited world works, but at the same time i need to listen to keyboard input in order to Jump with the dinosaur to avoid obstacles. How can i achieve that? Right now it's jumping based on a getch() function, but that function pauses the code and waits for the user input, so the world won't move until you push some key, and that's obviously not what i need. Is there some way to do this, or is it too advanced? Thanks!

Already tried getch() function, kbhit() function which is not available for me since i'm also working on a Linux OS, using getch() as a condition for IF statement, all without any luck ...


问:
how do I reopen a wallet I created on bitcoinlib?
I browsed innumerable sources online and tried a few methods of my own, but I still can't figure out how to reopen a previously created wallet. w = wallet. ___ (insert key here)  would be the most logical answer to do so I assume in order to run commands such as w.info () .

Thanks in advance!


问:
How do i block all VPN connections to my server?
I have a server in one game (it's called Mindustry).
On average, 60 people constantly play on the server, about 10,000 unique users enter per day.
Some people who use VPNs bypass all the bans and interfere with regular players. I need an easy and free way to block all VPN connections to my server.

Some info:

the server is running on a dedicated host with Ubuntu 20.04

i have a root access on the host

this game (Mindustry) supports loading java mods & plugins, they can track the connection of a player and get his ip-address

the game code is here: https://github.com/anuken/mindustry

I tried using public free anti-vpn APIs, but i need at least 10000 queries per day, however no API gives you that much.
I also tried to set up the firewall on my host, but idk where can i find all VPN IPs and how do i block them all.

Sorry for my bad english, it's not my national language
Also it's my first time asking something on StackOverflow


问:
Exclamation mark meaning into a chain
I know the meaning of a interrogation mark into a chain. For example:

```<code>last: dataChecked?.last,
</code>```

Here interrogation mark prevents the typical error "cannot read property of undefined". In this case prevent runtime error if dataChecked has undefined value.

But what about exclamation mark. Here an example:

```<code>this.form = this.options!.form
</code>```

Title: Exclamation mark meaning into a chain

Body:
I know the meaning of a interrogation mark into a chain. For example:

last: dataChecked?.last,

Here interrogation mark prevents the typical error "cannot read property of undefined". In this case prevent runtime error if dataChecked has undefined value.

But what about exclamation mark. Here an example:

this.form = this.options!.form


问:
How can I make a Window became Identifiable in SwiftUI macOS?
I want be able to track which Window get focused by user there foe I am using NSWindow.didBecomeMainNotification and NSWindow.didResignKeyNotification which is doing good job, but the issue is here if my user decide to make a new window of my app via File > New Window my code would not be able to identify this 2 deferent Window, and all of windows would be recognised as the same one, here my used code:

```<code>@main
struct oioApp: App {

    let uuid: UUID = UUID()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeMainNotification), perform: { newValue in
                    print("Focused = true", uuid, newValue.hashValue)
                })
                .onReceive(NotificationCenter.default.publisher(for: NSWindow.didResignKeyNotification), perform: { newValue in
                    print("Focused = false", uuid, newValue.hashValue)
                })
        }
    }
}
</code>```

I tried to use a uuid for making it trackable or even using the hashValue of notification, but all my try did not worked, and I am receiving same print for both deferent Window.

Body:
I want be able to track which Window get focused by user there foe I am using NSWindow.didBecomeMainNotification and NSWindow.didResignKeyNotification which is doing good job, but the issue is here if my user decide to make a new window of my app via File > New Window my code would not be able to identify this 2 deferent Window, and all of windows would be recognised as the same one, here my used code:

@main
struct oioApp: App {

    let uuid: UUID = UUID()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeMainNotification), perform: { newValue in
                    print("Focused = true", uuid, newValue.hashValue)
                })
                .onReceive(NotificationCenter.default.publisher(for: NSWindow.didResignKeyNotification), perform: { newValue in
                    print("Focused = false", uuid, newValue.hashValue)
                })
        }
    }
}

I tried to use a uuid for making it trackable or even using the hashValue of notification, but all my try did not worked, and I am receiving same print for both deferent Window.


问:
Stack Overflow error while using gridview builder with Sliver App bar and tabcontroller
Hello I am using the below code to make one of the tabbars disappears when I scroll down. it generates an error of "Stack overflow".
the error happens in the Gridview Builder and Listview.separated parts.

Note:
I have one main sliver app bar with nestedscrollview and it is workig correctly.
what I would like to do is to add the below tab bar in a different place in the widget tree and make it disappear while scroll down.

(so the below tab bar is not directly under the main AppBar)

is the below code correct?
if not, how can I achieve my objective?

```<code> Column(childeren:[
 Sizedbox(),
 Expanded(
      child: Padding(
        padding: EdgeInsets.fromLTRB(8.w, 0, 8.w, 0),
        child: DefaultTabController(
            length: 2,
            child: Scaffold(
              body: NestedScrollView(
                headerSliverBuilder:
                    (BuildContext context, bool innerBoxIsScrolled) {
                  return <Widget>[
                    SliverAppBar(
                      floating: true,
                      pinned: true,
                      snap:true,
                      bottom: TabBar(
                        indicator: BoxDecoration(
                            color: const Color.fromARGB(255, 249, 225, 238),
                            borderRadius: BorderRadius.circular(25.0)),
                        labelColor: Colors.white,
                        unselectedLabelColor: Colors.black,
                        tabs: [
                          Text(
                            "Tab1"
                            ),
                          ),
                          Text("Tab2"
                            ),
                          ),
                        ],
                      ),
                    ),
                  ];
                },
                body: TabBarView(children: [
                  CategoriesPage(), // This page contains a Column with expanded and gridview.builder.
                  OffersPage(), // this page contains a Column with expanded and listview.seprated
                ]),
              ),
            )),
      ),
    ),
   ]
</code>```

The error happens in the Gridview and the listview in the Tabbar views.

Snapshot of Gridview:

```<code> Column(childern:[
  SizedBox(),
  Expanded(
        child: Material(
          elevation: 4.h,
          child: Container(
            color: const Color.fromARGB(255, 248, 244, 244),
            padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 0),
            child: StreamBuilder<QuerySnapshot>(
                stream: FirebaseFirestore.instance
                    .collection('CategoriesCollection')
                    .orderBy('Category_order_level_1')
                    .orderBy('Category_order_level_2')
                    .where('Category_status', isEqualTo: "Active")
                    .snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return SizedBox();
                  } else {
                    return GridView.builder( // this is where the problem happens
                      gridDelegate:
                          SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              mainAxisExtent: 130.h,
                              crossAxisSpacing: 2.w,
                              mainAxisSpacing: 2.h),
                      itemCount: snapshot.data!.docs.length,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return Container();}));})))]
</code>```

Body:
Hello I am using the below code to make one of the tabbars disappears when I scroll down. it generates an error of "Stack overflow".
the error happens in the Gridview Builder and Listview.separated parts.

Note:
I have one main sliver app bar with nestedscrollview and it is workig correctly.
what I would like to do is to add the below tab bar in a different place in the widget tree and make it disappear while scroll down.

(so the below tab bar is not directly under the main AppBar)

is the below code correct?
if not, how can I achieve my objective?

 Column(childeren:[
 Sizedbox(),
 Expanded(
      child: Padding(
        padding: EdgeInsets.fromLTRB(8.w, 0, 8.w, 0),
        child: DefaultTabController(
            length: 2,
            child: Scaffold(
              body: NestedScrollView(
                headerSliverBuilder:
                    (BuildContext context, bool innerBoxIsScrolled) {
                  return <Widget>[
                    SliverAppBar(
                      floating: true,
                      pinned: true,
                      snap:true,
                      bottom: TabBar(
                        indicator: BoxDecoration(
                            color: const Color.fromARGB(255, 249, 225, 238),
                            borderRadius: BorderRadius.circular(25.0)),
                        labelColor: Colors.white,
                        unselectedLabelColor: Colors.black,
                        tabs: [
                          Text(
                            "Tab1"
                            ),
                          ),
                          Text("Tab2"
                            ),
                          ),
                        ],
                      ),
                    ),
                  ];
                },
                body: TabBarView(children: [
                  CategoriesPage(), // This page contains a Column with expanded and gridview.builder.
                  OffersPage(), // this page contains a Column with expanded and listview.seprated
                ]),
              ),
            )),
      ),
    ),
   ]

The error happens in the Gridview and the listview in the Tabbar views.

Snapshot of Gridview:

 Column(childern:[
  SizedBox(),
  Expanded(
        child: Material(
          elevation: 4.h,
          child: Container(
            color: const Color.fromARGB(255, 248, 244, 244),
            padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 0),
            child: StreamBuilder<QuerySnapshot>(
                stream: FirebaseFirestore.instance
                    .collection('CategoriesCollection')
                    .orderBy('Category_order_level_1')
                    .orderBy('Category_order_level_2')
                    .where('Category_status', isEqualTo: "Active")
                    .snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return SizedBox();
                  } else {
                    return GridView.builder( // this is where the problem happens
                      gridDelegate:
                          SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 2,
                              mainAxisExtent: 130.h,
                              crossAxisSpacing: 2.w,
                              mainAxisSpacing: 2.h),
                      itemCount: snapshot.data!.docs.length,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return Container();}));})))]


问:
Nested ASP Awesome Grid Not Populating
I am using ASP Awesome (https://www.aspnetawesome.com/learn/mvc/general) and ASP.NET MVC to handle two grids. I am using the first grid to display several entries, and then a partial view for the nested second grid . Basic usage is that when the user clicks a row in the first grid, the second nested grid is automatically shown.

This worked perfectly at one time, but for seemingly no reason has quit working. Code below:

Here is the first grid code:

```<code>@(Html.Awe().Grid("ReliabilityGrid")
                .Resizable()
                .Groupable(false)
                .Url(Url.Action("GetTopReliabilities", "Reliability"))
                .Columns(
                new Column
                {
                    Bind = "TestNumber",
                    Header = "Test Number",
                    ClientFormat = "<div class='detailnst'><i class='caretc'><i class='o-caret'></i></i><i class='fa fa-caret-right'></i> .TestNumber</div>   <a href='/Reliability/GetGraph?testNum=.TestNumber' style='display: inline'><img id='graphIMG' src='/img/graphIcon.png' width='20' height='20'></a> " + " " +
                "<a href='javascript:makeExcel(.TestNumber)'><img id='excelIMG' src='/img/testsearch/excel_icon_small.jpg' width='20' height='20'></a> "
                },
                new Column { Bind = "TestStall", Header = "Test Stall" },
                new Column { Bind = "Voltage", Header = "Voltage" },
                new Column { Bind = "Ambient", Header = "Ambient" },
                new Column { Bind = "Request", Header = "Request" },
                new Column { Bind = "Unit", Header = "Unit" },
                new Column { Bind = "CycleStart", Header = "Cycle Start" },
                new Column { Bind = "CycleEnd", Header = "Cycle End" }

                )
                .Nests(new Nest { Name = "detailnst", Url = Url.Action("ReliabilityKey"), LoadOnce = true }))
</code>```

This grid correctly loads data from the "GetTopReliabilities" method and displays the data. At the bottom as you can see I set up the Nested second grid.

Once the user clicks on a row inside this first grid, a method is fired which returns a partial view containing the nested grid. The view code and nested second grid below:

Nested second grid contained within my partial view below:

```<code><div style="margin: 5px;">
 @(Html.Awe().Grid("ReliabilityPartGrid" + ViewData["Id"])
  .Url(Url.Action("GetPartialData", "Reliability"))
  .Reorderable()
  .Groupable(false)
  .Columns(
         new Column { Bind = "id", Hidden = true },
                        new Column { Bind = "CycleNumber", Header = "Cycle", Width = 75,
                                                                Sort = Sort.Desc },
                        new Column { Bind = "Comment", Header = "Comment" },
                        new Column { Bind = "CommentUserID", Header = "User ID", Width = 150 },
                        new Column { Bind = "EventType", Header = "Event Type", Width=75 },
                        new Column { Bind = "TimeStamp", Header = "Timestamp", Width=200},
                        new Column { Bind = "N1", Header = Model.dArray[0], Width = 90 },
                        new Column { Bind = "N2", Header = Model.dArray[1], Width = 90 },
                        new Column { Bind = "N3", Header = Model.dArray[2], Width = 90 },
                        new Column { Bind = "N4", Header = Model.dArray[3], Width = 90 },
                        new Column { Bind = "N5", Header = Model.dArray[4], Width = 90 },
                        new Column { Bind = "N6", Header = Model.dArray[5], Width = 90 },
                        new Column { Bind = "N7", Header = Model.dArray[6], Width = 90 },
                        new Column { Bind = "N8", Header = Model.dArray[7], Width = 90 },
                        new Column { Bind = "N9", Header = Model.dArray[8], Width = 90 },
                        new Column { Bind = "N10", Header = Model.dArray[9], Width = 90 })
                        .Parameter("keys", ViewData["Id"])
                        .Parent("selEvent", "EventType"))
     </div>
</code>```

The issue is that the "GetPartialData" action method is never hit for this second grid. The grid shows up completely blank in my partial view. I know the partial view is displayed because a grid does appear, but it does not contain any data.

I have set breakpoints to no avail. Here is the source code for the 2nd nested grid as rendered in the browser:

It correctly displays the method/controller URL, GetPartialData and Reliability controller.

But yet a breakpoint set on this method is never hit and grid is never populated.

Why isn't my grid populating correctly? Any help is much appreciated.

Title: Nested ASP Awesome Grid Not Populating

Body:
I am using ASP Awesome (https://www.aspnetawesome.com/learn/mvc/general) and ASP.NET MVC to handle two grids. I am using the first grid to display several entries, and then a partial view for the nested second grid . Basic usage is that when the user clicks a row in the first grid, the second nested grid is automatically shown.

This worked perfectly at one time, but for seemingly no reason has quit working. Code below:

Here is the first grid code:

@(Html.Awe().Grid("ReliabilityGrid")
                .Resizable()
                .Groupable(false)
                .Url(Url.Action("GetTopReliabilities", "Reliability"))
                .Columns(
                new Column
                {
                    Bind = "TestNumber",
                    Header = "Test Number",
                    ClientFormat = "
 .TestNumber
    " + " " +
                " "
                },
                new Column { Bind = "TestStall", Header = "Test Stall" },
                new Column { Bind = "Voltage", Header = "Voltage" },
                new Column { Bind = "Ambient", Header = "Ambient" },
                new Column { Bind = "Request", Header = "Request" },
                new Column { Bind = "Unit", Header = "Unit" },
                new Column { Bind = "CycleStart", Header = "Cycle Start" },
                new Column { Bind = "CycleEnd", Header = "Cycle End" }

                )
                .Nests(new Nest { Name = "detailnst", Url = Url.Action("ReliabilityKey"), LoadOnce = true }))

This grid correctly loads data from the "GetTopReliabilities" method and displays the data. At the bottom as you can see I set up the Nested second grid.

Once the user clicks on a row inside this first grid, a method is fired which returns a partial view containing the nested grid. The view code and nested second grid below:

Nested second grid contained within my partial view below:

 @(Html.Awe().Grid("ReliabilityPartGrid" + ViewData["Id"])
  .Url(Url.Action("GetPartialData", "Reliability"))
  .Reorderable()
  .Groupable(false)
  .Columns(
         new Column { Bind = "id", Hidden = true },
                        new Column { Bind = "CycleNumber", Header = "Cycle", Width = 75,
                                                                Sort = Sort.Desc },
                        new Column { Bind = "Comment", Header = "Comment" },
                        new Column { Bind = "CommentUserID", Header = "User ID", Width = 150 },
                        new Column { Bind = "EventType", Header = "Event Type", Width=75 },
                        new Column { Bind = "TimeStamp", Header = "Timestamp", Width=200},
                        new Column { Bind = "N1", Header = Model.dArray[0], Width = 90 },
                        new Column { Bind = "N2", Header = Model.dArray[1], Width = 90 },
                        new Column { Bind = "N3", Header = Model.dArray[2], Width = 90 },
                        new Column { Bind = "N4", Header = Model.dArray[3], Width = 90 },
                        new Column { Bind = "N5", Header = Model.dArray[4], Width = 90 },
                        new Column { Bind = "N6", Header = Model.dArray[5], Width = 90 },
                        new Column { Bind = "N7", Header = Model.dArray[6], Width = 90 },
                        new Column { Bind = "N8", Header = Model.dArray[7], Width = 90 },
                        new Column { Bind = "N9", Header = Model.dArray[8], Width = 90 },
                        new Column { Bind = "N10", Header = Model.dArray[9], Width = 90 })
                        .Parameter("keys", ViewData["Id"])
                        .Parent("selEvent", "EventType"))

The issue is that the "GetPartialData" action method is never hit for this second grid. The grid shows up completely blank in my partial view. I know the partial view is displayed because a grid does appear, but it does not contain any data.

I have set breakpoints to no avail. Here is the source code for the 2nd nested grid as rendered in the browser:

It correctly displays the method/controller URL, GetPartialData and Reliability controller.

But yet a breakpoint set on this method is never hit and grid is never populated.

Why isn't my grid populating correctly? Any help is much appreciated.


Title: how to add text on each rectangle in collection using matplotlib?

Body:
I am using matplotlib for plotting and convenient visualization of some graphs in xy coordinates.

I need to highlight some regions - and I use rectangles for this.

But I am interested to add some text upon each rectangle - to be able to distinguish those regions. How to do it using patches because I have a lot of objects in a plot?

Here is the code I use to plot rectangles:

# sample data for rectangles visualization
windows_df = pd.DataFrame( {'window_index_num': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}, 'left_pulse_num': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}, 'right_pulse_num': {0: 2, 1: 3, 2: 4, 3: 5, 4: 6, 5: 7, 6: 8, 7: 9, 8: 10, 9: 11}, 'idx_of_left_pulse': {0: 0, 1: 4036, 2: 4080, 3: 4107, 4: 4368, 5: 4491, 6: 4529, 7: 4624, 8: 4626, 9: 4639}, 'idx_of_right_pulse': {0: 4080, 1: 4107, 2: 4368, 3: 4491, 4: 4529, 5: 4624, 6: 4626, 7: 4639, 8: 4679, 9: 4781}, 'left_pulse_pos_in_E': {0: 10.002042118364418, 1: 40.29395464818188, 2: 41.19356816747343, 3: 41.76060061888303, 4: 47.90221207147802, 5: 51.27679395217831, 6: 52.39165780468267, 7: 55.37561818764979, 8: 55.47294132608167, 9: 55.99635666692289}, 'right_pulse_pos_in_E': {0: 41.19356816747343, 1: 41.76060061888303, 2: 47.90221207147802, 3: 51.27679395217831, 4: 52.39165780468267, 5: 55.37561818764979, 6: 55.47294132608167, 7: 55.99635666692289, 8: 57.33777021469516, 9: 60.984834434908144}, 'idx_window_left_border': {0: 0, 1: 3990, 2: 4058, 3: 4093, 4: 4237, 5: 4429, 6: 4510, 7: 4576, 8: 4625, 9: 4632}, 'idx_window_right_border': {0: 4094, 1: 4238, 2: 4430, 3: 4510, 4: 4577, 5: 4625, 6: 4633, 7: 4659, 8: 4730, 9: 4792}, 'left_win_pos_in_E': {0: 10.002042118364418, 1: 39.38459790393702, 2: 40.74003692229216, 3: 41.46513255508269, 4: 44.66179219947279, 5: 49.53272998148, 6: 51.82972979173252, 7: 53.82159300113625, 8: 55.40803086073492, 9: 55.76645477820397}, 'right_win_pos_in_E': {0: 41.48613320837913, 1: 44.6852679849016, 2: 49.56014983071213, 3: 51.82972979173252, 4: 53.85265044341121, 5: 55.40803086073492, 6: 55.79921126600202, 7: 56.66110947958804, 8: 59.119140585251095, 9: 61.39880967219205}, 'window_width': {0: 4095, 1: 249, 2: 373, 3: 418, 4: 341, 5: 197, 6: 124, 7: 84, 8: 106, 9: 161}, 'window_width_in_E': {0: 31.48409109001471, 1: 5.300670080964579, 2: 8.820112908419965, 3: 10.364597236649828, 4: 9.190858243938415, 5: 5.875300879254915, 6: 3.9694814742695, 7: 2.8395164784517917, 8: 3.7111097245161773, 9: 5.632354893988079}, 'sum_pulses_duration_in_E': {0: 0.5157099691135514, 1: 0.5408987779694527, 2: 0.6869248977656355, 3: 0.7304908951030242, 4: 0.7269657511683718, 5: 0.537271616198268, 6: 0.7609034761658222, 7: 0.6178183490930067, 8: 0.8269277926972265, 9: 0.5591109437337494}, 'sum_pulse_sq': {0: 3.7944375922206044, 1: 3.8756992116858715, 2: 2.9661915477796663, 3: 3.070559830941317, 4: 3.0597037730539385, 5: 10.2020204659669, 6: 45.77535573608872, 7: 45.87630607524008, 8: 39.10335270063814, 9: 3.437205923490125}, 'pulse_to_window_rate': {0: 0.01638001769335214, 1: 0.10204347180781788, 2: 0.07788164447530765, 3: 0.0704794290047244, 4: 0.0790966122938326, 5: 0.09144580460471718, 6: 0.1916883807363909, 7: 0.2175787158769594, 8: 0.22282493757444324, 9: 0.09926770493999569}, 'max_height_in_window': {0: 20.815950580921104, 1: 20.815950580921104, 2: 5.324888970962656, 3: 5.324888970962656, 4: 5.14075603114903, 5: 86.81228155905252, 6: 110.06755904473022, 7: 110.06755904473022, 8: 110.06755904473022, 9: 14.735092268739246}, 'min_height_in_window': {0: -0.011928180619527797, 1: 1.6172637244080776, 2: 1.6172637244080776, 3: 0.8658702248969847, 4: 0.8658702248969847, 5: 0.8658702248969847, 6: 1.8476229914953515, 7: 2.918666252051556, 8: 3.2397786967451707, 9: 2.4893555139463266}, 'windows_sq': {0: 655.3712842149647, 1: 110.33848645112575, 2: 46.96612194869083, 3: 55.19032951390669, 4: 47.24795994896218, 5: 510.0482741740266, 6: 436.911136546121, 7: 312.538647650477, 8: 408.4727887246568, 9: 82.9932690531994}} )

fig_w, axs_w = plt.subplots()

#theoretical cross-section
#axs_w.plot(df_wo_NANS['E'], df_wo_NANS['theo_cs'], marker = "o", markersize = 1, linewidth = 1.0, alpha=0.6, color = 'green', label = 'Theo Cross Section')
axs_w.grid(color = 'grey', linestyle = '--', linewidth = 0.2)

#windows rectangular
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
boxes = []

for index,row in windows_df.iterrows():
    current_rect_left_corner = (row['left_win_pos_in_E'], row['min_height_in_window'])
    current_w = row['window_width_in_E']
    current_h = row['max_height_in_window']-row['min_height_in_window']

    boxes.append(Rectangle(current_rect_left_corner, current_w, current_h))

    left = row['left_win_pos_in_E']
    right = row['right_win_pos_in_E']
    bottom = row['min_height_in_window']
    top = row['max_height_in_window']

    #mark of the start of the current window
    axs_w.text(
        left, #left corner,  #0.5*(left+right), #middle of the rectangle
        top, #top
        str(index),
        horizontalalignment='center',
        verticalalignment='center',
        fontsize=5
        )

    #mark of the end of the current window
    axs_w.text(
        right, #right corner,  #0.5*(left+right), #middle of the rectangle
        top+0.5*bottom, #top
        str(index)+'e',
        horizontalalignment='center',
        verticalalignment='center',
        fontsize=5
        )

pc = PatchCollection(boxes, facecolor='y', alpha=0.2, edgecolor='black')
axs_w.add_collection(pc)

Added text marks using cycle but is it possible to do it using patch and collections to make more efficient code?


问:
How use AntWeb API in Swift
I have experience in OpenWeather API and think that other API's almost the same. But not.

AntWeb provide open API and tell a little bit how to use it.
https://www.antweb.org/api.do

But their example-links doesn't returns any data in JSON. I found only Python examples (or other programming language, idk), on GitHub.

Is it some special API or am I missing something?
Or it doesn't work at all?

I was try simple URLSession.shared.dataTask(with: url). But it returns nothing.

```<code>   let url = URL(string: "https://antweb.org/v3.1/geoSpecimens?coords=37,%20-122&limit=100&radius=1")!

   let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
      guard let data = data else { return }
      print(String(data: data, encoding: .utf8)!)
   }

   task.resume()
</code>```

Title: How use AntWeb API in Swift

Body:
I have experience in OpenWeather API and think that other API's almost the same. But not.

AntWeb provide open API and tell a little bit how to use it.
https://www.antweb.org/api.do

But their example-links doesn't returns any data in JSON. I found only Python examples (or other programming language, idk), on GitHub.

Is it some special API or am I missing something?
Or it doesn't work at all?

I was try simple URLSession.shared.dataTask(with: url). But it returns nothing.

   let url = URL(string: "https://antweb.org/v3.1/geoSpecimens?coords=37,%20-122&limit=100&radius=1")!

   let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
      guard let data = data else { return }
      print(String(data: data, encoding: .utf8)!)
   }

   task.resume()


问:
Typescript Deep Understanding Generic Types with Union Types (Create Reducer example)
I want to set Typescript types for Create Reducer and I want to understand How can I use Generics in this hard construction.

Here I have Actions

State

Object where Keys is name of action type and value is function with 3 parameter (payload, state, type)

I want to make Auto types based on Passed Types to createReducer function

I have next example

enum ActionTypes {
  INCREMENT = 'INCREMENT',
  DECREMENT = 'DECREMENT',
  SET_COUNT = 'SET_COUNT',
}

type IncrementAction = IAction<ActionTypes.INCREMENT>;
type DecrementAction = IAction<ActionTypes.DECREMENT, 'hello' | 'world'>;
type SetCountAction = IAction<ActionTypes.SET_COUNT, number>;

type CounterState = {
  count: number;
  message?: string;
};

const state: CounterState = {
  count: 0,
};

type Action = IncrementAction | DecrementAction | SetCountAction;

// I want auto type inference for the action type
const counterReducer = createReducer<CounterState, Action>(state, {
  // [ActionTypes.INCREMENT]: (payload: unknown, state: CounterState, type: ActionTypes.INCREMENT)
  [ActionTypes.INCREMENT]: (payload, state, type) => ({ count: state.count + 1 }),

  // [ActionTypes.DECREMENT]: (payload: 'hello' | 'world', state: CounterState, type: ActionTypes.DECREMENT)
  [ActionTypes.DECREMENT]: (payload, state, type) => ({ count: state.count - 1 }),

  // [ActionTypes.SET_COUNT]: (payload: number, state: CounterState, type: ActionTypes.SET_COUNT)
  [ActionTypes.SET_COUNT]: (payload, state, type) => ({ count: payload }),
  ['*']: (payload: unknown, state: CounterState, type: string) => ({}),

  // here should be Error becase is not member of ActionTypes
  ['something']: (payload: unknown, state: CounterState, type: string) => ({}),
});

```
<p>So, I have some code for it, but I cant resolve all types</p>
<pre class="lang-js prettyprint-override"><code>export type IState = Record<string, any>;

export type IAction<T extends string = string, P = unknown> = {
  type: T;
  payload?: P;
};

export type Reducer<S, A extends IAction> = (
  payload: A['payload'],
  state: S,
  type: A['type'],
) => IState;

interface IHandlers<S, A extends IAction, T extends IAction['type'] = string> {
  [key: T]: Reducer<S, A>;
  ['*']: Reducer<S, A>;
}

export function createReducer<S extends IState, A extends IAction>(
  initialState: S = {} as S,
  handlers: IHandlers<S, A>,
) {
  return function reducer(state = initialState, action: A) {
    let newState = state;
    if (handlers.hasOwnProperty(action.type)) {
      const result = handlers[action.type](action.payload, state, action.type);
      newState = { ...state, ...result };
    }
    if (handlers['*']) {
      return { ...newState, ...handlers['*'](action.payload, newState, action.type) };
    }
    return newState;
  };
}

export default createReducer;
</code>```

Body:
I want to set Typescript types for Create Reducer and I want to understand How can I use Generics in this hard construction.

Here I have Actions

State

Object where Keys is name of action type and value is function with 3 parameter (payload, state, type)

I want to make Auto types based on Passed Types to createReducer function

I have next example

enum ActionTypes {
  INCREMENT = 'INCREMENT',
  DECREMENT = 'DECREMENT',
  SET_COUNT = 'SET_COUNT',
}

type IncrementAction = IAction<ActionTypes.INCREMENT>;
type DecrementAction = IAction<ActionTypes.DECREMENT, 'hello' | 'world'>;
type SetCountAction = IAction<ActionTypes.SET_COUNT, number>;

type CounterState = {
  count: number;
  message?: string;
};

const state: CounterState = {
  count: 0,
};

type Action = IncrementAction | DecrementAction | SetCountAction;

// I want auto type inference for the action type
const counterReducer = createReducer<CounterState, Action>(state, {
  // [ActionTypes.INCREMENT]: (payload: unknown, state: CounterState, type: ActionTypes.INCREMENT)
  [ActionTypes.INCREMENT]: (payload, state, type) => ({ count: state.count + 1 }),

  // [ActionTypes.DECREMENT]: (payload: 'hello' | 'world', state: CounterState, type: ActionTypes.DECREMENT)
  [ActionTypes.DECREMENT]: (payload, state, type) => ({ count: state.count - 1 }),

  // [ActionTypes.SET_COUNT]: (payload: number, state: CounterState, type: ActionTypes.SET_COUNT)
  [ActionTypes.SET_COUNT]: (payload, state, type) => ({ count: payload }),
  ['*']: (payload: unknown, state: CounterState, type: string) => ({}),

  // here should be Error becase is not member of ActionTypes
  ['something']: (payload: unknown, state: CounterState, type: string) => ({}),
});

So, I have some code for it, but I cant resolve all types

export type IState = Record<string, any>;

export type IAction<T extends string = string, P = unknown> = {
  type: T;
  payload?: P;
};

export type Reducer<S, A extends IAction> = (
  payload: A['payload'],
  state: S,
  type: A['type'],
) => IState;

interface IHandlers<S, A extends IAction, T extends IAction['type'] = string> {
  [key: T]: Reducer<S, A>;
  ['*']: Reducer<S, A>;
}

export function createReducer<S extends IState, A extends IAction>(
  initialState: S = {} as S,
  handlers: IHandlers<S, A>,
) {
  return function reducer(state = initialState, action: A) {
    let newState = state;
    if (handlers.hasOwnProperty(action.type)) {
      const result = handlers[action.type](action.payload, state, action.type);
      newState = { ...state, ...result };
    }
    if (handlers['*']) {
      return { ...newState, ...handlers['*'](action.payload, newState, action.type) };
    }
    return newState;
  };
}

export default createReducer;


问:
Linking to a Google Play search result / Invoking a Google Play Search from an Android App on Android TV
I am building Apps for Android TV. In the app, I give users the option to display further apps that I have created. On all Android devices this works fine by starting an intent that starts Google Play and runs a search as described via here: Linking to Google Play.

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
        "http://play.google.com/store/search?q=<search_query>&c=apps"));
intent.setPackage("com.android.vending");
startActivity(intent);
</code>```

On all devices, when I start the intent, Google Play pops up and displays the results of my query.

On Android TV devices however, the same action purely results in a toast being displayed: "play store search is not available". I did not find a solution yet of how to code such a search in a way, that it also runs on Android TV respectively on Google TV devices.

Google Play is available on all devices that I tested this. On all devices I was logged on to Google with a valid account. Running the intent with a simple link to a Play Store App works fine. Running it with a link to the search does not.

Body:
I am building Apps for Android TV. In the app, I give users the option to display further apps that I have created. On all Android devices this works fine by starting an intent that starts Google Play and runs a search as described via here: Linking to Google Play.

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
        "http://play.google.com/store/search?q=<search_query>&c=apps"));
intent.setPackage("com.android.vending");
startActivity(intent);

On all devices, when I start the intent, Google Play pops up and displays the results of my query.

On Android TV devices however, the same action purely results in a toast being displayed: "play store search is not available". I did not find a solution yet of how to code such a search in a way, that it also runs on Android TV respectively on Google TV devices.

Google Play is available on all devices that I tested this. On all devices I was logged on to Google with a valid account. Running the intent with a simple link to a Play Store App works fine. Running it with a link to the search does not.


问:
AWS Lambda, no longer provides default access to aws-sdk?
Havent used aws in a while and it seems some changes have been made. I tried making a lambda function that connects to cognito today, but when I test it i get an error:

the first line in the function is :

```<code>import AWS from 'aws-sdk'
</code>```

the error in cloudwatch:

"Cannot find package 'aws-sdk' imported from /var/task/index.mjs"

I read some stuff suggesting a work around creating a layer and uploading a zip file with some shareable code that includes the sdk, but I dont want to do that. Is aws-sdk really no longer accessible by default in a lambda function?

Body:
Havent used aws in a while and it seems some changes have been made. I tried making a lambda function that connects to cognito today, but when I test it i get an error:

the first line in the function is :

import AWS from 'aws-sdk'

the error in cloudwatch:

"Cannot find package 'aws-sdk' imported from /var/task/index.mjs"

I read some stuff suggesting a work around creating a layer and uploading a zip file with some shareable code that includes the sdk, but I dont want to do that. Is aws-sdk really no longer accessible by default in a lambda function?


问:
How to change the color of the bar that shows up when an Entry is active?
I'm trying to change the color of the bar that lights up when focusing on an Entry (see screenshot below for reference)

The bar is purple (on google pixel emulator) when I start typing.

Entry Bar

`

```<code>    <Style TargetType="Entry">
        <Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
        <Setter Property="BackgroundColor" Value="Transparent" />
        <Setter Property="FontFamily" Value="OpenSansRegular"/>
        <Setter Property="FontSize" Value="14" />
        <Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
        <Setter Property="MinimumHeightRequest" Value="44"/>
        <Setter Property="MinimumWidthRequest" Value="44"/>
        <Setter Property="VisualStateManager.VisualStateGroups">
            <VisualStateGroupList>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Normal"/>
                    <VisualState x:Name="Disabled"/>
                </VisualStateGroup>
            </VisualStateGroupList>
        </Setter>
    </Style>

</code>```

`

Changed my primary, secondary and tertiary color in styles just in case it is automatically set to one of those

Tried to set a visual state for "Focused" in the code below under "VisualStateGroup"

Body:
I'm trying to change the color of the bar that lights up when focusing on an Entry (see screenshot below for reference)

The bar is purple (on google pixel emulator) when I start typing.

Entry Bar

`

`

Changed my primary, secondary and tertiary color in styles just in case it is automatically set to one of those

Tried to set a visual state for "Focused" in the code below under "VisualStateGroup"


问:
How can we compare two @Rest\RequestParam?
I am trying to compare two input values, provided to the request body via API.
Is there a way via Annonations to compare two request params?

i.e.,

```<code>* @Rest\RequestParam(
*     name="abc",
*     strict=true,
*     nullable=false
* )
* @Rest\RequestParam(
*     name="xyz",
*     strict=true,
*     nullable=false
*     requirements={
*         @Assert\EqualTo(
*             value="abc"
*         )
*     }
* )
</code>```

But above logic will not work because here "xyz" is trying to compare with string "abc" not the request body value provided.

Body:
I am trying to compare two input values, provided to the request body via API.
Is there a way via Annonations to compare two request params?

i.e.,

* @Rest\RequestParam(
*     name="abc",
*     strict=true,
*     nullable=false
* )
* @Rest\RequestParam(
*     name="xyz",
*     strict=true,
*     nullable=false
*     requirements={
*         @Assert\EqualTo(
*             value="abc"
*         )
*     }
* )

But above logic will not work because here "xyz" is trying to compare with string "abc" not the request body value provided.


问:
Problem with Slim Framework V3 routes when deploying using nginx reverse proxy
I'm trying to deploy a Slim v3 project on a dockerized nginx reverse proxy on my dedicated server (let's supose the URL is www.mywebsite.com) and I assigned a 'subdirectory' ussing the reverse proxy (for example /my_project).

The problem is that when I want to go to a route diferent to / in the 'subdirectory', the subdirectory part of the URL is deleted.

For example, when I go to www.mywebsite.com/my_project it works fine, but when I want to go to the route www.mywebsite.com/my_project/register the browser redirects me to www.mywebsite.com/register, deleting the 'subdirectory' part of the URL.

I've already tried to force a base url but without success changing the APP_URL variable on index.php

An example in Laravel of what I want to achieve with Slim

I've made deploys on Nginx Reverse Proxy using the Laravel Framework and I faced this issue, but I solved it defining the APP_URL in .env file like www.mywebsite.com/my_projectand forcing the root url using the next code

```<code>public function boot()
    {
        URL::forceRootUrl(Config::get('app.url'));
        if (Str::contains(Config::get('app.url'), 'https://')) {
            URL::forceScheme('https');
        }
    }
</code>```

I hope that this example of Laravel helps me to clarify the problem i'm facing.

Body:
I'm trying to deploy a Slim v3 project on a dockerized nginx reverse proxy on my dedicated server (let's supose the URL is www.mywebsite.com) and I assigned a 'subdirectory' ussing the reverse proxy (for example /my_project).

The problem is that when I want to go to a route diferent to / in the 'subdirectory', the subdirectory part of the URL is deleted.

For example, when I go to www.mywebsite.com/my_project it works fine, but when I want to go to the route www.mywebsite.com/my_project/register the browser redirects me to www.mywebsite.com/register, deleting the 'subdirectory' part of the URL.

I've already tried to force a base url but without success changing the APP_URL variable on index.php

An example in Laravel of what I want to achieve with Slim

I've made deploys on Nginx Reverse Proxy using the Laravel Framework and I faced this issue, but I solved it defining the APP_URL in .env file like www.mywebsite.com/my_projectand forcing the root url using the next code

public function boot()
    {
        URL::forceRootUrl(Config::get('app.url'));
        if (Str::contains(Config::get('app.url'), 'https://')) {
            URL::forceScheme('https');
        }
    }

I hope that this example of Laravel helps me to clarify the problem i'm facing.


问:
Get-EC2Instance Creds cannot find region
I have been at this all day, we have an account that uses permissions to spin up ec2 instance, it is used heavily and worked without concerns. I have deleted the credentials.ini and config.ini files and reEntered aws configure with even a new password.

It says the creds are fine, however, if I run something simple like (Get-EC2Instance).instances I get in return the following error:

get-ec2instance : Name resolution failure attempting to reach service in region Region (as supplied to the -Region parameter or from configured shell default). The remote name could not be resolved: 'ec2.region.amazonaws.com'.

Note the url says region, even if I set a default in the config region to something like us-east-1

I tried a different person on the same box, and no problems. What can I do to purge the user and try again? The user is using a group permission and that should have not altered (just encase what instances would it need for create & delete ec2?)


问:
How to create nextjs getStaticPaths function using dynamic and nested paths (graphql)?
How to create nextjs getStaticPaths function using dynamic and nested paths (graphql)?

I don't know how I can create the function correctly... Can someone help me? I am using Wordpress headless with graphQL

```<code>export async function getStaticPaths() {
  const GET_ALL_SLUGS = gql`
    query getAllSlugs {
      posts {
        nodes {
          slug
        }
      }
      pages {
        nodes {
          slug
        }
      }
    }
  `;
  const response = await client.query({
    query: GET_ALL_SLUGS,
  });

  const categories = response?.data?.pages?.nodes;
  const posts = response?.data?.posts?.nodes;

  let paths = {
    params: {
      category: "",
      post: "",
    },
  };

  paths = categories.map(({ slug }) => {
    return {
      params: {
        category: slug,
      },
    };
  });

  paths = posts.map(({ slug }) => {
    return {
      params: {
        post: slug,
      },
    };
  });

  return {
    paths,
    fallback: false,
  };
}
</code>```

Body:
How to create nextjs getStaticPaths function using dynamic and nested paths (graphql)?

I don't know how I can create the function correctly... Can someone help me? I am using Wordpress headless with graphQL

export async function getStaticPaths() {
  const GET_ALL_SLUGS = gql`
    query getAllSlugs {
      posts {
        nodes {
          slug
        }
      }
      pages {
        nodes {
          slug
        }
      }
    }
  `;
  const response = await client.query({
    query: GET_ALL_SLUGS,
  });

  const categories = response?.data?.pages?.nodes;
  const posts = response?.data?.posts?.nodes;

  let paths = {
    params: {
      category: "",
      post: "",
    },
  };

  paths = categories.map(({ slug }) => {
    return {
      params: {
        category: slug,
      },
    };
  });

  paths = posts.map(({ slug }) => {
    return {
      params: {
        post: slug,
      },
    };
  });

  return {
    paths,
    fallback: false,
  };
}