问:
How to save a dataframe into multiple files based on unique columns in spark-scala
I've the inputDf that I need to divide based on the columns origin and destination and save each unique combination into a different csv file.

(Using Spark 2.4.4)

```<code>val spark: SparkSession = SparkSession.builder().appName("Test").getOrCreate()

val inputRdd: RDD[(String, String, String, String, String, String)] = spark.sparkContext.parallelize(Seq(
  ("City1", "City2", "Sedan", "AE1235", "80", "2020-02-01"),
  ("City2", "City3", "Hatchback", "XY5434", "100", "2020-02-01"),
  ("City3", "City1", "Sedan", "YU3456", "120", "2020-02-01"),
  ("City3", "City2", "Sedan", "BV3555", "105", "2020-02-01"),
  ("City2", "City1", "SUV", "PO1234", "75", "2020-02-01"),
  ("City1", "City3", "SUV", "TY4123", "125", "2020-02-01"),
  ("City1", "City2", "Hatchback", "VI3415", "85", "2020-02-01"),
  ("City1", "City2", "SUV", "VF1244", "84", "2020-02-01"),
  ("City3", "City1", "Sedan", "EW1248", "124", "2020-02-01"),
  ("City2", "City1", "Hatchback", "GE576", "82", "2020-02-01"),
  ("City3", "City2", "Sedan", "PK2144", "104", "2020-02-01"),
  ("City3", "City1", "Hatchback", "PJ1244", "118", "2020-02-01"),
  ("City3", "City2", "SUV", "WF0976", "98", "2020-02-01"),
  ("City1", "City2", "Sedan", "WE876", "78", "2020-02-01"),
  ("City2", "City1", "Hatchback", "AB5467", "80", "2020-02-01")
))
val inputDf = spark.createDataFrame(inputRdd).toDF("origin", "destination", "vehicleType", "uniqueId", "distanceTravelled", "date")
</code>```

Sample Output:

csv file 1:

```<code>origin,destination,vehicleType,uniqueId,distanceTravelled,date
City1,City2,Sedan,AE1235,80,2020-02-01
City1,City2,Hatchback,VI3415,85,2020-02-01
City1,City2,SUV,VF1244,84,2020-02-01
City1,City2,Sedan,WE876,78,2020-02-01
</code>```

csv file 2:

```<code>origin,destination,vehicleType,uniqueId,distanceTravelled,date
City3,City1,Sedan,YU3456,120,2020-02-01
City3,City1,Sedan,EW1248,124,2020-02-01
City3,City1,Hatchback,PJ1244,118,2020-02-01
</code>```

csv file 3:

```<code>origin,destination,vehicleType,uniqueId,distanceTravelled,date
City2,City1,SUV,PO1234,75,2020-02-01
City2,City1,Hatchback,GE576,82,2020-02-01
City2,City1,Hatchback,AB5467,80,2020-02-01
</code>```

So far I've tried getting the unique combinations into a tuple and then using a foreach on it, filtering the inputDf each time saving the filtered dataframe to csv

```<code>val tuple = inputDf.groupBy("origin","destination").count()
  .select("origin","destination").rdd.map(r => (r(0),r(1))).collect

tuple.foreach(row => {
  val origin = row._1
  val destination = row._2
  val dataToWrite = inputDf.filter(inputDf.col("origin").equalTo(origin) && inputDf.col("destination").equalTo(destination))
  dataToWrite.repartition(1).write.mode("overwrite").format("csv").option("header", "true").save("/path/to/output/folder/" + origin + "-" + destination + ".csv")
})
</code>```

This approach takes a lot of time as it involves filtering the inputDf every single time as the number of unique combinations are pretty huge. What would be an optimal way to do it?

EDIT:
Each inputDf will have data only for one date.

The output should contain files at date level.

Like:

/output/City1-City2/2020-02-01.csv

/output/City1-City2/2020-02-02.csv

/output/City1-City2/2020-02-03.csv

/output/City3-City1/2020-02-01.csv

/output/City3-City1/2020-02-02.csv

... and so on

答:
You can use partitionBy and divide data in separate csv file as per your combination. I have used coalesce to keep all data into one csv file which is not recommended if you have large data.  GO through below code which will write all  possible combination into separate csv files.

```<code>    scala> df.show()
+------+-----------+-----------+--------+-----------------+----------+
|origin|destination|vehicleType|uniqueId|distanceTravelled|      date|
+------+-----------+-----------+--------+-----------------+----------+
| City1|      City2|      Sedan|  AE1235|               80|2020-02-01|
| City2|      City3|  Hatchback|  XY5434|              100|2020-02-01|
| City3|      City1|      Sedan|  YU3456|              120|2020-02-01|
| City3|      City2|      Sedan|  BV3555|              105|2020-02-01|
| City2|      City1|        SUV|  PO1234|               75|2020-02-01|
| City1|      City3|        SUV|  TY4123|              125|2020-02-01|
| City1|      City2|  Hatchback|  VI3415|               85|2020-02-02|
| City1|      City2|        SUV|  VF1244|               84|2020-02-02|
| City3|      City1|      Sedan|  EW1248|              124|2020-02-02|
| City2|      City1|  Hatchback|   GE576|               82|2020-02-02|
| City3|      City2|      Sedan|  PK2144|              104|2020-02-02|
| City3|      City1|  Hatchback|  PJ1244|              118|2020-02-02|
| City3|      City2|        SUV|  WF0976|               98|2020-02-02|
| City1|      City2|      Sedan|   WE876|               78|2020-02-02|
| City2|      City1|  Hatchback|  AB5467|               80|2020-02-02|
+------+-----------+-----------+--------+-----------------+----------+

scala> val df1 = df.withColumn("combination", concat(col("origin") ,lit("-"), col("destination")))

scala> df1.coalesce(1).write.partitionBy("combination","date").format("csv").option("header", "true").mode("overwrite").save("/stackOut/")
</code>```

Output will be like:

Body:
I've the inputDf that I need to divide based on the columns origin and destination and save each unique combination into a different csv file.

(Using Spark 2.4.4)

val spark: SparkSession = SparkSession.builder().appName("Test").getOrCreate()

val inputRdd: RDD[(String, String, String, String, String, String)] = spark.sparkContext.parallelize(Seq(
  ("City1", "City2", "Sedan", "AE1235", "80", "2020-02-01"),
  ("City2", "City3", "Hatchback", "XY5434", "100", "2020-02-01"),
  ("City3", "City1", "Sedan", "YU3456", "120", "2020-02-01"),
  ("City3", "City2", "Sedan", "BV3555", "105", "2020-02-01"),
  ("City2", "City1", "SUV", "PO1234", "75", "2020-02-01"),
  ("City1", "City3", "SUV", "TY4123", "125", "2020-02-01"),
  ("City1", "City2", "Hatchback", "VI3415", "85", "2020-02-01"),
  ("City1", "City2", "SUV", "VF1244", "84", "2020-02-01"),
  ("City3", "City1", "Sedan", "EW1248", "124", "2020-02-01"),
  ("City2", "City1", "Hatchback", "GE576", "82", "2020-02-01"),
  ("City3", "City2", "Sedan", "PK2144", "104", "2020-02-01"),
  ("City3", "City1", "Hatchback", "PJ1244", "118", "2020-02-01"),
  ("City3", "City2", "SUV", "WF0976", "98", "2020-02-01"),
  ("City1", "City2", "Sedan", "WE876", "78", "2020-02-01"),
  ("City2", "City1", "Hatchback", "AB5467", "80", "2020-02-01")
))
val inputDf = spark.createDataFrame(inputRdd).toDF("origin", "destination", "vehicleType", "uniqueId", "distanceTravelled", "date")

Sample Output:

csv file 1:

origin,destination,vehicleType,uniqueId,distanceTravelled,date
City1,City2,Sedan,AE1235,80,2020-02-01
City1,City2,Hatchback,VI3415,85,2020-02-01
City1,City2,SUV,VF1244,84,2020-02-01
City1,City2,Sedan,WE876,78,2020-02-01

csv file 2:

origin,destination,vehicleType,uniqueId,distanceTravelled,date
City3,City1,Sedan,YU3456,120,2020-02-01
City3,City1,Sedan,EW1248,124,2020-02-01
City3,City1,Hatchback,PJ1244,118,2020-02-01

csv file 3:

origin,destination,vehicleType,uniqueId,distanceTravelled,date
City2,City1,SUV,PO1234,75,2020-02-01
City2,City1,Hatchback,GE576,82,2020-02-01
City2,City1,Hatchback,AB5467,80,2020-02-01

So far I've tried getting the unique combinations into a tuple and then using a foreach on it, filtering the inputDf each time saving the filtered dataframe to csv

val tuple = inputDf.groupBy("origin","destination").count()
  .select("origin","destination").rdd.map(r => (r(0),r(1))).collect

tuple.foreach(row => {
  val origin = row._1
  val destination = row._2
  val dataToWrite = inputDf.filter(inputDf.col("origin").equalTo(origin) && inputDf.col("destination").equalTo(destination))
  dataToWrite.repartition(1).write.mode("overwrite").format("csv").option("header", "true").save("/path/to/output/folder/" + origin + "-" + destination + ".csv")
})

This approach takes a lot of time as it involves filtering the inputDf every single time as the number of unique combinations are pretty huge. What would be an optimal way to do it?

EDIT:
Each inputDf will have data only for one date.

The output should contain files at date level.

Like:

/output/City1-City2/2020-02-01.csv

/output/City1-City2/2020-02-02.csv

/output/City1-City2/2020-02-03.csv

/output/City3-City1/2020-02-01.csv

/output/City3-City1/2020-02-02.csv

... and so on

Body:
You can use partitionBy and divide data in separate csv file as per your combination. I have used coalesce to keep all data into one csv file which is not recommended if you have large data.  GO through below code which will write all  possible combination into separate csv files.

    scala> df.show()
+------+-----------+-----------+--------+-----------------+----------+
|origin|destination|vehicleType|uniqueId|distanceTravelled|      date|
+------+-----------+-----------+--------+-----------------+----------+
| City1|      City2|      Sedan|  AE1235|               80|2020-02-01|
| City2|      City3|  Hatchback|  XY5434|              100|2020-02-01|
| City3|      City1|      Sedan|  YU3456|              120|2020-02-01|
| City3|      City2|      Sedan|  BV3555|              105|2020-02-01|
| City2|      City1|        SUV|  PO1234|               75|2020-02-01|
| City1|      City3|        SUV|  TY4123|              125|2020-02-01|
| City1|      City2|  Hatchback|  VI3415|               85|2020-02-02|
| City1|      City2|        SUV|  VF1244|               84|2020-02-02|
| City3|      City1|      Sedan|  EW1248|              124|2020-02-02|
| City2|      City1|  Hatchback|   GE576|               82|2020-02-02|
| City3|      City2|      Sedan|  PK2144|              104|2020-02-02|
| City3|      City1|  Hatchback|  PJ1244|              118|2020-02-02|
| City3|      City2|        SUV|  WF0976|               98|2020-02-02|
| City1|      City2|      Sedan|   WE876|               78|2020-02-02|
| City2|      City1|  Hatchback|  AB5467|               80|2020-02-02|
+------+-----------+-----------+--------+-----------------+----------+

scala> val df1 = df.withColumn("combination", concat(col("origin") ,lit("-"), col("destination")))

scala> df1.coalesce(1).write.partitionBy("combination","date").format("csv").option("header", "true").mode("overwrite").save("/stackOut/")

Output will be like:


来源: stackexchange

问:
React - correct syntax to use a prop with a prefix as an ID for an element?
What's the correct syntax to use a prop for an element id except but with a prefix. Do I have to assign each to a variable and use a string literal, or can I do it inline?

e.g.

```<code><input id="first_{id}" type="text" value={firstName} />
<input id="last_{id}" type="text" value={lastName} />
</code>```

答:
Use ${} outside your value, which is called template literals in javascript

```<code>{`your-prefix-${yourValue}`}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What's the correct syntax to use a prop for an element id except but with a prefix. Do I have to assign each to a variable and use a string literal, or can I do it inline?

e.g.

<input id="first_{id}" type="text" value={firstName} />
<input id="last_{id}" type="text" value={lastName} />

Body:
Use ${} outside your value, which is called template literals in javascript

{`your-prefix-${yourValue}`}


问:
session_regenerate_id(): Cannot regenerate session id - headers already sent in
it is outputting: session_regenerate_id(): Cannot regenerate session id - headers already sent in</p>

```<code>session_start();

session_regenerate_id();
$_SESSION['inside'] = TRUE;
$_SESSION['username'] = $GettedName;
$_SESSION['id'] = $ID;
$_SESSION['email'] = $sirname ;
$_SESSION['sirname '] = $sirname ;
</code>```

答:
There are few reason for session already send error. Please trey with ob_start();</p>

```<code>ob_start();
session_start();
session_regenerate_id();
$_SESSION['inside'] = TRUE;
$_SESSION['username'] = $GettedName;
$_SESSION['id'] = $ID;
$_SESSION['email'] = $sirname;
$_SESSION['sirname '] = $sirname;
</code>```

Body:
it is outputting: session_regenerate_id(): Cannot regenerate session id - headers already sent in

session_start();

session_regenerate_id();
$_SESSION['inside'] = TRUE;
$_SESSION['username'] = $GettedName;
$_SESSION['id'] = $ID;
$_SESSION['email'] = $sirname ;
$_SESSION['sirname '] = $sirname ;

Body:
There are few reason for session already send error. Please trey with ob_start();

ob_start();
session_start();
session_regenerate_id();
$_SESSION['inside'] = TRUE;
$_SESSION['username'] = $GettedName;
$_SESSION['id'] = $ID;
$_SESSION['email'] = $sirname;
$_SESSION['sirname '] = $sirname;


问:
Dynamically Change API Environments Google Rollout Track
I'm developing an Ionic(3 / 4)(Angular 4 - 7)-Cordova / Capacitor Cross Platform Application(s). I'm interested in switching API env based on the current rollout track in the Google Play Store. For example, once an application has been successfully tested and recommended to continue staging/production. I would like to have the API env dynamically changed (e.g., using a different URI domain to connect to REST API ) dependent on the Google Play Store Track.

I'm aware that I can use Google Developer Play Store API to identify / list versions and available tracks yet, I'm unaware if there's already an implementation or solution. I'm perfectly willing to design a solution though, I figure I find out if it's been done already rather than reinvent the wheel.

I'm hoping to implement a solution either to the REST API BACKEND or in the ionic framework layer rather than an integration at the native layer for scalability per-project. The purpose of doing this would enable CI rather than rebuilding the project and change the API URI domain for every environment. Any assistance in this matter would be greatly appreciated.

答:
So, if anyone's interested. The approach highlighted above is possible, couldn't get an answer so I just created something. Using Google Play Developer API. The process flow is as follows:
    []

For now it's a working prototype perhaps its not very efficient; I suppose it can be improved if the request was issued from a single server, or microservice. Though, I wanted to make the code recyclable and it's isolated from both the mobile application & Node Server.

If you are interested in learning more or would like to work on project. Please feel free to contact me.


问:
PDO connection error when running PHINX migration on a Docker Container
I am trying to run a migration using Phinx from my host machine (OSX Sierra) but I keep getting PDO connection error. It's a simple LAMP stack and is working fine otherwise.

Here is my docker-compose:

```<code>version: '2'
services:
  apache:
    build:
      context: ./docker/apache-php7
      dockerfile: Dockerfile
    volumes:
      - ./app:/var/www
    ports:
      - "80:80"
      - "443:443"
    networks:
     - localnet
    links:
    - mysql
  mysql:
    image: mysql:5.7
    ports:
     - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_DATABASE: "root"
      MYSQL_USER: "root"
      MYSQL_PASSWORD: "root"
    volumes:
     - ./db/mysql:/var/lib/mysql
    networks:
     - localnet
networks:
  localnet:
    driver: "bridge"
volumes:
  mysqldata:
    driver: "local"
  redisdata:
    driver: "local"
</code>```

My folder strucutre is as follows:

```<code>/app
/db/mysql
/docker
docker-compose.yml
</code>```

My phinx.yml:

```<code>paths:
    migrations: %%PHINX_CONFIG_DIR%%
    seeds: %%PHINX_CONFIG_DIR%%

environments:
    default_migration_table: phinxlog
    default_database: docker
    production:
        adapter: mysql
        host: localhost
        name: %%PHINX_DBNAME%%
        user: %%PHINX_DBUSER%%
        pass: %%PHINX_DBPASS%%
        port: 3306
        charset: utf8

    development:
        adapter: mysql
        host: localhost
        name: %%PHINX_DBNAME%%
        user: %%PHINX_DBUSER%%
        pass: %%PHINX_DBPASS%%
        port: 3306
        charset: utf8

    docker:
        adapter: mysql
        host: mysql
        name: foo_db
        user: root
        pass: root
        port: 3306
        charset: utf8
</code>```

Here is the output I get when I run the command (php ~/projects/project/app/vendor/bin/phinx migrate) from my host machine.

```<code>using config file ./phinx.yml
using config parser yaml
using migration paths
 - /Users/foo/projects/project/app/migrations
using seed paths
 - /Users/foo/projects/project/app/migrations
warning no environment specified, defaulting to: docker
using adapter mysql
using database foo_db

[InvalidArgumentException]
  There was a problem connecting to the database: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known
</code>```

I have tried rebuilding the image, tried other images but just doesn't seem to work. I can connect to the Docker MySQL from my host machine using SequelPro with the following configuration:

```<code> Host: 0.0.0.0
 Username: root
 Password: root
 Databse:
 Port: 3306
</code>```

What do I need to do/fix in order run these Phinx migrations on the MySQL container from my host machine as the alternative would be to use another Docker Container which I am trying to avoid?

答:
As you said you are running the command from your host machine, this is the problem. First login into your docker container on terminal by using command :
docker exec -it {container_id} sh ,
then go to your project folder and run phinx command.
sharing phinx.yml file below for reference -
(make sure migration path should be your docker folder path )

paths:
    migrations: /cars/engine/dealerengine/migrations

environments:
    default_migration_table: phinxlog
    default_database: docker

```<code>production:
    adapter: mysql
    host: localhost
    name: production_db
    user: root
    pass: ''
    port: 3306
    charset: utf8

docker:
    adapter: mysql
    host: mysql
    name: dealerengine
    user: root
    pass: root
    port: 3306
    charset: utf8

testing:
    adapter: mysql
    host: localhost
    name: testing_db
    user: root
    pass: ''
    port: 3306
    charset: utf8
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run a migration using Phinx from my host machine (OSX Sierra) but I keep getting PDO connection error. It's a simple LAMP stack and is working fine otherwise.

Here is my docker-compose:

version: '2'
services:
  apache:
    build:
      context: ./docker/apache-php7
      dockerfile: Dockerfile
    volumes:
      - ./app:/var/www
    ports:
      - "80:80"
      - "443:443"
    networks:
     - localnet
    links:
    - mysql
  mysql:
    image: mysql:5.7
    ports:
     - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: "root"
      MYSQL_DATABASE: "root"
      MYSQL_USER: "root"
      MYSQL_PASSWORD: "root"
    volumes:
     - ./db/mysql:/var/lib/mysql
    networks:
     - localnet
networks:
  localnet:
    driver: "bridge"
volumes:
  mysqldata:
    driver: "local"
  redisdata:
    driver: "local"

My folder strucutre is as follows:

/app
/db/mysql
/docker
docker-compose.yml

My phinx.yml:

paths:
    migrations: %%PHINX_CONFIG_DIR%%
    seeds: %%PHINX_CONFIG_DIR%%

environments:
    default_migration_table: phinxlog
    default_database: docker
    production:
        adapter: mysql
        host: localhost
        name: %%PHINX_DBNAME%%
        user: %%PHINX_DBUSER%%
        pass: %%PHINX_DBPASS%%
        port: 3306
        charset: utf8

    development:
        adapter: mysql
        host: localhost
        name: %%PHINX_DBNAME%%
        user: %%PHINX_DBUSER%%
        pass: %%PHINX_DBPASS%%
        port: 3306
        charset: utf8

    docker:
        adapter: mysql
        host: mysql
        name: foo_db
        user: root
        pass: root
        port: 3306
        charset: utf8

Here is the output I get when I run the command (php ~/projects/project/app/vendor/bin/phinx migrate) from my host machine.

using config file ./phinx.yml
using config parser yaml
using migration paths
 - /Users/foo/projects/project/app/migrations
using seed paths
 - /Users/foo/projects/project/app/migrations
warning no environment specified, defaulting to: docker
using adapter mysql
using database foo_db

[InvalidArgumentException]
  There was a problem connecting to the database: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known

I have tried rebuilding the image, tried other images but just doesn't seem to work. I can connect to the Docker MySQL from my host machine using SequelPro with the following configuration:

 Host: 0.0.0.0
 Username: root
 Password: root
 Databse:
 Port: 3306

What do I need to do/fix in order run these Phinx migrations on the MySQL container from my host machine as the alternative would be to use another Docker Container which I am trying to avoid?

Body:
As you said you are running the command from your host machine, this is the problem. First login into your docker container on terminal by using command :
docker exec -it {container_id} sh ,
then go to your project folder and run phinx command.
sharing phinx.yml file below for reference -
(make sure migration path should be your docker folder path )

paths:
    migrations: /cars/engine/dealerengine/migrations

environments:
    default_migration_table: phinxlog
    default_database: docker

production:
    adapter: mysql
    host: localhost
    name: production_db
    user: root
    pass: ''
    port: 3306
    charset: utf8

docker:
    adapter: mysql
    host: mysql
    name: dealerengine
    user: root
    pass: root
    port: 3306
    charset: utf8

testing:
    adapter: mysql
    host: localhost
    name: testing_db
    user: root
    pass: ''
    port: 3306
    charset: utf8


问:
How to use Android View Binding with RecyclerView
This is not data binding, this is View binding which is new to Android Studio 3.6 Canary 11+ described here.

For using inside an Activity it is clear, you just use it like this:

Let's say we have a layout named activity_main.xml

Then in the code we can use it like this:

```<code>public class MainActivity extends Activity{

    ActivityMainBinding binding; //Name of the layout in camel case + "Binding"

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }
}
</code>```

However, It's not clear how to use View Binding with RecyclerView?

Edit: Please explain in Java.

答:
Let's say we have a RecyclerView inside activity_main.xml and its id is "@+id/rv_test"

Inside the Activity we can use it like so:

```<code>public class MainActivity extends Activity{

    ActivityMainBinding binding; //Name of the layout in camel case + "Binding"

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        binding.rvTest.setLayoutManager(layoutManager);
    }
}
</code>```

Let's name the layout for RecyclerView items test_list_item.xml

Then we can implement our adapter inside Activity like this:

```<code>public class MainActivity extends Activity{

    ActivityMainBinding binding; //Name of the layout in camel case + "Binding"

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        binding.rvTest.setLayoutManager(layoutManager);

        List<String> items = Arrays.asList("item", "item", "item");

        binding.rvTest.setAdapter(new MyAdapter(items));
    }

    private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{

        private List<String> items;

        private class MyViewHolder extends RecyclerView.ViewHolder{

            TestListItemBinding binding;//Name of the test_list_item.xml in camel case + "Binding"

            public MyViewHolder(TestListItemBinding b){
                super(b.getRoot());
                binding = b;
            }
        }

        public MyAdapter(List<String> items){
            this.items = items;
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){
            return new MyViewHolder(TestListItemBinding.inflate(getLayoutInflater()));
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position){
            String text = String.format(Locale.ENGLISH, "%s %d", items.get(position), position);

            //An example of how to use the bindings
            holder.binding.tvTest.setText(text);
        }

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

}
</code>```

Body:
This is not data binding, this is View binding which is new to Android Studio 3.6 Canary 11+ described here.

For using inside an Activity it is clear, you just use it like this:

Let's say we have a layout named activity_main.xml

Then in the code we can use it like this:

public class MainActivity extends Activity{

    ActivityMainBinding binding; //Name of the layout in camel case + "Binding"

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
    }
}

However, It's not clear how to use View Binding with RecyclerView?

Edit: Please explain in Java.

Body:
Let's say we have a RecyclerView inside activity_main.xml and its id is "@+id/rv_test"

Inside the Activity we can use it like so:

public class MainActivity extends Activity{

    ActivityMainBinding binding; //Name of the layout in camel case + "Binding"

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        binding.rvTest.setLayoutManager(layoutManager);
    }
}

Let's name the layout for RecyclerView items test_list_item.xml

Then we can implement our adapter inside Activity like this:

public class MainActivity extends Activity{

    ActivityMainBinding binding; //Name of the layout in camel case + "Binding"

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        binding.rvTest.setLayoutManager(layoutManager);

        List<String> items = Arrays.asList("item", "item", "item");

        binding.rvTest.setAdapter(new MyAdapter(items));
    }

    private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{

        private List<String> items;

        private class MyViewHolder extends RecyclerView.ViewHolder{

            TestListItemBinding binding;//Name of the test_list_item.xml in camel case + "Binding"

            public MyViewHolder(TestListItemBinding b){
                super(b.getRoot());
                binding = b;
            }
        }

        public MyAdapter(List<String> items){
            this.items = items;
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){
            return new MyViewHolder(TestListItemBinding.inflate(getLayoutInflater()));
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position){
            String text = String.format(Locale.ENGLISH, "%s %d", items.get(position), position);

            //An example of how to use the bindings
            holder.binding.tvTest.setText(text);
        }

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

}


问:
Azure- zip push deployment for a function app doesn't work
I am trying to update the code in my App Function from the CLI using the kudu zip push deployment for a function app.
I am using this command-

```<code>az functionapp deployment source config-zip --name funcApp1 --resource-group MyGroup --src C:\Users\user\Documents\funcApp1.zip
</code>```

And getting this output-

```<code>Getting scm site credentials for zip deployment Starting zip deployment. This operation can take a while to complete ... Deployment endpoint responded with status code 202
</code>```

It looks like it worked but I can't see the updated code in the App Function from the CLI.
What can be the problem?

答:
facing the same issue and I am using below command

```<code>az functionapp deployment source config-zip -g clitesting4 -n zeroclitrigger --src D:\latestcli\functionapp.zip --build-remote true
</code>```

I think it is related to either a folder structure or some file missing issue as my runtime is python I am using below folder structure.

```<code>__app__
 | - MyFirstFunction
 | | - __init__.py
 | | - function.json
 | | - example.py
 | - MySecondFunction
 | | - __init__.py
 | | - function.json
 | - SharedCode
 | | - myFirstHelperFunction.py
 | | - mySecondHelperFunction.py
 | - host.json
 | - requirements.txt
 tests
</code>```

all the files I got from vscode . I am not using any ARM template

Body:
I am trying to update the code in my App Function from the CLI using the kudu zip push deployment for a function app.
I am using this command-

az functionapp deployment source config-zip --name funcApp1 --resource-group MyGroup --src C:\Users\user\Documents\funcApp1.zip

And getting this output-

Getting scm site credentials for zip deployment Starting zip deployment. This operation can take a while to complete ... Deployment endpoint responded with status code 202

It looks like it worked but I can't see the updated code in the App Function from the CLI.
What can be the problem?

Body:
facing the same issue and I am using below command

az functionapp deployment source config-zip -g clitesting4 -n zeroclitrigger --src D:\latestcli\functionapp.zip --build-remote true

I think it is related to either a folder structure or some file missing issue as my runtime is python I am using below folder structure.

__app__
 | - MyFirstFunction
 | | - __init__.py
 | | - function.json
 | | - example.py
 | - MySecondFunction
 | | - __init__.py
 | | - function.json
 | - SharedCode
 | | - myFirstHelperFunction.py
 | | - mySecondHelperFunction.py
 | - host.json
 | - requirements.txt
 tests

all the files I got from vscode . I am not using any ARM template


问:
Get fields from through table in Django
I have two models, organization and vendor, which are connected by a 'relational' or 'through' table, VendorOrganization. There is a field description in my through table, which I am trying to access, but do not know. How should I configure my view, query and serializer to be able to access fields from the through table? Thanks for any help!

// models.py

```<code>class Organization(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20, unique=True, validators=[alphanumeric_plus_underscore, MinLengthValidator(4)])
    vendors = models.ManyToManyField("thirdparty.Vendor", through="thirdparty.VendorOrganization")

class Vendor(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=60, blank=False, null=False)

class VendorOrganization(models.Model):
    vendor = models.ForeignKey(Vendor, blank=False, null=False, on_delete=models.CASCADE)
    organization = models.ForeignKey(Organization, blank=True, null=False, on_delete=models.DO_NOTHING)
    created_at = models.DateTimeField(_('created at'), auto_now_add=True, null=True)
    created_by_user = models.ForeignKey(User, blank=False, null=False, on_delete=models.DO_NOTHING)
    description = models.CharField(max_length=300, blank=True, null=False)
</code>```

// serializers.py (this does not work to get the 'description' field)

```<code>class VendorSerializer(serializers.ModelSerializer):

class Meta:
    model = Vendor
    fields = ('id', 'name', 'created_at', 'created_by_user', 'description')
    extra_kwargs = {
        'id': {'read_only': True},
        'created_at': {'read_only': True},
    }
</code>```

// views.py

```<code>class VendorView(mixins.DestroyModelMixin, ListAPIView):
    authentication_classes = (TokenAuthentication,)

    def get(self, request):

        pagination_class = None
        current_org = Organization.objects.get(id=request.user.organization.id)
        queryset = current_org.vendors.select_related()
        vendors = VendorSerializer(queryset, many=True)
        return Response(vendors.data)
</code>```

答: In serializer.py change the model from Vendor to VendorOrganization. Because you are referencing both through that model</p>

Title: Get fields from through table in Django

Body:
I have two models, organization and vendor, which are connected by a 'relational' or 'through' table, VendorOrganization. There is a field description in my through table, which I am trying to access, but do not know. How should I configure my view, query and serializer to be able to access fields from the through table? Thanks for any help!

// models.py

class Organization(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=20, unique=True, validators=[alphanumeric_plus_underscore, MinLengthValidator(4)])
    vendors = models.ManyToManyField("thirdparty.Vendor", through="thirdparty.VendorOrganization")

class Vendor(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=60, blank=False, null=False)

class VendorOrganization(models.Model):
    vendor = models.ForeignKey(Vendor, blank=False, null=False, on_delete=models.CASCADE)
    organization = models.ForeignKey(Organization, blank=True, null=False, on_delete=models.DO_NOTHING)
    created_at = models.DateTimeField(_('created at'), auto_now_add=True, null=True)
    created_by_user = models.ForeignKey(User, blank=False, null=False, on_delete=models.DO_NOTHING)
    description = models.CharField(max_length=300, blank=True, null=False)

// serializers.py (this does not work to get the 'description' field)

class VendorSerializer(serializers.ModelSerializer):

class Meta:
    model = Vendor
    fields = ('id', 'name', 'created_at', 'created_by_user', 'description')
    extra_kwargs = {
        'id': {'read_only': True},
        'created_at': {'read_only': True},
    }

// views.py

class VendorView(mixins.DestroyModelMixin, ListAPIView):
    authentication_classes = (TokenAuthentication,)

    def get(self, request):

        pagination_class = None
        current_org = Organization.objects.get(id=request.user.organization.id)
        queryset = current_org.vendors.select_related()
        vendors = VendorSerializer(queryset, many=True)
        return Response(vendors.data)


问:
How to fix "ReferenceError: primordials is not defined" in Node.js
I have installed Node.js modules by 'npm install', and then I tried to do gulp sass-watch in a command prompt. After that, I got the below response.

[18:18:32] Requiring external module babel-register
fs.js:27
const { Math, Object, Reflect } = primordials;
                                  ^

ReferenceError: primordials is not defined
```
<p>I have tried this before <code>gulp sass-watch</code>:</p>
<pre class="lang-none prettyprint-override"><code>npm -g install gulp-cli
</code>```

答:
This error is because of the new version of Node.js (12) and an old version of Gulp (less than 4).

Downgrading Node.js and other dependencies isn't recommended. I solved this by updating package.json file, fetching the latest version of all dependencies. For this, I use npm-check-updates. It is a module that updates the package.json with the latest version of all dependencies.

Reference: https://www.npmjs.com/package/npm-check-updates

```<code>npm i -g npm-check-updates
ncu -u
npm install
</code>```

In most cases, we will have to update the gulpfile.js as well like the following:

Reference: Gulp 4: The new task execution system - gulp.parallel and gulp.series, Migration

Before:

```<code>gulp.task(
    'sass', function () {
        return gulp.src([sourcePath + '/sass/**/*.scss', "!" + sourcePath + "/sass/**/_*.scss"])

            ....
    }
);

Other configuration...

gulp.task(
    'watch', function () {
        gulp.watch(sourcePath + '/sass/**/*.scss', ['sass']);
    }
);
</code>```

After:

```<code>gulp.task('sass', gulp.series(function(done) {
    return gulp.src([sourcePath + '/sass/**/*.scss', "!" + sourcePath + "/sass/**/_*.scss"])

            ...

    done();
}));

Other config...

gulp.task(
    'watch', function () {
        gulp.watch(sourcePath + '/sass/**/*.scss', gulp.series('sass'));
    }
);
</code>```

Body:
I have installed Node.js modules by 'npm install', and then I tried to do gulp sass-watch in a command prompt. After that, I got the below response.

[18:18:32] Requiring external module babel-register
fs.js:27
const { Math, Object, Reflect } = primordials;
                                  ^

ReferenceError: primordials is not defined

I have tried this before gulp sass-watch:

npm -g install gulp-cli

Body:
This error is because of the new version of Node.js (12) and an old version of Gulp (less than 4).

Downgrading Node.js and other dependencies isn't recommended. I solved this by updating package.json file, fetching the latest version of all dependencies. For this, I use npm-check-updates. It is a module that updates the package.json with the latest version of all dependencies.

Reference: https://www.npmjs.com/package/npm-check-updates

npm i -g npm-check-updates
ncu -u
npm install

In most cases, we will have to update the gulpfile.js as well like the following:

Reference: Gulp 4: The new task execution system - gulp.parallel and gulp.series, Migration

Before:

gulp.task(
    'sass', function () {
        return gulp.src([sourcePath + '/sass/**/*.scss', "!" + sourcePath + "/sass/**/_*.scss"])

            ....
    }
);

Other configuration...

gulp.task(
    'watch', function () {
        gulp.watch(sourcePath + '/sass/**/*.scss', ['sass']);
    }
);

After:

gulp.task('sass', gulp.series(function(done) {
    return gulp.src([sourcePath + '/sass/**/*.scss', "!" + sourcePath + "/sass/**/_*.scss"])

            ...

    done();
}));

Other config...

gulp.task(
    'watch', function () {
        gulp.watch(sourcePath + '/sass/**/*.scss', gulp.series('sass'));
    }
);


问:
Apache Beam create timeseries from event stream
I am trying to create a timeseries of the count of events that happened over a given time.

The events are encoded as

```<code>PCollection<KV<String, Long>> events;
</code>```

Where the String is the id of the event source, and long is the timestamp of the event.

What I want out is a PCollection<Timeseries> of timeseries that have the form

```<code>class Timeseries  {
  String id;
  List<TimeseriesWindow> windows;
}

class TimeseriesWindow  {
  long timestamp;
  long count;
}
</code>```

Toy example with a fixed window size (is this the correct term?) of 10 seconds, and an total timeseries duration of 60 seconds:

Input:

```<code>[("one", 1), ("one", 13), ("one", 2), ("one", 43), ("two", 3)]
</code>```

Output:

```<code>[
  {
    id: "one"
    windows: [
      {
        timestamp: 0,
        count: 2
      },
      {
        timestamp: 10,
        count: 1
      },
      {
        timestamp: 20,
        count: 0
      },
      {
        timestamp: 30,
        count: 0
      },
      {
        timestamp: 40,
        count: 1
      },
      {
        timestamp: 50,
        count: 0
      }
    ]
  },
  {
    id: "two"
    windows: [
      {
        timestamp: 0,
        count: 1
      },
      {
        timestamp: 10,
        count: 0
      },
      {
        timestamp: 20,
        count: 0
      },
      {
        timestamp: 30,
        count: 0
      },
      {
        timestamp: 40,
        count: 0
      },
      {
        timestamp: 50,
        count: 0
      }
    ]
  }
]
</code>```

I hope this makes sense :)

答:
You can do a GroupByKey to transform your input into

```<code>[
    ("one", [1, 13, 2, 43]),
    ("two", [3]),
]
</code>```

at which point you can apply a DoFn to convert the list of integers into a Timeseries object (e.g. by creating the list of TimeseriesWindow at the appropriate times, and then iterating over the values incrementing the counts.)

You may also look into the builtin windowing capabilities to see if that will meet your needs.

Body:
I am trying to create a timeseries of the count of events that happened over a given time.

The events are encoded as

PCollection<KV<String, Long>> events;

Where the String is the id of the event source, and long is the timestamp of the event.

What I want out is a PCollection<Timeseries> of timeseries that have the form

class Timeseries  {
  String id;
  List<TimeseriesWindow> windows;
}

class TimeseriesWindow  {
  long timestamp;
  long count;
}

Toy example with a fixed window size (is this the correct term?) of 10 seconds, and an total timeseries duration of 60 seconds:

Input:

[("one", 1), ("one", 13), ("one", 2), ("one", 43), ("two", 3)]

Output:

[
  {
    id: "one"
    windows: [
      {
        timestamp: 0,
        count: 2
      },
      {
        timestamp: 10,
        count: 1
      },
      {
        timestamp: 20,
        count: 0
      },
      {
        timestamp: 30,
        count: 0
      },
      {
        timestamp: 40,
        count: 1
      },
      {
        timestamp: 50,
        count: 0
      }
    ]
  },
  {
    id: "two"
    windows: [
      {
        timestamp: 0,
        count: 1
      },
      {
        timestamp: 10,
        count: 0
      },
      {
        timestamp: 20,
        count: 0
      },
      {
        timestamp: 30,
        count: 0
      },
      {
        timestamp: 40,
        count: 0
      },
      {
        timestamp: 50,
        count: 0
      }
    ]
  }
]

I hope this makes sense :)

Body:
You can do a GroupByKey to transform your input into

[
    ("one", [1, 13, 2, 43]),
    ("two", [3]),
]

at which point you can apply a DoFn to convert the list of integers into a Timeseries object (e.g. by creating the list of TimeseriesWindow at the appropriate times, and then iterating over the values incrementing the counts.)

You may also look into the builtin windowing capabilities to see if that will meet your needs.


问:
Pre-commit hook permission denied inside script
I have following pre-commit hook:

#!/bin/bash

set -e

result=''

for file in $(find rest/src/main/groovy/ru/naumen/modules -name '*.groovy' | sort); do
    filename=basename "$file"
    result+=echo "${filename//.groovy/}",
done

result+='smpUtils'

sed -i -r "s|modules = .*|modules = $result|g" rest/smpsync.ini

git add rest/smpsync.ini
```

<p>I'm getting <code>Permission denied</code> error on line 8</p>

<pre class="lang-sh prettyprint-override"><code>filename=basename "$file"
</code>```

And I'm not able to determine the reason of it.

Hook itself has execution rights (chmod +x .git/hooks/pre-commit)

Whole directories/files tree in ./rest/src/main/groovy/ru/naumen/modules has read/write rights and belongs to my user.

答:
Issue #1 was as mentioned by @VonC in variable assignment

filename=basename "$file" -> filename=$(basename "$file")

Issue #2 was in line #9 (I just removed echo):

result+=echo "${filename//.groovy/}", -> result+="${filename//.groovy/}",

Body:
I have following pre-commit hook:

#!/bin/bash

set -e

result=''

for file in $(find rest/src/main/groovy/ru/naumen/modules -name '*.groovy' | sort); do
    filename=basename "$file"
    result+=echo "${filename//.groovy/}",
done

result+='smpUtils'

sed -i -r "s|modules = .*|modules = $result|g" rest/smpsync.ini

git add rest/smpsync.ini

I'm getting Permission denied error on line 8

filename=basename "$file"

And I'm not able to determine the reason of it.

Hook itself has execution rights (chmod +x .git/hooks/pre-commit)

Whole directories/files tree in ./rest/src/main/groovy/ru/naumen/modules has read/write rights and belongs to my user.


问:
Flutter: Merge two images and store it in local storage as a single image
I want to merge two images and show & store them as a single image.</p>

答:
Found the answer, Thanks to this awesome library https://pub.dev/packages/image</p>

```<code>final image1 = decodeImage(File('imageA.jpg').readAsBytesSync());
final image2 = decodeImage(File('imageB.jpg').readAsBytesSync());
final mergedImage = Image(image1.width + image2.width, max(image1.height, image2.height));
copyInto(mergedImage, image1, blend = false);
copyInto(mergedImage, image2, dstx = image1.width, blend = false);

final documentDirectory = await getApplicationDocumentsDirectory();
final file = new File(join(documentDirectory.path, "merged_image.jpg"));
file.writeAsBytesSync(encodeJpg(mergedImage));
</code>```

Body:
Found the answer, Thanks to this awesome library https://pub.dev/packages/image

final image1 = decodeImage(File('imageA.jpg').readAsBytesSync());
final image2 = decodeImage(File('imageB.jpg').readAsBytesSync());
final mergedImage = Image(image1.width + image2.width, max(image1.height, image2.height));
copyInto(mergedImage, image1, blend = false);
copyInto(mergedImage, image2, dstx = image1.width, blend = false);

final documentDirectory = await getApplicationDocumentsDirectory();
final file = new File(join(documentDirectory.path, "merged_image.jpg"));
file.writeAsBytesSync(encodeJpg(mergedImage));


问:
Setting download directory in webdriver using JS
I want to change default download directory for chrome using JS (TypeScript). Tryed to set options like this :

let options = webdriver.ChromeOptions;

options.add_argument("download.default_directory=C:/Downloads")

let driver = webdriver.chrome(options);

But, options sets to undefined and ChromeOptions doesn't exist on webdriver.

Here is full code:

```<code>let webdriver = require('selenium-webdriver');
let chrome = require('selenium-webdriver/chrome');
let chromedriver = require('chromedriver');

chrome.setDefaultService(new chrome.ServiceBuilder(chromedriver.path).build());

// let driver = new webdriver.Builder()
//     .withCapabilities(webdriver.Capabilities.chrome())
//     .build();
let options = webdriver.ChromeOptions;

options.add_argument("download.default_directory=C:/Downloads")

let driver = webdriver.chrome(options);

let figma = 'https://www.figma.com/';
driver.get (figma).then(
    backup
);

function backup() {
    driver.sleep(3000);
    driver.quit();
}
</code>```

答:
Try below code and let me know:</p>

```<code>var chrome = require('chromedriver');
var chromeCapabilities = webdriver.Capabilities.chrome();
const chromeOption = require('selenium-webdriver/chrome');
//setting chrome options to start the browser fully maximized
var chromeOptions = {
    'args': ['--test-type', '--start-maximized'],
    'prefs': {"download.default_directory":"/home/(user)/Downloads/Chrome_test"}
};
chromeCapabilities.set('chromeOptions', chromeOptions);
var driver = new webdriver.Builder()
  .withCapabilities(chromeCapabilities)
  .build();
</code>```

Body:
I want to change default download directory for chrome using JS (TypeScript). Tryed to set options like this :

let options = webdriver.ChromeOptions;

options.add_argument("download.default_directory=C:/Downloads")

let driver = webdriver.chrome(options);

But, options sets to undefined and ChromeOptions doesn't exist on webdriver.

Here is full code:

let webdriver = require('selenium-webdriver');
let chrome = require('selenium-webdriver/chrome');
let chromedriver = require('chromedriver');

chrome.setDefaultService(new chrome.ServiceBuilder(chromedriver.path).build());

// let driver = new webdriver.Builder()
//     .withCapabilities(webdriver.Capabilities.chrome())
//     .build();
let options = webdriver.ChromeOptions;

options.add_argument("download.default_directory=C:/Downloads")

let driver = webdriver.chrome(options);

let figma = 'https://www.figma.com/';
driver.get (figma).then(
    backup
);

function backup() {
    driver.sleep(3000);
    driver.quit();
}

Body:
Try below code and let me know:

var chrome = require('chromedriver');
var chromeCapabilities = webdriver.Capabilities.chrome();
const chromeOption = require('selenium-webdriver/chrome');
//setting chrome options to start the browser fully maximized
var chromeOptions = {
    'args': ['--test-type', '--start-maximized'],
    'prefs': {"download.default_directory":"/home/(user)/Downloads/Chrome_test"}
};
chromeCapabilities.set('chromeOptions', chromeOptions);
var driver = new webdriver.Builder()
  .withCapabilities(chromeCapabilities)
  .build();


问:
Can I map resources to a different controller?
I have my resources already defined, but a client wants to change the names of the URLs to match their brand (e.g. something like "catalog" when the resource is currently "products").  Can I specify a different controller name with a resource so I can get all the built-in resources functionality without having to actually rename the controller and model names?</p>

答:
The rails guide specifies how to use specific controllers for certain routes.

You can do something like this:

```<code>Rails.application.routes.draw do
  resources :products, controller: "catalog"
  # but rails conventions suggests you should pluralise your controller name
  # so use "catalogs" (plural) instead of the singular "catalog"
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The rails guide specifies how to use specific controllers for certain routes.

You can do something like this:

Rails.application.routes.draw do
  resources :products, controller: "catalog"
  # but rails conventions suggests you should pluralise your controller name
  # so use "catalogs" (plural) instead of the singular "catalog"
end


问:
Flutter Chewie Video Player - check when playback is complete
I'm using the Chewie Video player in my Flutter app. How to check when playback has completed, so that I can close the screen and dispose?</p>

答:
You can copy paste run full code below

You can check position and duration

full code is official example set loop to false and add the following code snippet

code snippet

```<code>_videoPlayerController1.addListener(() {
      if (_videoPlayerController1.value.position ==
          _videoPlayerController1.value.duration) {
        print('video Ended');
      }
    });
</code>```

Output

```<code>I/flutter ( 4881): video Ended
</code>```

full code

```<code>import 'package:chewie/chewie.dart';
import 'package:chewie/src/chewie_player.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(
    ChewieDemo(),
  );
}

class ChewieDemo extends StatefulWidget {
  ChewieDemo({this.title = 'Chewie Demo'});

  final String title;

  @override
  State<StatefulWidget> createState() {
    return _ChewieDemoState();
  }
}

class _ChewieDemoState extends State<ChewieDemo> {
  TargetPlatform _platform;
  VideoPlayerController _videoPlayerController1;
  VideoPlayerController _videoPlayerController2;
  ChewieController _chewieController;

  @override
  void initState() {
    super.initState();
    _videoPlayerController1 = VideoPlayerController.network(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4');
    _videoPlayerController2 = VideoPlayerController.network(
        'https://www.sample-videos.com/video123/mp4/480/asdasdas.mp4');
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController1,
      aspectRatio: 3 / 2,
      autoPlay: true,
      looping: false,
      // Try playing around with some of these other options:

      // showControls: false,
      // materialProgressColors: ChewieProgressColors(
      //   playedColor: Colors.red,
      //   handleColor: Colors.blue,
      //   backgroundColor: Colors.grey,
      //   bufferedColor: Colors.lightGreen,
      // ),
      // placeholder: Container(
      //   color: Colors.grey,
      // ),
      // autoInitialize: true,
    );

    _videoPlayerController1.addListener(() {
      if (_videoPlayerController1.value.position ==
          _videoPlayerController1.value.duration) {
        print('video Ended');
      }
    });
  }

  @override
  void dispose() {
    _videoPlayerController1.dispose();
    _videoPlayerController2.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: widget.title,
      theme: ThemeData.light().copyWith(
        platform: _platform ?? Theme.of(context).platform,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: Center(
                child: Chewie(
                  controller: _chewieController,
                ),
              ),
            ),
            FlatButton(
              onPressed: () {
                _chewieController.enterFullScreen();
              },
              child: Text('Fullscreen'),
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        _chewieController.dispose();
                        _videoPlayerController2.pause();
                        _videoPlayerController2.seekTo(Duration(seconds: 0));
                        _chewieController = ChewieController(
                          videoPlayerController: _videoPlayerController1,
                          aspectRatio: 3 / 2,
                          autoPlay: true,
                          looping: true,
                        );
                      });
                    },
                    child: Padding(
                      child: Text("Video 1"),
                      padding: EdgeInsets.symmetric(vertical: 16.0),
                    ),
                  ),
                ),
                Expanded(
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        _chewieController.dispose();
                        _videoPlayerController1.pause();
                        _videoPlayerController1.seekTo(Duration(seconds: 0));
                        _chewieController = ChewieController(
                          videoPlayerController: _videoPlayerController2,
                          aspectRatio: 3 / 2,
                          autoPlay: true,
                          looping: true,
                        );
                      });
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 16.0),
                      child: Text("Error Video"),
                    ),
                  ),
                )
              ],
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        _platform = TargetPlatform.android;
                      });
                    },
                    child: Padding(
                      child: Text("Android controls"),
                      padding: EdgeInsets.symmetric(vertical: 16.0),
                    ),
                  ),
                ),
                Expanded(
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        _platform = TargetPlatform.iOS;
                      });
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 16.0),
                      child: Text("iOS controls"),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
You can copy paste run full code below

You can check position and duration

full code is official example set loop to false and add the following code snippet

code snippet

_videoPlayerController1.addListener(() {
      if (_videoPlayerController1.value.position ==
          _videoPlayerController1.value.duration) {
        print('video Ended');
      }
    });

Output

I/flutter ( 4881): video Ended

full code

import 'package:chewie/chewie.dart';
import 'package:chewie/src/chewie_player.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

void main() {
  runApp(
    ChewieDemo(),
  );
}

class ChewieDemo extends StatefulWidget {
  ChewieDemo({this.title = 'Chewie Demo'});

  final String title;

  @override
  State<StatefulWidget> createState() {
    return _ChewieDemoState();
  }
}

class _ChewieDemoState extends State<ChewieDemo> {
  TargetPlatform _platform;
  VideoPlayerController _videoPlayerController1;
  VideoPlayerController _videoPlayerController2;
  ChewieController _chewieController;

  @override
  void initState() {
    super.initState();
    _videoPlayerController1 = VideoPlayerController.network(
        'https://flutter.github.io/assets-for-api-docs/assets/videos/butterfly.mp4');
    _videoPlayerController2 = VideoPlayerController.network(
        'https://www.sample-videos.com/video123/mp4/480/asdasdas.mp4');
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController1,
      aspectRatio: 3 / 2,
      autoPlay: true,
      looping: false,
      // Try playing around with some of these other options:

      // showControls: false,
      // materialProgressColors: ChewieProgressColors(
      //   playedColor: Colors.red,
      //   handleColor: Colors.blue,
      //   backgroundColor: Colors.grey,
      //   bufferedColor: Colors.lightGreen,
      // ),
      // placeholder: Container(
      //   color: Colors.grey,
      // ),
      // autoInitialize: true,
    );

    _videoPlayerController1.addListener(() {
      if (_videoPlayerController1.value.position ==
          _videoPlayerController1.value.duration) {
        print('video Ended');
      }
    });
  }

  @override
  void dispose() {
    _videoPlayerController1.dispose();
    _videoPlayerController2.dispose();
    _chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: widget.title,
      theme: ThemeData.light().copyWith(
        platform: _platform ?? Theme.of(context).platform,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: Center(
                child: Chewie(
                  controller: _chewieController,
                ),
              ),
            ),
            FlatButton(
              onPressed: () {
                _chewieController.enterFullScreen();
              },
              child: Text('Fullscreen'),
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        _chewieController.dispose();
                        _videoPlayerController2.pause();
                        _videoPlayerController2.seekTo(Duration(seconds: 0));
                        _chewieController = ChewieController(
                          videoPlayerController: _videoPlayerController1,
                          aspectRatio: 3 / 2,
                          autoPlay: true,
                          looping: true,
                        );
                      });
                    },
                    child: Padding(
                      child: Text("Video 1"),
                      padding: EdgeInsets.symmetric(vertical: 16.0),
                    ),
                  ),
                ),
                Expanded(
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        _chewieController.dispose();
                        _videoPlayerController1.pause();
                        _videoPlayerController1.seekTo(Duration(seconds: 0));
                        _chewieController = ChewieController(
                          videoPlayerController: _videoPlayerController2,
                          aspectRatio: 3 / 2,
                          autoPlay: true,
                          looping: true,
                        );
                      });
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 16.0),
                      child: Text("Error Video"),
                    ),
                  ),
                )
              ],
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        _platform = TargetPlatform.android;
                      });
                    },
                    child: Padding(
                      child: Text("Android controls"),
                      padding: EdgeInsets.symmetric(vertical: 16.0),
                    ),
                  ),
                ),
                Expanded(
                  child: FlatButton(
                    onPressed: () {
                      setState(() {
                        _platform = TargetPlatform.iOS;
                      });
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 16.0),
                      child: Text("iOS controls"),
                    ),
                  ),
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}


问:
Git GUI like Bzr Explorer but for Git?
What GUI's are there for GIT that are like Bazaar Explorer?

Preferably for Linux.

(source: ubuntugeek.com)

Would be great to include or link to screenshots in the answers.

If you could do each app as one answer, they could be individually voted on.

答: Install bzr-git plugin for bzr and then simply use Bazaar Explorer to work with your git repositories.</p>

Title: Git GUI like Bzr Explorer but for Git?


问:
How to make a dice roller remove the last rolled race in unity
I'm using a dice rolling script to roll through different faces of my classmates as a sort of wheel of fortune system and I'm completely new to both unity and C#. I've done some googling and come up with the following code that works.

using System.Collections;
using UnityEngine;

public class Dice : MonoBehaviour
{
    // Array of dice sides sprites to load from Resources folder
    public Sprite[] diceSides;

    // Reference to sprite renderer to change sprites
    private SpriteRenderer rend;

    // Use this for initialization
    private void Start()
    {
        // Assign Renderer component
        rend = GetComponent<SpriteRenderer>();

        // Load dice sides sprites to array from DiceSides subfolder of Resources folder
        diceSides = Resources.LoadAll<Sprite>("DiceSides/");
    }

    // If you left click over the dice then RollTheDice coroutine is started
    public void OnMouseDown()
    {
        StartCoroutine("RollTheDice");
    }

    // Coroutine that rolls the dice
    private IEnumerator RollTheDice()
    {
        // Variable to contain random dice side number.
        // It needs to be assigned. Let it be 0 initially
        int randomDiceSide = 0;

        // Final side or value that dice reads in the end of coroutine
        int finalSide = 0;

        // Loop to switch dice sides ramdomly
        // before final side appears. 20 itterations here.
        Random rnd = new Random();
        for (int i = 0; i <= 20; i++)
        {
            // Pick up random value from 0 to 5 (All inclusive)
            randomDiceSide = Random.Range(0, 9);

            // Set sprite to upper face of dice from array according to random value
            rend.sprite = diceSides[randomDiceSide];

            diceSides = Resources.LoadAll<Sprite>("DiceSides/");

            // Pause before next itteration
            yield return new WaitForSeconds(0.2f);
        }

        // Assigning final side so you can use this value later in your game
        // for player movement for example
        finalSide = randomDiceSide;

        // Show final dice value in Console
        Debug.Log(finalSide);
    }
}

```

What I want to do is to make it so that when someone's face is selected they are taken out of the array. I don't really know how to do it. If you need any more details to help me out feel free to ask. Thanks in advance.

答:
At the top, add this using statement: using System.Collections.Generic;

Have a private List<Sprite> finalSideSprites variable.

In Start:  finalSideSprites = new List<Sprite>(Resources.LoadAll<Sprite>("DiceSides/"));

In RollTheDice: Replace finalSide = randomDiceSide; with

```<code>finalSide = (int)Random.Range(0, finalSideSprites.Count - 1);
rend.sprite = finalSideSprites[finalSide];
finalSideSprites.RemoveAt(finalSide);
if(finalSideSprites.Count <= 0){
    finalSideSprites = new List<Sprite>(Resources.LoadAll<Sprite>("DiceSides/"));
}
</code>```

Essentially, this keeps a list of eligible "final side" values, picks one at random, removes it from the eligible values list, then resets the list when they've all been used.

Body:
I'm using a dice rolling script to roll through different faces of my classmates as a sort of wheel of fortune system and I'm completely new to both unity and C#. I've done some googling and come up with the following code that works.

using System.Collections;
using UnityEngine;

public class Dice : MonoBehaviour
{
    // Array of dice sides sprites to load from Resources folder
    public Sprite[] diceSides;

    // Reference to sprite renderer to change sprites
    private SpriteRenderer rend;

    // Use this for initialization
    private void Start()
    {
        // Assign Renderer component
        rend = GetComponent<SpriteRenderer>();

        // Load dice sides sprites to array from DiceSides subfolder of Resources folder
        diceSides = Resources.LoadAll<Sprite>("DiceSides/");
    }

    // If you left click over the dice then RollTheDice coroutine is started
    public void OnMouseDown()
    {
        StartCoroutine("RollTheDice");
    }

    // Coroutine that rolls the dice
    private IEnumerator RollTheDice()
    {
        // Variable to contain random dice side number.
        // It needs to be assigned. Let it be 0 initially
        int randomDiceSide = 0;

        // Final side or value that dice reads in the end of coroutine
        int finalSide = 0;

        // Loop to switch dice sides ramdomly
        // before final side appears. 20 itterations here.
        Random rnd = new Random();
        for (int i = 0; i <= 20; i++)
        {
            // Pick up random value from 0 to 5 (All inclusive)
            randomDiceSide = Random.Range(0, 9);

            // Set sprite to upper face of dice from array according to random value
            rend.sprite = diceSides[randomDiceSide];

            diceSides = Resources.LoadAll<Sprite>("DiceSides/");

            // Pause before next itteration
            yield return new WaitForSeconds(0.2f);
        }

        // Assigning final side so you can use this value later in your game
        // for player movement for example
        finalSide = randomDiceSide;

        // Show final dice value in Console
        Debug.Log(finalSide);
    }
}

What I want to do is to make it so that when someone's face is selected they are taken out of the array. I don't really know how to do it. If you need any more details to help me out feel free to ask. Thanks in advance.

Body:
At the top, add this using statement: using System.Collections.Generic;

Have a private List<Sprite> finalSideSprites variable.

In Start:  finalSideSprites = new List<Sprite>(Resources.LoadAll<Sprite>("DiceSides/"));

In RollTheDice: Replace finalSide = randomDiceSide; with

finalSide = (int)Random.Range(0, finalSideSprites.Count - 1);
rend.sprite = finalSideSprites[finalSide];
finalSideSprites.RemoveAt(finalSide);
if(finalSideSprites.Count <= 0){
    finalSideSprites = new List<Sprite>(Resources.LoadAll<Sprite>("DiceSides/"));
}

Essentially, this keeps a list of eligible "final side" values, picks one at random, removes it from the eligible values list, then resets the list when they've all been used.


问:
Select Top 3 from joined tables, apply rank based on column value
Table1

```<code>ID         | JoinedStart        | CohortID | CohortName
---------- | ------------------ | -------- | ----------
1          | 20080101 01:30:00  | 1        | Peanut
1          | 20090204 01:01:00  | 2        | Apple
2          | 20190107 05:52:14  | 1        | Peanut
3          | 20190311 02:35:26  | 2        | Apple
6          | 20190311 02:35:26  | 2        | Apple
</code>```

Table 2

```<code>ID         | event_start   | StartDateTimestamp2
---------- | ------------- | -------------------
1          | HiredStart    | 20080501 01:30:00
1          | DeferredStart | 20090604 01:01:00
2          | HiredStart    | 20190115 05:52:14
3          | HiredStart    | 20190330 02:35:26
6          | DeferredStart | 20190330 02:35:26
</code>```

Attempt 1

```<code>SELECT CohortID, RANK() OVER(ORDER BY CohortID ASC) RANK, t1.id, event_start, startdatetimestamp2
FROM table1 e JOIN table 2 ON table2.id = table1.id

</code>```

Then I tried:

```<code>SELECT CohortID, (CASE WHEN CohortID = 1 THEN RANK() OVER(ORDER BY(StartDateTimestamp2) ASC)
                       WHEN CohortID = 2 THEN RANK() OVER(ORDER BY(StartDateTimestamp2) ASC) END)
FROM table1 JOIN table2 ON table1.user_id = table2.user_id
</code>```

Expected Output

```<code>CohortID   | RANK | ID | CohortName | startdatetimestamp2
---------- | -----|----|------------|-------------------
1          | 1    | 1  | Peanut     | 20080501 01:30:00
1          | 2    | 2  | Peanut     | 20090604 01:01:00
1          | 3    | 6  | Apple      | 20190115 05:52:14
2          | 1    | 3  | Apple      | 20190330 02:35:26
2          | 2    | 5  | Peanut     | 20190115 05:52:14
</code>```

The Rank restarts when the CohortId changes from 1 to 2, from 123 to 12.

My above query just ranks in a weird sequence. How do I make it so that it restarts every time top 3 when the CohortID is different?

答:
You need to create a query which generates a rank assignment, per cohort, and then subquery and retain only ranks of 3 or less:</p>

```<code>WITH cte AS (
    SELECT t1.CohortID, t1.ID, t1.CohortName, t2.startdatetimestamp2,
        RANK() OVER (PARTITION BY t1.CohortID ORDER BY t2.StartDateTimestamp2) rnk
    FROM table1 t1
    INNER JOIN table2 t2 ON t1.id = t2.id
)

SELECT CohortID, rnk AS "RANK", ID, CohortName, startdatetimestamp2
FROM cte
WHERE "RANK" <= 3
ORDER BY CohortID, "RANK";
</code>```

Body:
Table1

ID         | JoinedStart        | CohortID | CohortName
---------- | ------------------ | -------- | ----------
1          | 20080101 01:30:00  | 1        | Peanut
1          | 20090204 01:01:00  | 2        | Apple
2          | 20190107 05:52:14  | 1        | Peanut
3          | 20190311 02:35:26  | 2        | Apple
6          | 20190311 02:35:26  | 2        | Apple

Table 2

ID         | event_start   | StartDateTimestamp2
---------- | ------------- | -------------------
1          | HiredStart    | 20080501 01:30:00
1          | DeferredStart | 20090604 01:01:00
2          | HiredStart    | 20190115 05:52:14
3          | HiredStart    | 20190330 02:35:26
6          | DeferredStart | 20190330 02:35:26

Attempt 1

SELECT CohortID, RANK() OVER(ORDER BY CohortID ASC) RANK, t1.id, event_start, startdatetimestamp2
FROM table1 e JOIN table 2 ON table2.id = table1.id

Then I tried:

SELECT CohortID, (CASE WHEN CohortID = 1 THEN RANK() OVER(ORDER BY(StartDateTimestamp2) ASC)
                       WHEN CohortID = 2 THEN RANK() OVER(ORDER BY(StartDateTimestamp2) ASC) END)
FROM table1 JOIN table2 ON table1.user_id = table2.user_id

Expected Output

CohortID   | RANK | ID | CohortName | startdatetimestamp2
---------- | -----|----|------------|-------------------
1          | 1    | 1  | Peanut     | 20080501 01:30:00
1          | 2    | 2  | Peanut     | 20090604 01:01:00
1          | 3    | 6  | Apple      | 20190115 05:52:14
2          | 1    | 3  | Apple      | 20190330 02:35:26
2          | 2    | 5  | Peanut     | 20190115 05:52:14

The Rank restarts when the CohortId changes from 1 to 2, from 123 to 12.

My above query just ranks in a weird sequence. How do I make it so that it restarts every time top 3 when the CohortID is different?

Body:
You need to create a query which generates a rank assignment, per cohort, and then subquery and retain only ranks of 3 or less:

WITH cte AS (
    SELECT t1.CohortID, t1.ID, t1.CohortName, t2.startdatetimestamp2,
        RANK() OVER (PARTITION BY t1.CohortID ORDER BY t2.StartDateTimestamp2) rnk
    FROM table1 t1
    INNER JOIN table2 t2 ON t1.id = t2.id
)

SELECT CohortID, rnk AS "RANK", ID, CohortName, startdatetimestamp2
FROM cte
WHERE "RANK" <= 3
ORDER BY CohortID, "RANK";


问:
Can't push to bitbucket, Permission denied (publickey)
I am trying to push my project onto my bitbucket, been messing with this for about 4 days pouring through countless problem solving/pages/troubleshooting/tutorials. Im at a loss and very frustrated. I have done this before but on different computers...anyway here is the code/response that I'm getting

```<code>~/dev/sample_app git push -u origin --all
The authenticity of host 'bitbucket.org (131.103.20.168)' can't be established.
RSA key fingerprint is 81:7b:2c:f5:6f:18:2b:7c:4b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
~/dev/sample_app
</code>```

I am on a mac running 10.8.4.

So a little progress has been made, initially there was no .ssh folder so I created that way back in the beginning, there was no known_hosts file so I ran

```<code>ssh -T git@bitbucket.org
</code>```

I chose yes and this created a known_hosts file and when I tried to push again I got:

```<code>~/dev/sample_app git push -u origin --all
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

My .ssh folder is 700 and the keys inside are all 600.

答:
If any.ssh fix didn't work or you cloned as https there can be a validation issue. in my case, I fixed this error by providing my username and password when cloning the repo. This issue can occur when you are using multiple accounts in a same machine.

use  "git clone https://username:password@github.com/username/repository.git" command with your user name and password and repo URL.

Body:
I am trying to push my project onto my bitbucket, been messing with this for about 4 days pouring through countless problem solving/pages/troubleshooting/tutorials. Im at a loss and very frustrated. I have done this before but on different computers...anyway here is the code/response that I'm getting

~/dev/sample_app git push -u origin --all
The authenticity of host 'bitbucket.org (131.103.20.168)' can't be established.
RSA key fingerprint is 81:7b:2c:f5:6f:18:2b:7c:4b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
~/dev/sample_app

I am on a mac running 10.8.4.

So a little progress has been made, initially there was no .ssh folder so I created that way back in the beginning, there was no known_hosts file so I ran

ssh -T git@bitbucket.org

I chose yes and this created a known_hosts file and when I tried to push again I got:

~/dev/sample_app git push -u origin --all
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

My .ssh folder is 700 and the keys inside are all 600.


问:
React - correct syntax to use a prop with a prefix as an ID for an element?
What's the correct syntax to use a prop for an element id except but with a prefix. Do I have to assign each to a variable and use a string literal, or can I do it inline?

e.g.

```<code><input id="first_{id}" type="text" value={firstName} />
<input id="last_{id}" type="text" value={lastName} />
</code>```

答:
I would prefer a string interpolation syntax like so

<input id={`first_${id}`} type="text" value={firstName} />
```

Body:
What's the correct syntax to use a prop for an element id except but with a prefix. Do I have to assign each to a variable and use a string literal, or can I do it inline?

e.g.

<input id="first_{id}" type="text" value={firstName} />
<input id="last_{id}" type="text" value={lastName} />


问:
Best practice to record large amount of hits into MySQL database
Well, this is the thing. Let's say that my future PHP CMS need to drive 500k visitors daily and I need to record them all in MySQL database (referrer, ip address, time etc.). This way I need to insert 300-500 rows per minute and update 50 more. The main problem is that script would call database every time I want to insert new row, which is every time someone hits a page.

My question, is there any way to locally cache incoming hits first (and what is the best solution for that apc, csv...?) and periodically send them to database every 10 minutes for example? Is this good solution and what is the best practice for this situation?

答: We do this by storing locally on each server to CSV, then having a minutely cron job to push the entries into the database.  This is to avoid needing a highly available MySQL database more than anything - the database should be able to cope with that volume of inserts without a problem.</p>


问:
Shift DataFrame Columns Up Based on Threshold Value found in Columns
I have the following df:

```<code>                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -1.33           -1.29           -1.38
2020022000                 -1.24           -1.33           -1.29
2020022006               -999.00           -1.23           -1.33
2020022012                 -0.88         -999.00           -1.21
2020022018                 -0.70           -0.88         -999.00
2020022100                 -0.46           -0.70           -0.89
2020022106                 -0.37           -0.45           -0.70
</code>```

I would like to shift the columns up, and not include the cells containing the -999 values once a -999 is reached for every column.

My desired result would look like the following:

```<code>                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -0.88           -0.88           -0.89
2020022000                 -0.70           -1.70           -0.70
2020022006                 -0.46           -0.45
2020022012                 -0.37
2020022018
2020022100
2020022106
</code>```

(The length of column once this operation is achieved does not matter in this case; additionally the column names can be named anything so I cannot reference them by name).

I have tried various iterations of df.ffill and df.bfill, however to no avail.

Thank you for your time in advance.

答:
Let's find out the indices where -999.0 occurs, then iterate through the columns and shift each of them from the bottom.

# resetting the index for flattening the dataframe
df.reset_index(inplace=True)

for col in df.columns:
    try:
        # finding the index where -990 occurs
        n_shift = df.index[df[col] == -999.0].tolist()[0] + 1

        # shifting the column from bottom
        df[col] = df[col].shift(-n_shift)

        print(f"Shifted : {col}")
    except IndexError:
        print(f"Not shifted : {col}")

# setting the index back to original
df.set_index(["dates"], inplace=True)
```

<p>This prints out:</p>

<pre class="lang-py prettyprint-override"><code>Not shifted : dates
Not shifted : testcol_45
Not shifted : testcol_76
Not shifted : testcol_99
</code>```

The dataframe looks like this:

            testcol_45  testcol_76  testcol_99
dates
2020021918       -0.88       -0.88       -0.89
2020022000       -0.70       -0.70       -0.70
2020022006       -0.46       -0.45         NaN
2020022012       -0.37         NaN         NaN
2020022018         NaN         NaN         NaN
2020022100         NaN         NaN         NaN
2020022106         NaN         NaN         NaN
```

Body:
I have the following df:

                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -1.33           -1.29           -1.38
2020022000                 -1.24           -1.33           -1.29
2020022006               -999.00           -1.23           -1.33
2020022012                 -0.88         -999.00           -1.21
2020022018                 -0.70           -0.88         -999.00
2020022100                 -0.46           -0.70           -0.89
2020022106                 -0.37           -0.45           -0.70

I would like to shift the columns up, and not include the cells containing the -999 values once a -999 is reached for every column.

My desired result would look like the following:

                           testcol_45    testcol_76    testcol_99
dates
2020021918                 -0.88           -0.88           -0.89
2020022000                 -0.70           -1.70           -0.70
2020022006                 -0.46           -0.45
2020022012                 -0.37
2020022018
2020022100
2020022106

(The length of column once this operation is achieved does not matter in this case; additionally the column names can be named anything so I cannot reference them by name).

I have tried various iterations of df.ffill and df.bfill, however to no avail.

Thank you for your time in advance.

Body:
Let's find out the indices where -999.0 occurs, then iterate through the columns and shift each of them from the bottom.

# resetting the index for flattening the dataframe
df.reset_index(inplace=True)

for col in df.columns:
    try:
        # finding the index where -990 occurs
        n_shift = df.index[df[col] == -999.0].tolist()[0] + 1

        # shifting the column from bottom
        df[col] = df[col].shift(-n_shift)

        print(f"Shifted : {col}")
    except IndexError:
        print(f"Not shifted : {col}")

# setting the index back to original
df.set_index(["dates"], inplace=True)

This prints out:

Not shifted : dates
Not shifted : testcol_45
Not shifted : testcol_76
Not shifted : testcol_99

The dataframe looks like this:

            testcol_45  testcol_76  testcol_99
dates
2020021918       -0.88       -0.88       -0.89
2020022000       -0.70       -0.70       -0.70
2020022006       -0.46       -0.45         NaN
2020022012       -0.37         NaN         NaN
2020022018         NaN         NaN         NaN
2020022100         NaN         NaN         NaN
2020022106         NaN         NaN         NaN


问:
How to send data to another page without using cookies or JS in PHP?
So, I have a PHP file that runs an SQL(MySql) query and gets the result. I need that page to send that result to another page automatically(I can use PHP in the receiving page). However, I want to make my website accessible to privacy-sensitive people who disable cookies and javascript on their browsers. I'm not using any PHP frameworks.

An initial page that runs the query only runs in the backend like a controller so it does not have any HTML in it. This means I cannot use a hidden form and make the user submit it with a button. I thought about sessions but they need cookies to work and JSON needs javascript. I thought about sending the data in the URL but the query result is quite big and I was afraid it could exceed some kind of URL length limits(if such thing exists). Is there a way to achieve this reliably?

EDIT: To clarify some things, the data I am sending is a search result so the query changes depending on the users input(which was provided to the page which runs the query with a form).

答:
Store data somewhere and send id or something through  query string and access data from database through that id from query string. Sending too much data is not advisable through cookies, session or even query string just pass your unique id and grab data from db.
Happy coding.</p>


问:
session_regenerate_id(): Cannot regenerate session id - headers already sent in
it is outputting: session_regenerate_id(): Cannot regenerate session id - headers already sent in</p>

```<code>session_start();

session_regenerate_id();
$_SESSION['inside'] = TRUE;
$_SESSION['username'] = $GettedName;
$_SESSION['id'] = $ID;
$_SESSION['email'] = $sirname ;
$_SESSION['sirname '] = $sirname ;
</code>```

答:
```<code>ob_clean();
ob_start();
</code>```

at the start of the code and check you have space in your session array like below

```<code>$_SESSION['sirname '] = $sirname ;
</code>```

should be

```<code>$_SESSION['sirname'] = $sirname ;
</code>```

and try this

```<code>ob_clean();
ob_start();
session_regenerate_id();
$_SESSION['inside'] = TRUE;
$_SESSION['username'] = $GettedName;
$_SESSION['id'] = $ID;
$_SESSION['email'] = $sirname;
$_SESSION['sirname'] = $sirname;
</code>```

Body:
it is outputting: session_regenerate_id(): Cannot regenerate session id - headers already sent in

session_start();

session_regenerate_id();
$_SESSION['inside'] = TRUE;
$_SESSION['username'] = $GettedName;
$_SESSION['id'] = $ID;
$_SESSION['email'] = $sirname ;
$_SESSION['sirname '] = $sirname ;

Body:
ob_clean();
ob_start();

at the start of the code and check you have space in your session array like below

$_SESSION['sirname '] = $sirname ;

should be

$_SESSION['sirname'] = $sirname ;

and try this

ob_clean();
ob_start();
session_regenerate_id();
$_SESSION['inside'] = TRUE;
$_SESSION['username'] = $GettedName;
$_SESSION['id'] = $ID;
$_SESSION['email'] = $sirname;
$_SESSION['sirname'] = $sirname;


问:
Android highlight an imagebutton when clicked
I am using an ImageButton. But I don get the highlight when clicked. I googled and many suggested to use selector where another image is displayed. Is there any way around this. by using only one image and highlighting it or giving it a glow effect. so that the user knows that button has been clicked.

答:
You can simply use android:foreground for your View to achieve clickable effect:

```<code>android:foreground="?android:attr/selectableItemBackground"
</code>```

For use with dark theme add also theme to your layout (to make clickable effect clear):

```<code>android:theme="@android:style/ThemeOverlay.Material.Dark"
</code>```

Body:
You can simply use android:foreground for your View to achieve clickable effect:

android:foreground="?android:attr/selectableItemBackground"

For use with dark theme add also theme to your layout (to make clickable effect clear):

android:theme="@android:style/ThemeOverlay.Material.Dark"