问:
How to enable Firebase Real time database Offline persistence?
In my MainActivity I'm enabling firebase persistence enabled like below,

```<code>// Imports **

private  lateinit var mDatabase : FirebaseDatabase

val md = FirebaseDatabase.getInstance().setPersistenceEnabled(true)

class MainActivity: AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
// bla bla
}
}
</code>```

After Initialising MainActiviy my Activity2 starts destroying MainActivity. In my Activity2 viewmodel I'm Initialising all data from server like below,

```<code>class AppMainActivityViewModel(application: Application) : AndroidViewModel(application) {

lateinit var user_data_ref : DatabaseReference
lateinit var user_data_ref_lis : ValueEventListener

init {
        user = FirebaseAuth.getInstance().currentUser?.uid!! }

fun updateDashboard(){
 user_data_ref = FirebaseDatabase.getInstance().getReference("Users/$user")
user_data_ref_lis = user_data_ref.addValueEventListener(object : ValueEventListener {

            override fun onCancelled(p0: DatabaseError) {
            }
            override fun onDataChange(p0: DataSnapshot) {
                userdata.value = p0.getValue(UserModel::class.java)
            }
        })
}

override fun onCleared() {
        super.onCleared()
        user_data_ref.removeEventListener(user_data_ref_lis)
    }

    }
</code>```

If I first run my application with internet, I assume here that my listeners would have cached data offline now, then I quit my app then opened without internet, I expected here that the locally cached data would trigger onData change immediately but to my surprise onData change was never triggred. I then changed my code to keepsync true to my user_data_ref, then it worked fine in offline mode.

Every time user opens the app, a bunch of old histories are being downloaded (approximately 30 reference with 100kb for each reference,Some of the old history is never going to change at all ). This greatly increases my bandwidth consumption over period as  every time fresh files are downloaded with current logic. My main goal of enabling persistence is to reduce bandwidth consumption.

Following are the bunch of question I have now,

According to document, ValueEvent listener should be enough to cache data, why is it not working in my case?

Will this keep synced true increase my bandwidth consumption as it continuously checking for updates?

Will this keep synced true runs even my activity is destroyed?

If i put keepsynced true to my database reference which has 100kb of size, if there is a child update happening inside my ref which will be 1 kb change. Will this 100 kb be downloaded next time or just that 1 kb is downloaded?

答:
My main goal of enabling persistence is to reduce bandwidth consumption.

The goal of disk persistence is to allow the app to be started and run even when the user doesn't have an internet connection. While disk persistence may also reduce some of the data downloads, that is not guaranteed and is not its main purpose.

To reduce bandwidth consumption, you should read less data. Calling keepSynced(true) on a node will keep that node in sync for as long as the app is active. If the node changes regularly, and you only need the data sporadically, this is almost guaranteed to waste bandwidth. Here too, the goal of keeping a node synced is not to reduce bandwidth usage, but to keep that data "fresh" in case it is needed when the user is not connected.

To your questions:

According to [documentation], ValueEvent listener should be enough to cache data, why is it not working in my case?

It is impossible to say precise why data is not being cached. But if your onDataChange is not being called, it is safe to assume the data won't be written to the disk cache either.

The first step to troubleshooting is to implement onCancelled, which you should never leave empty. Its minimal implementation is:

```<code>override fun onCancelled(p0: DatabaseError) {
    throw p0.toException();
}
</code>```

Will this keep synced true increase my bandwidth consumption as it continuously checking for updates?

Will this keep synced true runs even my activity is destroyed?

When you call ref.keepSynced(true), it attaches an empty listener to ref. This means the data at ref will be kept up to date in memory (and if you've enable disk persistence, in the cache) for as long as the app is running.

As said earlier, if the data is updated frequently, and used infrequently, this may end up using more bandwidth than just attaching a listener when it's needed. As also said earlier: you should call ref.keepSynced(true) when you need the data of a node to be fresh.

It is impossible to say for every scenario what effect keeping a node synced
has on bandwidth usage. You will have to measure and extrapolate based on understanding what each API actually does, and what it's meant to be used for.

If i put keepsynced true to my database reference which has 100kb of size, if there is a child update happening inside my ref which will be 1 kb change. Will this 100 kb be downloaded next time or just that 1 kb is downloaded?

Neither. Firebase performs a so-called delta sync in this case. The SDK calculates a list of hashes for the local data, and sends these to the server. The server compares these to its own hashes, and then sends back only the data that has changed. The result should typically be smaller than sending back the whole snapshot, but how much smaller depends on how much data is at the location, and how much was changed.

Also see:

Firebase : What is the difference between setPersistenceEnabled and keepSynced?

Firebase setPersistenceEnabled(true) what about the downloaded data

Does firebase web client download data every time I subscribe for a certain database path? (especially the comments to my answer)

Body:
In my MainActivity I'm enabling firebase persistence enabled like below,

// Imports **

private  lateinit var mDatabase : FirebaseDatabase

val md = FirebaseDatabase.getInstance().setPersistenceEnabled(true)

class MainActivity: AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
// bla bla
}
}

After Initialising MainActiviy my Activity2 starts destroying MainActivity. In my Activity2 viewmodel I'm Initialising all data from server like below,

class AppMainActivityViewModel(application: Application) : AndroidViewModel(application) {

lateinit var user_data_ref : DatabaseReference
lateinit var user_data_ref_lis : ValueEventListener

init {
        user = FirebaseAuth.getInstance().currentUser?.uid!! }

fun updateDashboard(){
 user_data_ref = FirebaseDatabase.getInstance().getReference("Users/$user")
user_data_ref_lis = user_data_ref.addValueEventListener(object : ValueEventListener {

            override fun onCancelled(p0: DatabaseError) {
            }
            override fun onDataChange(p0: DataSnapshot) {
                userdata.value = p0.getValue(UserModel::class.java)
            }
        })
}

override fun onCleared() {
        super.onCleared()
        user_data_ref.removeEventListener(user_data_ref_lis)
    }

    }

If I first run my application with internet, I assume here that my listeners would have cached data offline now, then I quit my app then opened without internet, I expected here that the locally cached data would trigger onData change immediately but to my surprise onData change was never triggred. I then changed my code to keepsync true to my user_data_ref, then it worked fine in offline mode.

Every time user opens the app, a bunch of old histories are being downloaded (approximately 30 reference with 100kb for each reference,Some of the old history is never going to change at all ). This greatly increases my bandwidth consumption over period as  every time fresh files are downloaded with current logic. My main goal of enabling persistence is to reduce bandwidth consumption.

Following are the bunch of question I have now,

According to document, ValueEvent listener should be enough to cache data, why is it not working in my case?

Will this keep synced true increase my bandwidth consumption as it continuously checking for updates?

Will this keep synced true runs even my activity is destroyed?

If i put keepsynced true to my database reference which has 100kb of size, if there is a child update happening inside my ref which will be 1 kb change. Will this 100 kb be downloaded next time or just that 1 kb is downloaded?

Body:
My main goal of enabling persistence is to reduce bandwidth consumption.

The goal of disk persistence is to allow the app to be started and run even when the user doesn't have an internet connection. While disk persistence may also reduce some of the data downloads, that is not guaranteed and is not its main purpose.

To reduce bandwidth consumption, you should read less data. Calling keepSynced(true) on a node will keep that node in sync for as long as the app is active. If the node changes regularly, and you only need the data sporadically, this is almost guaranteed to waste bandwidth. Here too, the goal of keeping a node synced is not to reduce bandwidth usage, but to keep that data "fresh" in case it is needed when the user is not connected.

To your questions:

According to [documentation], ValueEvent listener should be enough to cache data, why is it not working in my case?

It is impossible to say precise why data is not being cached. But if your onDataChange is not being called, it is safe to assume the data won't be written to the disk cache either.

The first step to troubleshooting is to implement onCancelled, which you should never leave empty. Its minimal implementation is:

override fun onCancelled(p0: DatabaseError) {
    throw p0.toException();
}

Will this keep synced true increase my bandwidth consumption as it continuously checking for updates?

Will this keep synced true runs even my activity is destroyed?

When you call ref.keepSynced(true), it attaches an empty listener to ref. This means the data at ref will be kept up to date in memory (and if you've enable disk persistence, in the cache) for as long as the app is running.

As said earlier, if the data is updated frequently, and used infrequently, this may end up using more bandwidth than just attaching a listener when it's needed. As also said earlier: you should call ref.keepSynced(true) when you need the data of a node to be fresh.

It is impossible to say for every scenario what effect keeping a node synced
has on bandwidth usage. You will have to measure and extrapolate based on understanding what each API actually does, and what it's meant to be used for.

If i put keepsynced true to my database reference which has 100kb of size, if there is a child update happening inside my ref which will be 1 kb change. Will this 100 kb be downloaded next time or just that 1 kb is downloaded?

Neither. Firebase performs a so-called delta sync in this case. The SDK calculates a list of hashes for the local data, and sends these to the server. The server compares these to its own hashes, and then sends back only the data that has changed. The result should typically be smaller than sending back the whole snapshot, but how much smaller depends on how much data is at the location, and how much was changed.

Also see:

Firebase : What is the difference between setPersistenceEnabled and keepSynced?

Firebase setPersistenceEnabled(true) what about the downloaded data

Does firebase web client download data every time I subscribe for a certain database path? (especially the comments to my answer)


来源: stackexchange

问:
Why setImageResource displays nothing?
I would like to display an icon in my ListView depending on the database value. I follow this answer to do so.
But in result nothing is displayed. Here is what I have in my row.xml:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

    <ImageView
        android:id="@+id/movie_subscribed_icon"
        android:padding="3dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/star_off"/>

    <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical">

     <TextView android:id="@+id/movie_name"
     ...
</code>```

and here is the code:

```<code>    movies.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
          int viewId = view.getId();
          switch(viewId) {
          case R.id.movie_name:
                  int readValue = cursor.getInt(cursor.getColumnIndexOrThrow(MoviesDbAdapter.KEY_READ));
                  if (readValue == 1) { // viewed movie item
                      TextView movieName = (TextView) view;
                      movieName.setTextColor(Color.GRAY);
                  }
                  break;
          case R.id.movie_subscribed_icon:
              int subscribedValue = cursor.getInt(cursor.getColumnIndexOrThrow(MoviesDbAdapter.KEY_READ));
                  if (subscribedValue > 0) { // subscribed movie item
                      ImageView movieIcon = (ImageView) view;
                      movieIcon.setImageResource(R.drawable.star_off);
                  }
              break;
          }
          return false;
        }

      } );
</code>```

I especially use the same icon in my code as default one.
What is wrong here? (I have star_off in drawable-hdpi and drawable-mdpi folders only)

Upd. the following code works well:

```<code>movieIcon.setImageDrawable(getResources().getDrawable(R.drawable.star_off));
</code>```

答:
This piece of code solves the problem : </p>

```<code>ImageView movieIcon = (ImageView)findViewById(R.id.movie_subscribed_icon);
Drawable drawable = this.getResources().getDrawable(R.drawable.android);
movie_subscribed_icon.setBackgroundDrawable(drawable);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Why setImageResource displays nothing?

Body:
I would like to display an icon in my ListView depending on the database value. I follow this answer to do so.
But in result nothing is displayed. Here is what I have in my row.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

    <ImageView
        android:id="@+id/movie_subscribed_icon"
        android:padding="3dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/star_off"/>

    <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical">

     <TextView android:id="@+id/movie_name"
     ...

and here is the code:

    movies.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
          int viewId = view.getId();
          switch(viewId) {
          case R.id.movie_name:
                  int readValue = cursor.getInt(cursor.getColumnIndexOrThrow(MoviesDbAdapter.KEY_READ));
                  if (readValue == 1) { // viewed movie item
                      TextView movieName = (TextView) view;
                      movieName.setTextColor(Color.GRAY);
                  }
                  break;
          case R.id.movie_subscribed_icon:
              int subscribedValue = cursor.getInt(cursor.getColumnIndexOrThrow(MoviesDbAdapter.KEY_READ));
                  if (subscribedValue > 0) { // subscribed movie item
                      ImageView movieIcon = (ImageView) view;
                      movieIcon.setImageResource(R.drawable.star_off);
                  }
              break;
          }
          return false;
        }

      } );

I especially use the same icon in my code as default one.
What is wrong here? (I have star_off in drawable-hdpi and drawable-mdpi folders only)

Upd. the following code works well:

movieIcon.setImageDrawable(getResources().getDrawable(R.drawable.star_off));

Body:
This piece of code solves the problem :

ImageView movieIcon = (ImageView)findViewById(R.id.movie_subscribed_icon);
Drawable drawable = this.getResources().getDrawable(R.drawable.android);
movie_subscribed_icon.setBackgroundDrawable(drawable);

ContentLicense: CC BY-SA 3.0


问:
Why am I getting a an error when creating a generated column in PostgreSQL?
```<code>CREATE TABLE my_app.person
(
    person_id smallserial NOT NULL,
    first_name character varying(50),
    last_name character varying(50),
    full_name character varying(100) generated always as (concat(first_name, ' ', last_name)) STORED,
    birth_date date,
    created_timestamp timestamp default current_timestamp,
    PRIMARY KEY (person_id)
);
</code>```

Error: generation expression is not immutable

The goal is to populate the first name and last into the full name column.

答:
The concat() function is not IMMUTABLE (only STABLE) because it can invoke datatype output functions (like timestamptz_out) that depend on locale settings. Tom Lane (core developer) explains it here.

And first_name || ' ' || last_name is not equivalent to concat(first_name, ' ', last_name) while at least one column can be NULL.

Detailed explanation:

Combine two columns and add into one new column

Solution

To make it work, exactly the way you demonstrated:

CREATE TABLE person (
  person_id smallserial PRIMARY KEY
, first_name varchar(50)
, last_name  varchar(50)
, full_name  varchar(101) GENERATED ALWAYS AS
                         (CASE WHEN first_name IS NULL THEN last_name
                               WHEN last_name  IS NULL THEN first_name
                               ELSE first_name || ' ' || last_name END) STORED
, ...
);
```

db<>fiddle here

The CASE expression is as fast as it gets - substantially faster than multiple concatenation and function calls. And exactly correct.

Or, if you know what you are doing and have the necessary privileges, create an IMMUTABLE concat function as demonstrated here (to replace the CASE expression):

Create an immutable clone of concat_ws

Aside: full_name needs to be varchar(101) (50+50+1) to make sense. Or just use text columns instead. See:

Any downsides of using data type "text" for storing strings?

General Advice

The best solution depends on how you plan to deal with NULL values (and empty strings) exactly. I would probably not add a generated column. That's typically more expensive and error prone overall than to concatenate the full name on the fly. Consider a view, or a function encapsulating the concatenation logic.

Related:

Computed / calculated / virtual / derived columns in PostgreSQL

Store common query as column?

ContentLicense: CC BY-SA 4.0

Body:
CREATE TABLE my_app.person
(
    person_id smallserial NOT NULL,
    first_name character varying(50),
    last_name character varying(50),
    full_name character varying(100) generated always as (concat(first_name, ' ', last_name)) STORED,
    birth_date date,
    created_timestamp timestamp default current_timestamp,
    PRIMARY KEY (person_id)
);

Error: generation expression is not immutable

The goal is to populate the first name and last into the full name column.

Body:
The concat() function is not IMMUTABLE (only STABLE) because it can invoke datatype output functions (like timestamptz_out) that depend on locale settings. Tom Lane (core developer) explains it here.

And first_name || ' ' || last_name is not equivalent to concat(first_name, ' ', last_name) while at least one column can be NULL.

Detailed explanation:

Combine two columns and add into one new column

Solution

To make it work, exactly the way you demonstrated:

CREATE TABLE person (
  person_id smallserial PRIMARY KEY
, first_name varchar(50)
, last_name  varchar(50)
, full_name  varchar(101) GENERATED ALWAYS AS
                         (CASE WHEN first_name IS NULL THEN last_name
                               WHEN last_name  IS NULL THEN first_name
                               ELSE first_name || ' ' || last_name END) STORED
, ...
);

db<>fiddle here

The CASE expression is as fast as it gets - substantially faster than multiple concatenation and function calls. And exactly correct.

Or, if you know what you are doing and have the necessary privileges, create an IMMUTABLE concat function as demonstrated here (to replace the CASE expression):

Create an immutable clone of concat_ws

Aside: full_name needs to be varchar(101) (50+50+1) to make sense. Or just use text columns instead. See:

Any downsides of using data type "text" for storing strings?

General Advice

The best solution depends on how you plan to deal with NULL values (and empty strings) exactly. I would probably not add a generated column. That's typically more expensive and error prone overall than to concatenate the full name on the fly. Consider a view, or a function encapsulating the concatenation logic.

Related:

Computed / calculated / virtual / derived columns in PostgreSQL

Store common query as column?


问:
Including a href in a picture source media element
I'm using the following code to show an image in my website:

```<code>  <div id="wideheader">
     <div id="header">
        <div id="headerimage">
            <picture>
              <source
                media="(max-width: 900px)"
                srcset="images/eye1.jpg">
              <img
                src="images/eye2.jpg"
                alt="">
            </picture>
           <div id="headerteaser">
              Beautiful Eyes
           </div>
        </div>
     </div>
  </div>
</code>```

How could I include an href so that a click on the image would take the visitor to another page?

Thank you!

答:
```<code>  <div id="wideheader">
     <div id="header">
        <div id="headerimage">
            <picture>
              <source
                media="(max-width: 900px)"
                srcset="images/eye1.jpg">
              <a href=""><img
                src="images/eye2.jpg"
                alt=""></a>
            </picture>
           <div id="headerteaser">
              Beautiful Eyes
           </div>
        </div>
     </div>
  </div>
</code>```

Body:
I'm using the following code to show an image in my website:

            <picture>
              <source
                media="(max-width: 900px)"
                srcset="images/eye1.jpg">

            </picture>

              Beautiful Eyes

How could I include an href so that a click on the image would take the visitor to another page?

Thank you!


问:
Change the language of Angular datepicker (AngularDateTimePickerModule)
I'm using this date picker https://www.npmjs.com/package/angular2-datetimepicker, and I would like to know if there is any way in which I can change the naming of the weekdays "Mon/Tue/Wed/..." or the naming of months? </p>

<p>There's a StackBlitz example here: https://stackblitz.com/edit/angular-mmq3ng?file=src%2Fapp%2Fhello.component.ts   </p>

答:
Seems like there is no build-in option to change the format in the date-picker itself. You can change how the selected date is displayed.

In the app.component.ts in your StackBlitz example, just change the format of the settings object.

```<code>settings = {
    bigBanner: true,
    timePicker: false,
    format: 'EEEE MMM yyy',  <-- Change this format
    defaultOpen: true
}
</code>```

In the example above I changed it to a format like this: Tuesday Feb 2020

On the npm page you can find all the information on what formats are accepted (there are a lot of them).

Body:
I'm using this date picker https://www.npmjs.com/package/angular2-datetimepicker, and I would like to know if there is any way in which I can change the naming of the weekdays "Mon/Tue/Wed/..." or the naming of months?

There's a StackBlitz example here: https://stackblitz.com/edit/angular-mmq3ng?file=src%2Fapp%2Fhello.component.ts

Body:
Seems like there is no build-in option to change the format in the date-picker itself. You can change how the selected date is displayed.

In the app.component.ts in your StackBlitz example, just change the format of the settings object.

settings = {
    bigBanner: true,
    timePicker: false,
    format: 'EEEE MMM yyy',  <-- Change this format
    defaultOpen: true
}

In the example above I changed it to a format like this: Tuesday Feb 2020

On the npm page you can find all the information on what formats are accepted (there are a lot of them).


问:
Using up bandwidth when calling readfile() on a different server?
I have a question about how servers communicate with each other and how it takes up bandwidth.  I'll use an example to better explain my question.

I have two sites: www.jojoedad.com and resources.jojoedad.com.  Each site resides on a separate server (with different IPs and on different machines).  "www| is used mainly for handling front-end tasks such as serving up different web pages.  "resources" stores a whole bunch of video files and is meant to only serve up large video files.

Assume that I code it correctly so only "www" can be accessed by the public and "resources" can only be accessed by calling scripts on "www".  Will large bandwidths of "www" be taken up if users retrieve videos on "resources" through www.jojoedad.com like this:

```<code>http://www.jojoedad.com/getVideo.php?filename=myVideo.mp4
</code>```

and in getVideo.php, I have something like this:

```<code>header("Content-Type..."); // I didn't fill in details for this line
header("Content-disposition..."); // I didn't fill in details for this line
header("COntent-description..."); // I didn't fill in details for this line
readfile("http://resources.jojoedad.com/video_files/{$_GET['filename']}");
</code>```

Thanks in advance!

答:
The fun thing is this will use twice the bandwidth on www -- once to retrieve the file from resources and once to send the data to the client -- and once on resources. Many data centers charge less (or nothing) for internal data traffic, so it might not be a big deal.

If you like restricting access to resources to come from www and only from www, then it might even be worth the triple-bandwidth costs to get a file from resources to www and then again from www to the client.

Body:
I have a question about how servers communicate with each other and how it takes up bandwidth.  I'll use an example to better explain my question.

I have two sites: www.jojoedad.com and resources.jojoedad.com.  Each site resides on a separate server (with different IPs and on different machines).  "www| is used mainly for handling front-end tasks such as serving up different web pages.  "resources" stores a whole bunch of video files and is meant to only serve up large video files.

Assume that I code it correctly so only "www" can be accessed by the public and "resources" can only be accessed by calling scripts on "www".  Will large bandwidths of "www" be taken up if users retrieve videos on "resources" through www.jojoedad.com like this:

http://www.jojoedad.com/getVideo.php?filename=myVideo.mp4

and in getVideo.php, I have something like this:

header("Content-Type..."); // I didn't fill in details for this line
header("Content-disposition..."); // I didn't fill in details for this line
header("COntent-description..."); // I didn't fill in details for this line
readfile("http://resources.jojoedad.com/video_files/{$_GET['filename']}");

Thanks in advance!


问:
Are LightGBM treating Pandas Categoricals based on name or cat_code value?
LightGBM provides the option to handle categorical variables without the need to onehot-encode the dataset.

One way to make use of this feature (from the Python interface) is to specify the column-names of the categorical features as a list using the categorical_feature-argument.
This approach requires the categories to be encoded as integers.

But an alternative is to provide LightGBM with a Pandas DataFrame where the columns which are categorical in nature is set the be of the Categorical dtype, and LightGBM will figure out which columns to treat as categoricals.

But the underlying interger codes used in categoricals are set by Pandas, and will likely not be consistent across Python sessions. Will mixed-up cat_codes lead to LightGBM misinterpreting entries in the categoricals?

By a Pandas categorical, I'm refering to a feature set as df['Some_categorical_feature'] = df['Some_categorical_feature'].astype('category').

答:
Pandas assigns categorical codes by sorting the keys (categories) before assigning the codes, and LightGBM relies on Pandas to handle assigning the categoridcal codes correctly.
Introducing a previously unseen category will break the ordering of the categoricals, and thus shift the categorical codes.

Source: https://github.com/microsoft/LightGBM/issues/2761#issuecomment-586722068

Code to demonstrate the problem:

```<code>#!/usr/bin/env python
# -*- coding: utf8 -*-

import pandas as pd
import lightgbm as lgb

X_train = pd.Series(['D', 'A', 'C', 'C', 'E', 'E', 'A'],
                    name='X', dtype='category').to_frame()
X_deploy = pd.Series(['B', 'E', 'A', 'C', 'D', 'E', 'F'],
                     name='X', dtype='category').to_frame()

X_train_transformed = lgb.basic._data_from_pandas(X_train, None, None, None)
X_deploy_transformed = lgb.basic._data_from_pandas(X_deploy, None, None, None)

print("X_train", X_train, sep=':\n', end='\n\n')
# X_train:
#    X
# 0  D
# 1  A
# 2  C
# 3  C
# 4  E
# 5  E
# 6  A

print("X_deploy", X_deploy, sep=':\n', end='\n\n')
# X_deploy:
#    X
# 0  B
# 1  E
# 2  A
# 3  C
# 4  D
# 5  E
# 6  F

print('X_train_transformed', X_train_transformed, sep=':\n', end='\n\n')
# X_train_transformed:
# (array([[2.],
#        [0.],
#        [1.],
#        [1.],
#        [3.],
#        [3.],
#        [0.]], dtype=float32), None, None, [['A', 'C', 'D', 'E']])

print('X_deploy_transformed', X_deploy_transformed, sep=':\n', end='\n\n')
# X_deploy_transformed:
# (array([[1.],
#        [4.],
#        [0.],
#        [2.],
#        [3.],
#        [4.],
#        [5.]], dtype=float32), None, None, [['A', 'B', 'C', 'D', 'E', 'F']])

print('X_train LGB-transformed codes and original Series')
# X_train LGB-transformed codes and original Series

print(*list(zip(X_train_transformed[0], X_train.X.to_list())), sep='\n', end='\n\n')
# (array([2.], dtype=float32), 'D')
# (array([0.], dtype=float32), 'A')
# (array([1.], dtype=float32), 'C')
# (array([1.], dtype=float32), 'C')
# (array([3.], dtype=float32), 'E')
# (array([3.], dtype=float32), 'E')
# (array([0.], dtype=float32), 'A')

print('X_deploy LGB-transformed codes and original Series')
# X_deploy LGB-transformed codes and original Series

print(*list(zip(X_deploy_transformed[0], X_deploy.X.to_list())), sep='\n', end='\n\n')
# (array([1.], dtype=float32), 'B')
# (array([4.], dtype=float32), 'E')
# (array([0.], dtype=float32), 'A')
# (array([2.], dtype=float32), 'C')
# (array([3.], dtype=float32), 'D')
# (array([4.], dtype=float32), 'E')
# (array([5.], dtype=float32), 'F')
</code>```

Body:
Pandas assigns categorical codes by sorting the keys (categories) before assigning the codes, and LightGBM relies on Pandas to handle assigning the categoridcal codes correctly.
Introducing a previously unseen category will break the ordering of the categoricals, and thus shift the categorical codes.

Source: https://github.com/microsoft/LightGBM/issues/2761#issuecomment-586722068

Code to demonstrate the problem:

#!/usr/bin/env python
# -*- coding: utf8 -*-

import pandas as pd
import lightgbm as lgb

X_train = pd.Series(['D', 'A', 'C', 'C', 'E', 'E', 'A'],
                    name='X', dtype='category').to_frame()
X_deploy = pd.Series(['B', 'E', 'A', 'C', 'D', 'E', 'F'],
                     name='X', dtype='category').to_frame()

X_train_transformed = lgb.basic._data_from_pandas(X_train, None, None, None)
X_deploy_transformed = lgb.basic._data_from_pandas(X_deploy, None, None, None)

print("X_train", X_train, sep=':\n', end='\n\n')
# X_train:
#    X
# 0  D
# 1  A
# 2  C
# 3  C
# 4  E
# 5  E
# 6  A

print("X_deploy", X_deploy, sep=':\n', end='\n\n')
# X_deploy:
#    X
# 0  B
# 1  E
# 2  A
# 3  C
# 4  D
# 5  E
# 6  F

print('X_train_transformed', X_train_transformed, sep=':\n', end='\n\n')
# X_train_transformed:
# (array([[2.],
#        [0.],
#        [1.],
#        [1.],
#        [3.],
#        [3.],
#        [0.]], dtype=float32), None, None, [['A', 'C', 'D', 'E']])

print('X_deploy_transformed', X_deploy_transformed, sep=':\n', end='\n\n')
# X_deploy_transformed:
# (array([[1.],
#        [4.],
#        [0.],
#        [2.],
#        [3.],
#        [4.],
#        [5.]], dtype=float32), None, None, [['A', 'B', 'C', 'D', 'E', 'F']])

print('X_train LGB-transformed codes and original Series')
# X_train LGB-transformed codes and original Series

print(*list(zip(X_train_transformed[0], X_train.X.to_list())), sep='\n', end='\n\n')
# (array([2.], dtype=float32), 'D')
# (array([0.], dtype=float32), 'A')
# (array([1.], dtype=float32), 'C')
# (array([1.], dtype=float32), 'C')
# (array([3.], dtype=float32), 'E')
# (array([3.], dtype=float32), 'E')
# (array([0.], dtype=float32), 'A')

print('X_deploy LGB-transformed codes and original Series')
# X_deploy LGB-transformed codes and original Series

print(*list(zip(X_deploy_transformed[0], X_deploy.X.to_list())), sep='\n', end='\n\n')
# (array([1.], dtype=float32), 'B')
# (array([4.], dtype=float32), 'E')
# (array([0.], dtype=float32), 'A')
# (array([2.], dtype=float32), 'C')
# (array([3.], dtype=float32), 'D')
# (array([4.], dtype=float32), 'E')
# (array([5.], dtype=float32), 'F')


问:
Applescript can't make <list> into type specifier -1700 error
Can anyone explain why the following piece of Applescript code returns an error:

```<code>tell application "Photos"
    set idList to {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"}
    set itemList to every media item in application "Photos" where its id is in idList
    log (count of itemList)
end tell
</code>```

The error is:

```<code>error "Photos got an error: Can’t make {\"v3xzjwPQT0y8a844gLHLHWg\", \"v3w3twPQT0y%%844gLgf4Wg\"} into type specifier." number -1700 from {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"} to specifier
</code>```

答:
That feature does seem to be broken in Photos 4.  You can work around it in a couple of ways.  If your list is simple and fixed you can build up a command using or statements like so:

```<code>set itemList to every media item whose id is "wi9HoFU0SKCDianaQBtJBg" or id is "DT29HF1lRgCKOaIZFHoHrQ"
</code>```

If you need something more flexible, you can use a repeat loop and build up the list through individual searches:

```<code>set idList to {"wi9HoFU0SKCDianaQBtJBg", "DT29HF1lRgCKOaIZFHoHrQ"}
tell application "Photos"
    set newList to {}
    repeat with thisID in idList
        set anItem to (first media item whose id is thisID)
        copy anItem to end of newList
    end repeat
end tell
</code>```

Body:
Can anyone explain why the following piece of Applescript code returns an error:

tell application "Photos"
    set idList to {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"}
    set itemList to every media item in application "Photos" where its id is in idList
    log (count of itemList)
end tell

The error is:

error "Photos got an error: Can’t make {\"v3xzjwPQT0y8a844gLHLHWg\", \"v3w3twPQT0y%%844gLgf4Wg\"} into type specifier." number -1700 from {"v3xzjwPQT0y8a844gLHLHWg", "v3w3twPQT0y%%844gLgf4Wg"} to specifier

Body:
That feature does seem to be broken in Photos 4.  You can work around it in a couple of ways.  If your list is simple and fixed you can build up a command using or statements like so:

set itemList to every media item whose id is "wi9HoFU0SKCDianaQBtJBg" or id is "DT29HF1lRgCKOaIZFHoHrQ"

If you need something more flexible, you can use a repeat loop and build up the list through individual searches:

set idList to {"wi9HoFU0SKCDianaQBtJBg", "DT29HF1lRgCKOaIZFHoHrQ"}
tell application "Photos"
    set newList to {}
    repeat with thisID in idList
        set anItem to (first media item whose id is thisID)
        copy anItem to end of newList
    end repeat
end tell


问:
Cannot compile wxWidgets Hello World
So, I was trying to compile hello world example provided by wxWidgets but was unsuccessful in doing so. I will explain what I have done step by step to the current point where I am stuck.

Compiling wxWidgets

First of all, my compiler of choice is MinGw-w64, and since wxWidgets advise to build their library from source (downloaded from wxWidgets download),  I decided to do so using CMake.

I created a directory called cmake inside the root directory of wxWidgets (in my case: C:\C++\wxWidgets-3.1.3). Also I created bin directory for storing the compiled binaries.

I then navigated to the cmake directory and run the following CMake configuration command:```$ cmake -G "MinGW Makefiles" .. -D "wxBUILD_SHARED=OFF" -D "wxBUILD_MONOLITHIC=OFF" -D "CMAKE_BUILD_TYPE=debug" -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe"```then I started the build by using the following command:```$ cmake --build . --target all```The resulting .a files (static library files) were placed in the bin directory.

I repeated the step 3 with the -D "CMAKE_BUILD_TYPE=release" parameter.

The generated lib\gcc_x64_lib\mswu and lib\gcc_x64_lib\mswud directories into the include directory for the convenience (as they contain setup.h header file).

As the result my C:\C++\wxWidgets-3.1.3\bin directory contains following files: ```libwxexpat.a   libwxpngd.a        libwxtiff.a   wxbase31u_net.a   wxmsw31u_adv.a   wxmsw31u_media.a     wxmsw31u_stc.a      wxmsw31ud_core.a      wxmsw31ud_qa.a        wxmsw31ud_xrc.a
libwxexpatd.a  libwxregexu.a      libwxtiffd.a  wxbase31u_xml.a   wxmsw31u_aui.a   wxmsw31u_propgrid.a  wxmsw31u_webview.a  wxmsw31ud_gl.a        wxmsw31ud_ribbon.a    wxrc.exe*
libwxjpeg.a    libwxregexud.a     libwxzlib.a   wxbase31ud.a      wxmsw31u_core.a  wxmsw31u_qa.a        wxmsw31u_xrc.a      wxmsw31ud_html.a      wxmsw31ud_richtext.a
libwxjpegd.a   libwxscintilla.a   libwxzlibd.a  wxbase31ud_net.a  wxmsw31u_gl.a    wxmsw31u_ribbon.a    wxmsw31ud_adv.a     wxmsw31ud_media.a     wxmsw31ud_stc.a
libwxpng.a     libwxscintillad.a  wxbase31u.a   wxbase31ud_xml.a  wxmsw31u_html.a  wxmsw31u_richtext.a  wxmsw31ud_aui.a     wxmsw31ud_propgrid.a  wxmsw31ud_webview.a```

Creating Hello World project

I created simple wxWidgets hello world project with the following file structure: ```app
|   build
|   headers
|   sources
|   |    main.cpp
|   CMakeLists.txt```

The contents of main.cpp:

// wxWidgets "Hello World" Program
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>

#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

class MyApp : public wxApp {
public:
    virtual bool OnInit();
};

class MyFrame : public wxFrame {
public:
    MyFrame();

private:
    void OnHello(wxCommandEvent& event);
    void OnExit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);
};

enum {
    ID_Hello = 1
};

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit() {
    MyFrame *frame = new MyFrame();
    frame->Show(true);
    return true;
}

MyFrame::MyFrame(): wxFrame(NULL, wxID_ANY, "Hello World") {
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item");
    menuFile->AppendSeparator();
    menuFile->Append(wxID_EXIT);

    wxMenu *menuHelp = new wxMenu;
    menuHelp->Append(wxID_ABOUT);

    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, "&File");
    menuBar->Append(menuHelp, "&Help");

    SetMenuBar( menuBar );
    CreateStatusBar();
    SetStatusText("Welcome to wxWidgets!");

    Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
    Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
    Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
}

void MyFrame::OnExit(wxCommandEvent& event) {
    Close(true);
}

void MyFrame::OnAbout(wxCommandEvent& event) {
    wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION);
}

void MyFrame::OnHello(wxCommandEvent& event) {
    wxLogMessage("Hello world from wxWidgets!");
}
```

<p>The contents of <strong><code>CMakeLists.txt</code></strong>:</p>

```cmake_minimum_required(VERSION 2.8)

project(hello_world)

if (MINGW)
    add_compile_options(--static)
endif()

set(wx_libraries_path "C:\\C++\\wxWidgets-3.1.3\\bin")

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswud")
    find_library(libwxexpat       NAMES libwxexpatd        PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpegd         PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpngd          PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexud       PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintillad    PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiffd         PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlibd         PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31ud         PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31ud_net     PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31ud_xml     PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31ud_adv      PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31ud_aui      PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31ud_core     PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31ud_gl       PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31ud_html     PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31ud_media    PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31ud_propgrid PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31ud_qa       PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31ud_ribbon   PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31ud_richtext PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31ud_stc      PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31ud_webview  PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31ud_xrc      PATH ${wx_libraries_path})
endif()

if(CMAKE_BUILD_TYPE STREQUAL "Release")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswu")
    find_library(libwxexpat       NAMES libwxexpat       PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpeg        PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpng         PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexu      PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintilla   PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiff        PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlib        PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31u        PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31u_xml    PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31u_net    PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31u_adv     PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31u_aui     PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31u_core    PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31u_gl      PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31u_html    PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31u_media   PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31u_propgri PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31u_qa      PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31u_ribbon  PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31u_richtex PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31u_stc     PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31u_webview PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31u_xrc     PATH ${wx_libraries_path})
endif()

include_directories("C:\\C++\\wxWidgets-3.1.3\\include")
link_directories("C:\\C++\\wxWidgets-3.1.3\\bin")

add_executable(app sources/main.cpp)

message(STATUS "${libwxexpat}")
target_link_libraries(app PRIVATE
    ${libwxexpat}
    ${libwxjpeg}
    ${libwxpng}
    ${libwxregexu}
    ${libwxscintilla}
    ${libwxtiff}
    ${libwxzlib}
    ${wxbase31u}
    ${wxbase31u_xml}
    ${wxbase31u_net}
    ${wxmsw31u_adv}
    ${wxmsw31u_aui}
    ${wxmsw31u_core}
    ${wxmsw31u_gl}
    ${wxmsw31u_html}
    ${wxmsw31u_media}
    ${wxmsw31u_propgrid}
    ${wxmsw31u_qa}
    ${wxmsw31u_ribbon}
    ${wxmsw31u_richtext}
    ${wxmsw31u_stc}
    ${wxmsw31u_webview}
    ${wxmsw31u_xrc}
)
```

<p>After I created project files I executed following CMake command to configure the project:```cmake -G "MinGW Makefiles" .. -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe" -D "CMAKE_BUILD_TYPE=Debug" -D "CMAKE_VERBOSE_MAKEFILE:BOOL=ON"```
Then I tried and failed to build the project with the following CMake command:```cmake --build .```</p>

<h3>Compilation errors</h3>

<p>Unfortunately, the program fails to compile with, here is the output:</p>

```"C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_start C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\progress.marks
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\Makefile2 all
mingw32-make.exe[1]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/depend
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake --color=
Dependee "C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Dependee "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Scanning dependencies of target app
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/build
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
[ 50%] Building CXX object CMakeFiles/app.dir/sources/main.cpp.obj
C:\C++\MingGW-w64\mingw64\bin\g++.exe   @CMakeFiles/app.dir/includes_CXX.rsp -g   --static -o CMakeFiles\app.dir\sources\main.cpp.obj -c C:\Users\Oiltanker\Git\Pepega-Inject\installer\sources\main.cpp
[100%] Linking CXX executable app.exe
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_link_script CMakeFiles\app.dir\link.txt --verbose=1
"C:\Program Files\CMake\bin\cmake.exe" -E remove -f CMakeFiles\app.dir/objects.a
C:\C++\MingGW-w64\mingw64\bin\ar.exe cr CMakeFiles\app.dir/objects.a @CMakeFiles\app.dir\objects1.rsp
C:\C++\MingGW-w64\mingw64\bin\g++.exe -g   -Wl,--whole-archive CMakeFiles\app.dir/objects.a -Wl,--no-whole-archive  -o app.exe -Wl,--out-implib,libapp.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\app.dir\linklibs.rsp
C:/C++/wxWidgets-3.1.3/bin/wxbase31ud.a(dlmsw.cpp.obj): In function `GetFileVersion':
C:/C++/wxWidgets-3.1.3/src/msw/dlmsw.cpp:67: undefined reference to `GetFileVersionInfoSizeW'
      .......
C:/C++/wxWidgets-3.1.3/src/common/geometry.cpp:350: undefined reference to `wxDataInputStream::Read32()'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [CMakeFiles\app.dir\build.make:110: app.exe] Error 1
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:78: CMakeFiles/app.dir/all] Error 2
mingw32-make.exe[1]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe: *** [Makefile:86: all] Error 2```
</code>```

答:
On top what Vadim said - all you play with CMake and friends to compile wxWidgets are unnecessary.

wxWidgets already provide Makefile to compile the library. The are stored in wxWidgets\build\msw.

So all you could've done is:

```<code>cd C:\C++\wxWidgets-3.1.3\buid\msw
mingw64-make -f makefile.gcc BUILD="debug"
</code>```

Then since wxWidgets already provides the minimal sample for the people to try all you woud be doing is:

```<code>cd C:\C++\wxWidgets\samples\minimal
mingw64-make -f makefile.gcc BUILD="debug"
./minimal.exe
</code>```

This is much simper and would save you a lot of time.

On top of that - just a little suggestion - it looks like you are linking with a lot of libraries that you don't really need. For the minimal sample like this all you really need is wxbase and wxcore. All other are unnecessary.

Thank you.

Title: Cannot compile wxWidgets Hello World

Body:
So, I was trying to compile hello world example provided by wxWidgets but was unsuccessful in doing so. I will explain what I have done step by step to the current point where I am stuck.

Compiling wxWidgets

First of all, my compiler of choice is MinGw-w64, and since wxWidgets advise to build their library from source (downloaded from wxWidgets download),  I decided to do so using CMake.

I created a directory called cmake inside the root directory of wxWidgets (in my case: C:\C++\wxWidgets-3.1.3). Also I created bin directory for storing the compiled binaries.

I then navigated to the cmake directory and run the following CMake configuration command:
$ cmake -G "MinGW Makefiles" .. -D "wxBUILD_SHARED=OFF" -D "wxBUILD_MONOLITHIC=OFF" -D "CMAKE_BUILD_TYPE=debug" -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe"
then I started the build by using the following command:
$ cmake --build . --target all
The resulting .a files (static library files) were placed in the bin directory.

I repeated the step 3 with the -D "CMAKE_BUILD_TYPE=release" parameter.

The generated lib\gcc_x64_lib\mswu and lib\gcc_x64_lib\mswud directories into the include directory for the convenience (as they contain setup.h header file).

As the result my C:\C++\wxWidgets-3.1.3\bin directory contains following files:
libwxexpat.a   libwxpngd.a        libwxtiff.a   wxbase31u_net.a   wxmsw31u_adv.a   wxmsw31u_media.a     wxmsw31u_stc.a      wxmsw31ud_core.a      wxmsw31ud_qa.a        wxmsw31ud_xrc.a
libwxexpatd.a  libwxregexu.a      libwxtiffd.a  wxbase31u_xml.a   wxmsw31u_aui.a   wxmsw31u_propgrid.a  wxmsw31u_webview.a  wxmsw31ud_gl.a        wxmsw31ud_ribbon.a    wxrc.exe*
libwxjpeg.a    libwxregexud.a     libwxzlib.a   wxbase31ud.a      wxmsw31u_core.a  wxmsw31u_qa.a        wxmsw31u_xrc.a      wxmsw31ud_html.a      wxmsw31ud_richtext.a
libwxjpegd.a   libwxscintilla.a   libwxzlibd.a  wxbase31ud_net.a  wxmsw31u_gl.a    wxmsw31u_ribbon.a    wxmsw31ud_adv.a     wxmsw31ud_media.a     wxmsw31ud_stc.a
libwxpng.a     libwxscintillad.a  wxbase31u.a   wxbase31ud_xml.a  wxmsw31u_html.a  wxmsw31u_richtext.a  wxmsw31ud_aui.a     wxmsw31ud_propgrid.a  wxmsw31ud_webview.a

Creating Hello World project

I created simple wxWidgets hello world project with the following file structure:
app
|   build
|   headers
|   sources
|   |    main.cpp
|   CMakeLists.txt

The contents of main.cpp:

// wxWidgets "Hello World" Program
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>

#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

class MyApp : public wxApp {
public:
    virtual bool OnInit();
};

class MyFrame : public wxFrame {
public:
    MyFrame();

private:
    void OnHello(wxCommandEvent& event);
    void OnExit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);
};

enum {
    ID_Hello = 1
};

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit() {
    MyFrame *frame = new MyFrame();
    frame->Show(true);
    return true;
}

MyFrame::MyFrame(): wxFrame(NULL, wxID_ANY, "Hello World") {
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item");
    menuFile->AppendSeparator();
    menuFile->Append(wxID_EXIT);

    wxMenu *menuHelp = new wxMenu;
    menuHelp->Append(wxID_ABOUT);

    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, "&File");
    menuBar->Append(menuHelp, "&Help");

    SetMenuBar( menuBar );
    CreateStatusBar();
    SetStatusText("Welcome to wxWidgets!");

    Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
    Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
    Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
}

void MyFrame::OnExit(wxCommandEvent& event) {
    Close(true);
}

void MyFrame::OnAbout(wxCommandEvent& event) {
    wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION);
}

void MyFrame::OnHello(wxCommandEvent& event) {
    wxLogMessage("Hello world from wxWidgets!");
}

The contents of CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

project(hello_world)

if (MINGW)
    add_compile_options(--static)
endif()

set(wx_libraries_path "C:\\C++\\wxWidgets-3.1.3\\bin")

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswud")
    find_library(libwxexpat       NAMES libwxexpatd        PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpegd         PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpngd          PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexud       PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintillad    PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiffd         PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlibd         PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31ud         PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31ud_net     PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31ud_xml     PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31ud_adv      PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31ud_aui      PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31ud_core     PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31ud_gl       PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31ud_html     PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31ud_media    PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31ud_propgrid PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31ud_qa       PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31ud_ribbon   PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31ud_richtext PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31ud_stc      PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31ud_webview  PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31ud_xrc      PATH ${wx_libraries_path})
endif()

if(CMAKE_BUILD_TYPE STREQUAL "Release")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswu")
    find_library(libwxexpat       NAMES libwxexpat       PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpeg        PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpng         PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexu      PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintilla   PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiff        PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlib        PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31u        PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31u_xml    PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31u_net    PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31u_adv     PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31u_aui     PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31u_core    PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31u_gl      PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31u_html    PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31u_media   PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31u_propgri PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31u_qa      PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31u_ribbon  PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31u_richtex PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31u_stc     PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31u_webview PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31u_xrc     PATH ${wx_libraries_path})
endif()

include_directories("C:\\C++\\wxWidgets-3.1.3\\include")
link_directories("C:\\C++\\wxWidgets-3.1.3\\bin")

add_executable(app sources/main.cpp)

message(STATUS "${libwxexpat}")
target_link_libraries(app PRIVATE
    ${libwxexpat}
    ${libwxjpeg}
    ${libwxpng}
    ${libwxregexu}
    ${libwxscintilla}
    ${libwxtiff}
    ${libwxzlib}
    ${wxbase31u}
    ${wxbase31u_xml}
    ${wxbase31u_net}
    ${wxmsw31u_adv}
    ${wxmsw31u_aui}
    ${wxmsw31u_core}
    ${wxmsw31u_gl}
    ${wxmsw31u_html}
    ${wxmsw31u_media}
    ${wxmsw31u_propgrid}
    ${wxmsw31u_qa}
    ${wxmsw31u_ribbon}
    ${wxmsw31u_richtext}
    ${wxmsw31u_stc}
    ${wxmsw31u_webview}
    ${wxmsw31u_xrc}
)

After I created project files I executed following CMake command to configure the project:
cmake -G "MinGW Makefiles" .. -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe" -D "CMAKE_BUILD_TYPE=Debug" -D "CMAKE_VERBOSE_MAKEFILE:BOOL=ON"

Then I tried and failed to build the project with the following CMake command:
cmake --build .

Compilation errors

Unfortunately, the program fails to compile with, here is the output:

"C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_start C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\progress.marks
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\Makefile2 all
mingw32-make.exe[1]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/depend
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake --color=
Dependee "C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Dependee "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Scanning dependencies of target app
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/build
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
[ 50%] Building CXX object CMakeFiles/app.dir/sources/main.cpp.obj
C:\C++\MingGW-w64\mingw64\bin\g++.exe   @CMakeFiles/app.dir/includes_CXX.rsp -g   --static -o CMakeFiles\app.dir\sources\main.cpp.obj -c C:\Users\Oiltanker\Git\Pepega-Inject\installer\sources\main.cpp
[100%] Linking CXX executable app.exe
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_link_script CMakeFiles\app.dir\link.txt --verbose=1
"C:\Program Files\CMake\bin\cmake.exe" -E remove -f CMakeFiles\app.dir/objects.a
C:\C++\MingGW-w64\mingw64\bin\ar.exe cr CMakeFiles\app.dir/objects.a @CMakeFiles\app.dir\objects1.rsp
C:\C++\MingGW-w64\mingw64\bin\g++.exe -g   -Wl,--whole-archive CMakeFiles\app.dir/objects.a -Wl,--no-whole-archive  -o app.exe -Wl,--out-implib,libapp.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\app.dir\linklibs.rsp
C:/C++/wxWidgets-3.1.3/bin/wxbase31ud.a(dlmsw.cpp.obj): In function `GetFileVersion':
C:/C++/wxWidgets-3.1.3/src/msw/dlmsw.cpp:67: undefined reference to `GetFileVersionInfoSizeW'
      .......
C:/C++/wxWidgets-3.1.3/src/common/geometry.cpp:350: undefined reference to `wxDataInputStream::Read32()'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [CMakeFiles\app.dir\build.make:110: app.exe] Error 1
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:78: CMakeFiles/app.dir/all] Error 2
mingw32-make.exe[1]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe: *** [Makefile:86: all] Error 2```

Body:
On top what Vadim said - all you play with CMake and friends to compile wxWidgets are unnecessary.

wxWidgets already provide Makefile to compile the library. The are stored in wxWidgets\build\msw.

So all you could've done is:

cd C:\C++\wxWidgets-3.1.3\buid\msw
mingw64-make -f makefile.gcc BUILD="debug"

Then since wxWidgets already provides the minimal sample for the people to try all you woud be doing is:

cd C:\C++\wxWidgets\samples\minimal
mingw64-make -f makefile.gcc BUILD="debug"
./minimal.exe

This is much simper and would save you a lot of time.

On top of that - just a little suggestion - it looks like you are linking with a lot of libraries that you don't really need. For the minimal sample like this all you really need is wxbase and wxcore. All other are unnecessary.

Thank you.


问:
.index.get_loc returns TRUE/FALSE instead of integer. Can tell me how to get the index in a dataframe?
I created two different dataframes (DF1 from a CSV file and PSE0 from TXT file).

When I use the .index.get_loc function to get the index (row number) of a value in the dataframe, DF1 would return the correct row number while PSE0 returns TRUE and FALSE.

Code below:

```<code>PSE0=pd.read_csv(os.path.join(PSE_DES,str(Sht1['K4'].value)),delimiter='\t')
PSE0=pd.DataFrame(PSE0,columns=['RIC','EFFECTIVE DATE','CHANGE TYPE','SEQ NUM','DISTRIBUTION AMOUNT'])

DF1 = pd.read_csv(os.path.join(PSE_DES, Files), delimiter='\t')
DF1 = pd.DataFrame(DF1, columns=['RIC', 'IC', 'LOCAL PRICE', 'CS', 'DVD'])

for i in range(0,len(L1)):
    PSE0.set_index('RIC').index.get_loc(L1[i])
    DF1.set_index('RIC').index.get_loc(L1[i])
</code>```

Can you please help?

答:
According to the documentation, there are two types of data that can be returned:

if the index you're looking for is unique, you will get a single int-value

unique_index = pd.Index(list('abcb'))
 unique_index.get_loc('b')
 1

if there are multiple indexes with the same name, you will get an array with boolean

same_index = pd.Index(list('abcb'))
 same_index.get_loc('b')
 array([False,  True, False,  True], dtype=bool)

So I guess, there is a moment where you have duplicates of Indexes, but I don't know at what point.

Body:
I created two different dataframes (DF1 from a CSV file and PSE0 from TXT file).

When I use the .index.get_loc function to get the index (row number) of a value in the dataframe, DF1 would return the correct row number while PSE0 returns TRUE and FALSE.

Code below:

PSE0=pd.read_csv(os.path.join(PSE_DES,str(Sht1['K4'].value)),delimiter='\t')
PSE0=pd.DataFrame(PSE0,columns=['RIC','EFFECTIVE DATE','CHANGE TYPE','SEQ NUM','DISTRIBUTION AMOUNT'])

DF1 = pd.read_csv(os.path.join(PSE_DES, Files), delimiter='\t')
DF1 = pd.DataFrame(DF1, columns=['RIC', 'IC', 'LOCAL PRICE', 'CS', 'DVD'])

for i in range(0,len(L1)):
    PSE0.set_index('RIC').index.get_loc(L1[i])
    DF1.set_index('RIC').index.get_loc(L1[i])

Can you please help?


问:
Unable to use "setValues" in Google Sheets after splitting string into array
I'm not sure, why setting values in one go does not work, after I split a text into an array. The error message is a bit strange:

"Cannot convert array in number[][]"

It works fine though, if I loop through the array and use setValue (without the "s") instead, so I can't figure out what is wrong.

I would appreciate your help. Thanks in advance.

```<code>function Replace() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Sheet1");

  var text ="Might-be-a-system-bug-of-course.";
  var list = text.split("-");

  var listLen = list.length;

  Logger.log(list.length);
  Logger.log(list);

  // This does not work:
  sh.getRange(1, 1, listLen, 1).setValues(list);

  // This works:
  //for (var i = 0; i < listLen; i++) {
  //  sh.getRange(i + 1, 1).setValue(list[i]);
  //}

}
</code>```

答:
setValues requires a two dimensional array:

```<code>function Replace() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Sheet1");

  var text ="It's-almost-never-a-system-bug";
  var list = text.split("-");

  var listLen = list.length;

  Logger.log(list.length);
  Logger.log(list);

  // This work:
  sh.getRange(1, 1, listLen, 1).setValues(list.map(e => [e]));
  sh.getRange(10, 1, 1,listLen).setValues([list]);

  // This works:
  //for (var i = 0; i < listLen; i++) {
  //  sh.getRange(i + 1, 1).setValue(list[i]);
  //}

}
</code>```

Body:
I'm not sure, why setting values in one go does not work, after I split a text into an array. The error message is a bit strange:

"Cannot convert array in number[][]"

It works fine though, if I loop through the array and use setValue (without the "s") instead, so I can't figure out what is wrong.

I would appreciate your help. Thanks in advance.

function Replace() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Sheet1");

  var text ="Might-be-a-system-bug-of-course.";
  var list = text.split("-");

  var listLen = list.length;

  Logger.log(list.length);
  Logger.log(list);

  // This does not work:
  sh.getRange(1, 1, listLen, 1).setValues(list);

  // This works:
  //for (var i = 0; i < listLen; i++) {
  //  sh.getRange(i + 1, 1).setValue(list[i]);
  //}

}

Body:
setValues requires a two dimensional array:

function Replace() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Sheet1");

  var text ="It's-almost-never-a-system-bug";
  var list = text.split("-");

  var listLen = list.length;

  Logger.log(list.length);
  Logger.log(list);

  // This work:
  sh.getRange(1, 1, listLen, 1).setValues(list.map(e => [e]));
  sh.getRange(10, 1, 1,listLen).setValues([list]);

  // This works:
  //for (var i = 0; i < listLen; i++) {
  //  sh.getRange(i + 1, 1).setValue(list[i]);
  //}

}


问:
List Grid Elements
I have managed to make some progress in this part of my assignment but have attached part of the code below that I have made:

```<code>module Grid where

data State = On | Off deriving (Eq, Show)

next :: State -> State
next On = Off
next Off = On

type Row = [State]
type Grid = [[State]]
type Point = (Int,Int)

initialRow      :: Int -> Row
initialRow w    = replicate w Off

updateRow :: Row -> Int -> Row
updateRow  (r:rs) x
    | x==0        = next r:rs
    | otherwise   = r : (updateRow rs (x-1))

update :: Grid -> Point -> Grid
update [[]] (x,y)       =   [[]]
update [(g:gs)] (x,y)   =   [(updateRow (g:gs) x)]
</code>```

As shown in the last line just above, I have managed to get update to work for when x = any Int as shown below (with the xth element inverted) - ghci.

```<code>*Grid> update [[Off,Off,Off,Off]] (2,0)
[[Off,Off,On,Off]]
*Grid>
</code>```

It all comes unstuck however when I try working with multiple lists such as this, or select a certain list within the list to update the xth element:

```<code>*Grid> update [[Off,Off,Off,Off],[Off,Off,Off,Off]] (2,0)
*** Exception: Grid.hs:(24,0)-(25,47): Non-exhaustive patterns in function update
</code>```

I can't seem to 'genralise' a formula in this function.

I also MUST follow THIS type convention:

```<code>updateRow :: Grid -> Point -> Grid
</code>```

Basically, what I would like to do is update from something like this...

```<code>[[Off,Off,Off,Off],
 [Off,Off,Off,Off],
 [Off,Off,Off,Off],
 [Off,Off Off,Off]]
</code>```

to this:

```<code>[[Off,Off,Off,Off],
 [Off,Off,**On**,Off],
 [Off,Off,Off,Off],
 [Off,Off Off,Off]]
</code>```

where 'x' is the value of the element and 'y' is the value of the list within the list IYGWIM.

Thanks in advance.

答:
Here is the solution. After some thought, I came out with the following and filled the final line of the above 'pattern':</p>

```<code>...
update        (g:gs)  (x,y) =  g : update gs (x,(y-1))
</code>```

Title: List Grid Elements

Body:
I have managed to make some progress in this part of my assignment but have attached part of the code below that I have made:

module Grid where

data State = On | Off deriving (Eq, Show)

next :: State -> State
next On = Off
next Off = On

type Row = [State]
type Grid = [[State]]
type Point = (Int,Int)

initialRow      :: Int -> Row
initialRow w    = replicate w Off

updateRow :: Row -> Int -> Row
updateRow  (r:rs) x
    | x==0        = next r:rs
    | otherwise   = r : (updateRow rs (x-1))

update :: Grid -> Point -> Grid
update [[]] (x,y)       =   [[]]
update [(g:gs)] (x,y)   =   [(updateRow (g:gs) x)]

As shown in the last line just above, I have managed to get update to work for when x = any Int as shown below (with the xth element inverted) - ghci.

*Grid> update [[Off,Off,Off,Off]] (2,0)
[[Off,Off,On,Off]]
*Grid>

It all comes unstuck however when I try working with multiple lists such as this, or select a certain list within the list to update the xth element:

*Grid> update [[Off,Off,Off,Off],[Off,Off,Off,Off]] (2,0)
*** Exception: Grid.hs:(24,0)-(25,47): Non-exhaustive patterns in function update

I can't seem to 'genralise' a formula in this function.

I also MUST follow THIS type convention:

updateRow :: Grid -> Point -> Grid

Basically, what I would like to do is update from something like this...

[[Off,Off,Off,Off],
 [Off,Off,Off,Off],
 [Off,Off,Off,Off],
 [Off,Off Off,Off]]

to this:

[[Off,Off,Off,Off],
 [Off,Off,**On**,Off],
 [Off,Off,Off,Off],
 [Off,Off Off,Off]]

where 'x' is the value of the element and 'y' is the value of the list within the list IYGWIM.

Thanks in advance.

Body:
Here is the solution. After some thought, I came out with the following and filled the final line of the above 'pattern':

...
update        (g:gs)  (x,y) =  g : update gs (x,(y-1))


答:
This is the XOR operator, try building your code up from 2 Boolean expressions

See this for more information:
https://python-reference.readthedocs.io/en/latest/docs/operators/bitwise_XOR.html

Title: What does the circumflex accent do in an if condition?

Body:
I have Javascript code here that I have to turn into Python code but I don't really know where to start. The function in question is:

    function test(e, t, n, r) {
        console.log("INPUT = " + e, t, n, r);
        for (var i, o = 0; e < r; e++) {
            if (o > n.length - 1 && (o = 0), e < r) {
                if ((i = t[e] ^ n.charCodeAt(o)) === t[e]) {
                    console.debug("Error decoding sample preview", t[e], n[o], o, n.length, n.charCodeAt(o));
                    break
                }
                t[e] = i
            }
            o++
        }
        console.log("OUTPUT = " + e, t, n, r);
        return e
    }

-- CONSOLE LOG --
    INPUT = 0
    Uint8Array(202710) [206, 159, 164, 117, 53, 55, 51, 165, 41, 229, 254, 16, 113, 47, 55, 181, 50, 67, 149, 232, 52, 122, 205, 82, 123, 46, 153, 176, 98, 65, 35, 67, 149, 42, 168, 50, 49, 118, 103, 161, 37, 35, 17, 189, 28, 104, 207, 169, 134, 45, 98, 52, 57, 183, 182, 227, 179, 177, 53, 55, 49, 54, 170, 183, 228, 187, 49, 60, 157, 132, 200, 192, 193, 148, 52, 49, 53, 51, 80, 216, 210, 71, 156, 203, 206, 193, 98, 52, 127, 223, 206, 155, 244, 49, 53, 38, 182, 176, 162, 196, …]
     1d415717-0c41-b480 50677

    OUTPUT = 50677
    Uint8Array(202710) [255, 251, 144, 68, 0, 0, 2, 146, 4, 213, 157, 36, 64, 2, 85, 129, 10, 115, 164, 140, 0, 75, 248, 101, 74, 25, 180, 128, 1, 117, 18, 110, 247, 30, 144, 2, 0, 18, 83, 144, 16, 20, 32, 138, 49, 88, 172, 157, 183, 0, 0, 0, 1, 135, 135, 135, 135, 128, 0, 0, 0, 1, 135, 135, 135, 143, 0, 17, 255, 176, 240, 240, 240, 240, 0, 0, 0, 4, 97, 239, 255, 119, 255, 255, 255, 236, 0, 0, 71, 239, 255, 255, 192, 0, 0, 17, 135, 135, 143, 244, …]
     1d415717-0c41-b480 50677

I would like to know how to copy the code in Python to receive the same output. Unfortunately, I don't know how this condition works

if ((i = t [e] ^ n.charCodeAt (o)) === t [e]) {

Is there anyone kind enough to write me the code ready or at least explain how to transform it? Thanks so much

My actual Python code:

    bit28 = [x for x in bit28][28::]

          e    t       n         r
          |    |       |         |
          V    V       V         V
    print(e, bit28, trackid, unkownValue)
    temp_i = 0
    temp_o = 0
    for k in range(e, unkownValue):
      if (temp_o > len(trackid) - 1 and (temp_o == 0)):
        print(bit28[k] ^ ord(trackid[temp_o]))
          if((temp_i == bit28[k] ^ ord(trackid[temp_o]) == bit28[k])):
            print("Error decoding sample preview")
            break
          bit28[k] = temp_i
          #print(temp_i)
      temp_o = temp_o + 1
    return k


问:
How to maintain state during recursion in python
I am trying to implement a simple min max algorithm for a tic tac toe game in python I have an issue with the following method:

```<code>def get_best_move(self, board, empty_cells, turns, points=None):
        if points is None:
            points = []

#here I loop trough the empty cells on the board and fill it with 'X' or 'O'
        for cell in empty_cells:
            new_board = copy.deepcopy(board)
            new_turns = turns.copy()

            if turns[-1] == 'X':
              new_board[cell[0]][cell[1]] = 'O'
              new_turns.append('O')
            elif turns[-1] == 'O':
              new_board[cell[0]][cell[1]] = 'X'
              new_turns.append('X')

#here i select all the empty cells after a move
            new_empty_cells = [[index1,index2] for index1,value1 in enumerate(new_board) for index2,value2 in enumerate(value1) if value2==' ']

#here I check if there is a winner and append the points list with 1,0,-1 accordingly
            if self.winner(new_board) == 'X':
                return points.append(-1)
            elif self.winner(new_board) == 'O':
                return points.append(1)
            elif len(new_empty_cells) == 0:
                return points.append(0)
            else:
#here I call this method again if there is no winner or the game is not a draw.
                self.get_best_move(new_board, new_empty_cells, new_turns, points)
            return print(points)
</code>```

the method takes the following arguments:

```<code>board = [[' ',' ',' '],
         [' ',' ',' '],
         [' ',' ',' ']]

empty_cells = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]

turns = ['X']
</code>```

So given a board like this there should be 255168 possible outcomes thus I would expect my points list to contain 255168 values of 1,0,-1 but all I have is this:

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

Ideally I would like to get a separate list for each cell in the for loop. I have a feeling that I am making some pretty obvious mistake but I just can not spot it, so any help would be greatly appreciated.

答:
I'm not really sure I understand your logic there.

I would probably totally ignore board positions that are empty. And keep track of where Xs and Os are instead.

Anyhow

Where you are recursively calling your function
self.get_best_move(new_board, new_empty_cells, new_turns, points) you should either return or add its return value to your list. Not sure, but you're discarding the return value altogether; that can't be right.

return self.get_best_move(new_board, new_empty_cells, new_turns, points)

or

points + self.get_best_move(new_board, new_empty_cells, new_turns, points)

something along those lines.

Body:
I am trying to implement a simple min max algorithm for a tic tac toe game in python I have an issue with the following method:

def get_best_move(self, board, empty_cells, turns, points=None):
        if points is None:
            points = []

#here I loop trough the empty cells on the board and fill it with 'X' or 'O'
        for cell in empty_cells:
            new_board = copy.deepcopy(board)
            new_turns = turns.copy()

            if turns[-1] == 'X':
              new_board[cell[0]][cell[1]] = 'O'
              new_turns.append('O')
            elif turns[-1] == 'O':
              new_board[cell[0]][cell[1]] = 'X'
              new_turns.append('X')

#here i select all the empty cells after a move
            new_empty_cells = [[index1,index2] for index1,value1 in enumerate(new_board) for index2,value2 in enumerate(value1) if value2==' ']

#here I check if there is a winner and append the points list with 1,0,-1 accordingly
            if self.winner(new_board) == 'X':
                return points.append(-1)
            elif self.winner(new_board) == 'O':
                return points.append(1)
            elif len(new_empty_cells) == 0:
                return points.append(0)
            else:
#here I call this method again if there is no winner or the game is not a draw.
                self.get_best_move(new_board, new_empty_cells, new_turns, points)
            return print(points)

the method takes the following arguments:

board = [[' ',' ',' '],
         [' ',' ',' '],
         [' ',' ',' ']]

empty_cells = [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]

turns = ['X']

So given a board like this there should be 255168 possible outcomes thus I would expect my points list to contain 255168 values of 1,0,-1 but all I have is this:

[1]
[1]
[1]
[1]
[1]
[1]

Ideally I would like to get a separate list for each cell in the for loop. I have a feeling that I am making some pretty obvious mistake but I just can not spot it, so any help would be greatly appreciated.


答:
Wrapping element in a tag will do the trick.

  <picture>
          <source
            media="(max-width: 900px)"
            srcset="images/eye1.jpg">

  </picture>
```

Title: Including a href in a picture source media element

Body:
Wrapping element in a tag will do the trick.

<a href="https://www.google.com/">
  <picture>
          <source
            media="(max-width: 900px)"
            srcset="images/eye1.jpg">
          <img
            src="images/eye2.jpg"
            alt="">
  </picture>
</a>


问:
How can I use my custom ImageView with DataBinding?
So I checked this codelab by Google for creating a custom view RatioImageView. It simply extends the ImageView and overrides the OnMeasure() method according to device's viewport's aspect ratio. The code for the same is:

```<code>class RatioImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
): ImageView(context, attrs, defStyleAttr) {

    private val VP_HEIGHT = Resources.getSystem().displayMetrics.heightPixels
    private val VP_WIDTH = Resources.getSystem().displayMetrics.widthPixels
    private val HWR: Float = VP_HEIGHT.toFloat()/VP_WIDTH.toFloat() //height to width ratio

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),(MeasureSpec.getSize(widthMeasureSpec)*HWR).toInt())
    }
}
</code>```

Then I am using this in ListItem view as:

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

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="0dp">

        <com.example.myapp.RatioImageView
            android:id="@+id/target"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:contentDescription="image holder"
            android:scaleType="centerCrop"
            android:background="#757575"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintDimensionRatio="9:16" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

Then in the Adapter, I am using DataBinding to update the views with content as follows:

```<code>override fun onBindViewHolder(holder: HomeItemHolder, position: Int) {
        holder.binding.apply {

              //loadImage() is an extension function added to ImageView class
              target.loadImage(UiUtil.getCustomUrl(photos[position].urls.fullImage, height, width))

            root.setOnClickListener {
                handleClick(position)
            }
        }
}
</code>```

During building, it shows the following error:

Cannot access class 'RatioImageView'. Check your module classpath for missing or conflicting dependencies

i.e. for the line in which target.loadImage(...) is written in OnBindViewHolder()

Also, if I don't use DataBinding for the root layout, then it works fine.

So the question is what needs to be added to RatioImageView? To make it work with DataBinding, considering that here I don't require an XML layout to be associated with the View class.

Here's the onCreateViewHolder()

```<code>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeItemHolder {
        return HomeItemHolder(ItemPhotoListLayoutBinding.inflate(LayoutInflater.from(parent.context)))
}
</code>```

And below is the ViewHolder class:

```<code>inner class HomeItemHolder (val binding: ItemPhotoListLayoutBinding):
        RecyclerView.ViewHolder(binding.root) {
}
</code>```

Also here is the repo in case my code is missing something over here: https://github.com/prafullmishra/CustomImageView

答:
Any custom view should have at least 3 different kinds of constructor implementations which you need to provide before you can access it conveniently:

The one with 1 parameter: RatioImageView(context)

The one with 2 parameters: RatioImageView(context, attrs)

The one with 3 parameters: RatioImageView(context, attrs, defStyleAttr)

While RatioImageView only have the one with 3 parameters which implements ImageView(context, attrs, defStyleAttr). That's why you get that error. You need to define the other 2 constructors as well.

Body:
So I checked this codelab by Google for creating a custom view RatioImageView. It simply extends the ImageView and overrides the OnMeasure() method according to device's viewport's aspect ratio. The code for the same is:

class RatioImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
): ImageView(context, attrs, defStyleAttr) {

    private val VP_HEIGHT = Resources.getSystem().displayMetrics.heightPixels
    private val VP_WIDTH = Resources.getSystem().displayMetrics.widthPixels
    private val HWR: Float = VP_HEIGHT.toFloat()/VP_WIDTH.toFloat() //height to width ratio

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),(MeasureSpec.getSize(widthMeasureSpec)*HWR).toInt())
    }
}

Then I am using this in ListItem view as:

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

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="0dp">

        <com.example.myapp.RatioImageView
            android:id="@+id/target"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:contentDescription="image holder"
            android:scaleType="centerCrop"
            android:background="#757575"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintDimensionRatio="9:16" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Then in the Adapter, I am using DataBinding to update the views with content as follows:

override fun onBindViewHolder(holder: HomeItemHolder, position: Int) {
        holder.binding.apply {

              //loadImage() is an extension function added to ImageView class
              target.loadImage(UiUtil.getCustomUrl(photos[position].urls.fullImage, height, width))

            root.setOnClickListener {
                handleClick(position)
            }
        }
}

During building, it shows the following error:

Cannot access class 'RatioImageView'. Check your module classpath for missing or conflicting dependencies

i.e. for the line in which target.loadImage(...) is written in OnBindViewHolder()

Also, if I don't use DataBinding for the root layout, then it works fine.

So the question is what needs to be added to RatioImageView? To make it work with DataBinding, considering that here I don't require an XML layout to be associated with the View class.

Here's the onCreateViewHolder()

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeItemHolder {
        return HomeItemHolder(ItemPhotoListLayoutBinding.inflate(LayoutInflater.from(parent.context)))
}

And below is the ViewHolder class:

inner class HomeItemHolder (val binding: ItemPhotoListLayoutBinding):
        RecyclerView.ViewHolder(binding.root) {
}

Also here is the repo in case my code is missing something over here: https://github.com/prafullmishra/CustomImageView


问:
How to calculate 1st and 3rd quartiles?
I have DataFrame:

```<code>    time_diff   avg_trips
0   0.450000    1.0
1   0.483333    1.0
2   0.500000    1.0
3   0.516667    1.0
4   0.533333    2.0
</code>```

I want to get 1st quartile, 3rd quartile and median for the column time_diff. To obtain median, I use np.median(df["time_diff"].values).

How can I calculate quartiles?

答:
you can use

```<code>df.describe()
</code>```

which would show the information

Title: How to calculate 1st and 3rd quartiles?

Body:
I have DataFrame:

    time_diff   avg_trips
0   0.450000    1.0
1   0.483333    1.0
2   0.500000    1.0
3   0.516667    1.0
4   0.533333    2.0

I want to get 1st quartile, 3rd quartile and median for the column time_diff. To obtain median, I use np.median(df["time_diff"].values).

How can I calculate quartiles?

Body:
you can use

df.describe()

which would show the information


问:
input tooltop plugin
I am looking for a plugin that displays something like tooltip that I can put html inside.

Something like a datepicker were I have a little image that allows me to open a helper that will assist fill the input.

Do you know such plugin?

答:
qTip is pretty good.

Only issue is you have to define the styles in the JavaScript (last time I used it at least).

Title: input tooltop plugin


问:
How to shrink an array in C?
Having this snippet

```<code>int main() {

  char *obstacles[3*3]

  char map[3][3] = {'D','*',' ',' ',' ',' ','*',' ',' '};

  int k = 0;

  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      if (map[i][j] == '*')
        obstacles[k++] = &map[i][j];
    }
  }
  return 0;
}
</code>```

Leads to me to this situation:

How do I shrink this array to a k-cells array?

答: You can't change the size of the array.  The best you can do is keep track of the number of elements it contains in a separate variable.</p>

Title: How to shrink an array in C?

Body:
Having this snippet

int main() {

  char *obstacles[3*3]

  char map[3][3] = {'D','*',' ',' ',' ',' ','*',' ',' '};

  int k = 0;

  for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 3; j++) {
      if (map[i][j] == '*')
        obstacles[k++] = &map[i][j];
    }
  }
  return 0;
}

Leads to me to this situation:

How do I shrink this array to a k-cells array?


问:
this.$apollo always undefined
I'm trying to use apollo (+ vue, django) but for some reason it won't get loaded/used in a component,this.$apollo is always undefined.

```<code><script>
import { GET_ALL_USERS_QUERY } from '../js/graphql/queries/userQueries.js'
export default {
  name: 'GraphQLTest',
  data() {
    return {
      users: [],
      loading: true
    }
  },
  async mounted() {
    this.loading = true
    this.users = await this.$apollo.query({
      query: GET_ALL_USERS_QUERY
    })
    this.loading = false
  }
}
</script>

  [Vue warn]: Error in mounted hook (Promise/async): "TypeError: Cannot read property 'query' of undefined"
</code>```

main.js

```<code>import Vue from 'vue'
import { router } from './routes.js'
import store from './store.js'
import { createProvider } from './apollo.js'

import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  provide: createProvider(),
  render: h => h(App),
}).$mount('#app')
</code>```

apollo.js

```<code>import Vue from 'vue'
import VueApollo from 'vue-apollo'
import { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'

// Install the vue plugin
Vue.use(VueApollo)

// Name of the localStorage item
const AUTH_TOKEN = 'jwt-token'

// Config
const defaultOptions = {
  httpEndpoint: '/graphql',
  wsEndpoint: null,
  tokenName: AUTH_TOKEN,
  persisting: false,
  websocketsOnly: false,
  ssr: false
}

// Call this in the Vue app file
export function createProvider (options = {}) {
  // Create apollo client
  const { apolloClient, wsClient } = createApolloClient({
    ...defaultOptions,
    ...options
  })
  apolloClient.wsClient = wsClient

  // Create vue apollo provider
  const apolloProvider = new VueApollo({
    defaultClient: apolloClient,
    defaultOptions: {
      $query: {
        loadingKey: 'loading',
        fetchPolicy: 'cache-and-network'
      }
    },
    errorHandler (error) {
      // eslint-disable-next-line no-console
      console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
    }
  })

  return apolloProvider
}

// Manually call this when user log in
export async function onLogin (apolloClient, token) {
  localStorage.setItem(AUTH_TOKEN, token)
  if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient)
  try {
    await apolloClient.resetStore()
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('%cError on cache reset (login)', 'color: orange;', e.message)
  }
}

// Manually call this when user log out
export async function onLogout (apolloClient) {
  localStorage.removeItem(AUTH_TOKEN)
  if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient)
  try {
    await apolloClient.resetStore()
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('%cError on cache reset (logout)', 'color: orange;', e.message)
  }
}
</code>```

Why is apollo never loaded? something missing in the config?

[edit: same thing happens when following the tutorial : ]

```<code>import Vue from "vue"
import App from "./App.vue"
import { router } from './routes.js'
import ApolloClient from "apollo-boost"
import VueApollo from "vue-apollo"

const apolloProvider = new VueApollo({
  defaultClient: new ApolloClient({
    uri: "http://localhost:8000/graphql/"
  })
})

Vue.use(VueApollo)
new Vue({
  router,
  el: "#app",
  provide: apolloProvider.provide(),
  render: h => h(App)
})
</code>```

答: if you created your VUE project using vue-cli > 3  this will cause the issue with this.$apollo equal to undefined.</p>

Title: this.$apollo always undefined

Body:
I'm trying to use apollo (+ vue, django) but for some reason it won't get loaded/used in a component,this.$apollo is always undefined.

  [Vue warn]: Error in mounted hook (Promise/async): "TypeError: Cannot read property 'query' of undefined"

main.js

import Vue from 'vue'
import { router } from './routes.js'
import store from './store.js'
import { createProvider } from './apollo.js'

import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  provide: createProvider(),
  render: h => h(App),
}).$mount('#app')

apollo.js

import Vue from 'vue'
import VueApollo from 'vue-apollo'
import { createApolloClient, restartWebsockets } from 'vue-cli-plugin-apollo/graphql-client'

// Install the vue plugin
Vue.use(VueApollo)

// Name of the localStorage item
const AUTH_TOKEN = 'jwt-token'

// Config
const defaultOptions = {
  httpEndpoint: '/graphql',
  wsEndpoint: null,
  tokenName: AUTH_TOKEN,
  persisting: false,
  websocketsOnly: false,
  ssr: false
}

// Call this in the Vue app file
export function createProvider (options = {}) {
  // Create apollo client
  const { apolloClient, wsClient } = createApolloClient({
    ...defaultOptions,
    ...options
  })
  apolloClient.wsClient = wsClient

  // Create vue apollo provider
  const apolloProvider = new VueApollo({
    defaultClient: apolloClient,
    defaultOptions: {
      $query: {
        loadingKey: 'loading',
        fetchPolicy: 'cache-and-network'
      }
    },
    errorHandler (error) {
      // eslint-disable-next-line no-console
      console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
    }
  })

  return apolloProvider
}

// Manually call this when user log in
export async function onLogin (apolloClient, token) {
  localStorage.setItem(AUTH_TOKEN, token)
  if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient)
  try {
    await apolloClient.resetStore()
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('%cError on cache reset (login)', 'color: orange;', e.message)
  }
}

// Manually call this when user log out
export async function onLogout (apolloClient) {
  localStorage.removeItem(AUTH_TOKEN)
  if (apolloClient.wsClient) restartWebsockets(apolloClient.wsClient)
  try {
    await apolloClient.resetStore()
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log('%cError on cache reset (logout)', 'color: orange;', e.message)
  }
}

Why is apollo never loaded? something missing in the config?

[edit: same thing happens when following the tutorial : ]

import Vue from "vue"
import App from "./App.vue"
import { router } from './routes.js'
import ApolloClient from "apollo-boost"
import VueApollo from "vue-apollo"

const apolloProvider = new VueApollo({
  defaultClient: new ApolloClient({
    uri: "http://localhost:8000/graphql/"
  })
})

Vue.use(VueApollo)
new Vue({
  router,
  el: "#app",
  provide: apolloProvider.provide(),
  render: h => h(App)
})