问:
How to show SVG files in react-native
I want to render images from SVG files generated by illustrator, I am using react-native 0.59, react-native-svg and react-native-svg-uri,
Here's my jsx:

```<code>  <View style={styles.aboutSection}>
              <SvgUri
                width="150"
                height="150"
                source={require('../../assets/images/logo_blue.svg')}
              />
    </View>
</code>```

and my SVG file:

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
<svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="-574 823.3 20 14" style="enable-background:new -574 823.3 20 14;" xml:space="preserve">
<style type="text/css">
    .st0{fill:#2A327B;}
</style>
<g>
    <g transform="translate(-320.000000, -1983.000000)">
        <g transform="translate(40.000000, 1680.000000)">
            <path class="st0" d="M-284,1140.3c-7.4,0-10-7-10-7s3.4-7,10-7c6.7,0,10,7,10,7S-277.3,1140.3-284,1140.3L-284,1140.3z
                 M-284,1129.3c-2.2,0-4,1.8-4,4s1.8,4,4,4s4-1.8,4-4S-281.8,1129.3-284,1129.3L-284,1129.3z M-284,1135.3c-1.1,0-2-0.9-2-2
                s0.9-2,2-2s2,0.9,2,2S-282.9,1135.3-284,1135.3L-284,1135.3z"/>
        </g>
    </g>
</g>
</svg>
</code>```

And is not showing when I debug, what I am missing and is there a better way to show images from SVG files?
Is converting them to jsx using  SVGR is a better approach or there are other ways to do so.

答:
Since the package seems to be no more maintained, after a good time of searching around, I’ve eventually ended up with using custom  web fonts with the help of react-native-icons:

(Optional) Minimizing the size of SVG, I used for this purpose SVG minizer

Convert fonts using icomoon

Add generated font to assets/fonts folder in your root (or any other path)

Add a linker in your packages.json

```<code>    "rnpm": {
        "assets": [
        "./assets/fonts/"
        ]
    }
</code>```

And link it using react-native link

To create a custom icon component I’ve used react-native-icons, it
has a createIconSetFromIcoMoon function to render font generated from  IcoMoon, and also a one generated from Fontello

In my custom component MyIcon.js, I also add the selection.json generated.

```<code>import { createIconSetFromIcoMoon } from 'react-native-vector-icons';
import MyIconConfig from '../../../selection.json';

const MyIcon = createIconSetFromIcoMoon(MyIconConfig, 'MyIcon-icons', 'MyIcon-icons.ttf');
 //name of font I used in the website to generate font and name of ttf files generated
export default MyIcon;
</code>```

I use it in my component, I the names of icons I've found them in demo.html:

```<code><MyIcon
 style={styles.customStyle}
 name="previous"
 size={18}
 color=’red’
/>
</code>```

Note: Make sure you use version >6.3.0 of react-native-icons, and link your assets by running:

```<code>react-native link ./assets/fonts/
</code>```

Title: How to show SVG files in react-native

Body:
I want to render images from SVG files generated by illustrator, I am using react-native 0.59, react-native-svg and react-native-svg-uri,
Here's my jsx:

  <View style={styles.aboutSection}>
              <SvgUri
                width="150"
                height="150"
                source={require('../../assets/images/logo_blue.svg')}
              />
    </View>

and my SVG file:

<?xml version="1.0" encoding="utf-8"?>

<svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="-574 823.3 20 14" style="enable-background:new -574 823.3 20 14;" xml:space="preserve">

<g>
    <g transform="translate(-320.000000, -1983.000000)">
        <g transform="translate(40.000000, 1680.000000)">
            <path class="st0" d="M-284,1140.3c-7.4,0-10-7-10-7s3.4-7,10-7c6.7,0,10,7,10,7S-277.3,1140.3-284,1140.3L-284,1140.3z
                 M-284,1129.3c-2.2,0-4,1.8-4,4s1.8,4,4,4s4-1.8,4-4S-281.8,1129.3-284,1129.3L-284,1129.3z M-284,1135.3c-1.1,0-2-0.9-2-2
                s0.9-2,2-2s2,0.9,2,2S-282.9,1135.3-284,1135.3L-284,1135.3z"/>
        </g>
    </g>
</g>
</svg>

And is not showing when I debug, what I am missing and is there a better way to show images from SVG files?
Is converting them to jsx using  SVGR is a better approach or there are other ways to do so.

Body:
Since the package seems to be no more maintained, after a good time of searching around, I’ve eventually ended up with using custom  web fonts with the help of react-native-icons:

(Optional) Minimizing the size of SVG, I used for this purpose SVG minizer

Convert fonts using icomoon

Add generated font to assets/fonts folder in your root (or any other path)

Add a linker in your packages.json

    "rnpm": {
        "assets": [
        "./assets/fonts/"
        ]
    }

And link it using react-native link

To create a custom icon component I’ve used react-native-icons, it
has a createIconSetFromIcoMoon function to render font generated from  IcoMoon, and also a one generated from Fontello

In my custom component MyIcon.js, I also add the selection.json generated.

import { createIconSetFromIcoMoon } from 'react-native-vector-icons';
import MyIconConfig from '../../../selection.json';

const MyIcon = createIconSetFromIcoMoon(MyIconConfig, 'MyIcon-icons', 'MyIcon-icons.ttf');
 //name of font I used in the website to generate font and name of ttf files generated
export default MyIcon;

I use it in my component, I the names of icons I've found them in demo.html:

<MyIcon
 style={styles.customStyle}
 name="previous"
 size={18}
 color=’red’
/>

Note: Make sure you use version >6.3.0 of react-native-icons, and link your assets by running:

react-native link ./assets/fonts/


来源: stackexchange

答:
Try like this:</p>

```<code>df["RSI"].shift(len(df)-len(df["RSI"].dropna()))
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to concatenate a series of smaller size to the bottom of a pandas dataframe

Body:
I'm trying to concatenate a Series onto the right side of a dataframe with the column name 'RSI'.  However, because the Series is of shorter length than the other columns in the dataframe, I need to ensure that NaN values are appended to the top of the column and not the bottom.  Right now, I've used the following code but I can't find an argument that would allow me to have the desired output.

RSI = pd.Series(RSI)
df = pd.concat((df, RSI.rename('RSI'), axis='columns')

So far, this is my output:

      Dates  Prices   Volumes      RSI
0    2013-02-08  201.68   2893254  47.7357
1    2013-02-11  200.16   2944651  53.3967
2    2013-02-12  200.04   2461779  56.3866
3    2013-02-13  200.09   2169757  60.1845
4    2013-02-14  199.65   3294126  62.1784
5    2013-02-15  200.98   3627887  63.9720
6    2013-02-19  200.32   2998317  62.9671
7    2013-02-20  199.31   3715311  63.9232
8    2013-02-21  198.33   3923051  66.8817
9    2013-02-22  201.09   3107876  72.8258
10   2013-02-25  197.51   3845276  69.6578
11   2013-02-26  199.14   3391562  63.8458
12   2013-02-27  202.33   4185545  64.2776
13   2013-02-28  200.83   4689698  67.2445
14   2013-03-01  202.91   3308544  58.2408
15   2013-03-04  205.19   3693365  57.7058
16   2013-03-05  206.53   3807706  53.7482
17   2013-03-06  208.38   3594899  57.5396
18   2013-03-07  209.42   3884317  53.2722
19   2013-03-08  210.38   3700086  58.6824
20   2013-03-11  210.08   3048901  56.0161
21   2013-03-12  210.55   3591261  60.2066
22   2013-03-13  212.06   3355969  55.3322
23   2013-03-14  215.80   5505484  51.7492
24   2013-03-15  214.92   7935024  47.1241
25   2013-03-18  213.21   3006125  46.9102
26   2013-03-19  213.44   3198577  46.6569
27   2013-03-20  215.06   3019153  54.0822
28   2013-03-21  212.26   5830566  56.2525
29   2013-03-22  212.08   3015847  51.8359
...         ...     ...       ...      ...
1229 2017-12-26  152.83   2479017  80.1930
1230 2017-12-27  153.13   2149257  80.7444
1231 2017-12-28  154.04   2687624  56.4425
1232 2017-12-29  153.42   3327087  56.9183
1233 2018-01-02  154.25   4202503  63.6958
1234 2018-01-03  158.49   9441567  61.1962
1235 2018-01-04  161.70   7556249  61.3816
1236 2018-01-05  162.49   5195764  64.7724
1237 2018-01-08  163.47   5237523  63.0508
1238 2018-01-09  163.83   4341810  53.9559
1239 2018-01-10  164.18   4174105  54.1351
1240 2018-01-11  164.20   3794453  50.6824
1241 2018-01-12  163.14   5031886  43.0222
1242 2018-01-16  163.85   7794195  32.7428
1243 2018-01-17  168.65  11710033  39.4754
1244 2018-01-18  169.12  14259345  37.3409
1245 2018-01-19  162.37  21172488      NaN
1246 2018-01-22  162.60   8480795      NaN
1247 2018-01-23  166.25   7466232      NaN
1248 2018-01-24  165.37   5645003      NaN
1249 2018-01-25  165.47   3302520      NaN
1250 2018-01-26  167.34   3787913      NaN
1251 2018-01-29  166.80   3516995      NaN
1252 2018-01-30  163.62   4902341      NaN
1253 2018-01-31  163.70   4072830      NaN
1254 2018-02-01  162.40   4434242      NaN
1255 2018-02-02  159.03   5251938      NaN
1256 2018-02-05  152.53   8746599      NaN
1257 2018-02-06  155.34   9867678      NaN
1258 2018-02-07  153.85   6149207      NaN

However, I need it to look like this:

          Dates  Prices   Volumes      RSI
0    2013-02-08  201.68   2893254  NaN
1    2013-02-11  200.16   2944651  NaN
2    2013-02-12  200.04   2461779  NaN
3    2013-02-13  200.09   2169757  NaN
4    2013-02-14  199.65   3294126  NaN
5    2013-02-15  200.98   3627887  NaN
6    2013-02-19  200.32   2998317  NaN
7    2013-02-20  199.31   3715311  NaN
8    2013-02-21  198.33   3923051  NaN
9    2013-02-22  201.09   3107876  NaN
10   2013-02-25  197.51   3845276  NaN
11   2013-02-26  199.14   3391562  NaN
12   2013-02-27  202.33   4185545  NaN
13   2013-02-28  200.83   4689698  NaN
14   2013-03-01  202.91   3308544  NaN
15   2013-03-04  205.19   3693365  57.7058
16   2013-03-05  206.53   3807706  53.7482
17   2013-03-06  208.38   3594899  57.5396
18   2013-03-07  209.42   3884317  53.2722
19   2013-03-08  210.38   3700086  58.6824
20   2013-03-11  210.08   3048901  56.0161
21   2013-03-12  210.55   3591261  60.2066
22   2013-03-13  212.06   3355969  55.3322
23   2013-03-14  215.80   5505484  51.7492
24   2013-03-15  214.92   7935024  47.1241
25   2013-03-18  213.21   3006125  46.9102
26   2013-03-19  213.44   3198577  46.6569
27   2013-03-20  215.06   3019153  54.0822
28   2013-03-21  212.26   5830566  56.2525
29   2013-03-22  212.08   3015847  51.8359
...         ...     ...       ...      ...
1229 2017-12-26  152.83   2479017  80.1930
1230 2017-12-27  153.13   2149257  80.7444
1231 2017-12-28  154.04   2687624  56.4425
1232 2017-12-29  153.42   3327087  56.9183
1233 2018-01-02  154.25   4202503  63.6958
1234 2018-01-03  158.49   9441567  61.1962
1235 2018-01-04  161.70   7556249  61.3816
1236 2018-01-05  162.49   5195764  64.7724
1237 2018-01-08  163.47   5237523  63.0508
1238 2018-01-09  163.83   4341810  53.9559
1239 2018-01-10  164.18   4174105  54.1351
1240 2018-01-11  164.20   3794453  50.6824
1241 2018-01-12  163.14   5031886  43.0222
1242 2018-01-16  163.85   7794195  32.7428
1243 2018-01-17  168.65  11710033  39.4754
1244 2018-01-18  169.12  14259345  36.9999
1245 2018-01-19  162.37  21172488  41.1297
1246 2018-01-22  162.60   8480795  12.1231
1247 2018-01-23  166.25   7466232  39.0977
1248 2018-01-24  165.37   5645003  63.6958
1249 2018-01-25  165.47   3302520  56.4425
1250 2018-01-26  167.34   3787913  80.7444
1251 2018-01-29  166.80   3516995  61.1962
1252 2018-01-30  163.62   4902341  58.6824
1253 2018-01-31  163.70   4072830  53.7482
1254 2018-02-01  162.40   4434242  43.0222
1255 2018-02-02  159.03   5251938  61.1962
1256 2018-02-05  152.53   8746599  56.4425
1257 2018-02-06  155.34   9867678  36.0978
1258 2018-02-07  153.85   6149207  41.1311

Thanks for the help.

Body:
Try like this:

df["RSI"].shift(len(df)-len(df["RSI"].dropna()))


问:
RegEx for capturing and replacing digits in a pattern
I would like to replace the 3rd argument in the string with a new number (let's say 100).  The matched string always starts with function, with the first argument either true or false, and with the number as second argument.

                                               Expected
                    |                             |
                    v                             v
'function(true, 0, 15)'   --> 'function(true, 0, 100)'
'function(false, 0, 23)'  --> 'function(false, 0, 100)'
```

<p>I have been reading the related posts but I believe I must have misunderstood some regex concept. The following code is that I had tried but it always replaces the whole string:</p>

<pre class="lang-py prettyprint-override"><code>import re
string = 'function(true, 0, 15)'
regex = re.compile('function\([a-zA-Z]*, [0-9]*, ([0-9]*)\)')
res = re.sub(regex, '100', string)

print(res) # 100
           # Expected: function(true, 0, 100)
</code>```

Question: Could you point me out why the above code doesn't work? How would I write the code to achieve the expected result?

答:
This expression also might work:

```<code>(?:\d+)(\))
</code>```

which has a non-capturing group with our desired digits (?:\d+), followed by a right boundary (\)), which we can replace it with our new number and $1.

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?:\d+)(\))"

test_str = "function(true, 0, 15)"

subst = "100\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

Demo

Body:
I would like to replace the 3rd argument in the string with a new number (let's say 100).  The matched string always starts with function, with the first argument either true or false, and with the number as second argument.

                                               Expected
                    |                             |
                    v                             v
'function(true, 0, 15)'   --> 'function(true, 0, 100)'
'function(false, 0, 23)'  --> 'function(false, 0, 100)'

I have been reading the related posts but I believe I must have misunderstood some regex concept. The following code is that I had tried but it always replaces the whole string:

import re
string = 'function(true, 0, 15)'
regex = re.compile('function\([a-zA-Z]*, [0-9]*, ([0-9]*)\)')
res = re.sub(regex, '100', string)

print(res) # 100
           # Expected: function(true, 0, 100)

Question: Could you point me out why the above code doesn't work? How would I write the code to achieve the expected result?

Body:
This expression also might work:

(?:\d+)(\))

which has a non-capturing group with our desired digits (?:\d+), followed by a right boundary (\)), which we can replace it with our new number and $1.

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(?:\d+)(\))"

test_str = "function(true, 0, 15)"

subst = "100\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

Demo


问:
No module named 'psycopg2' Error in Scrapy
When I use

```<code>import psycopg2
</code>```

in Scrapy pipeline.py or spider.py I get the following error

```<code>ModuleNotFoundError: No module named 'psycopg2'
</code>```

I know that the error is not valid, because I am running Django server with postgresql, using same venv which contains psycopg2. And also I can connect to db in a test file and enquiry as well. In addition I can run import psycopg2 in Scrapy shell with no issue. So it has puzzled me that I might be missing something,
I appreciate if someone can help me,

答:
You need to install psycopg2 in your virtualenv, issue the next command

pip install psycopg2

Body:
When I use

import psycopg2

in Scrapy pipeline.py or spider.py I get the following error

ModuleNotFoundError: No module named 'psycopg2'

I know that the error is not valid, because I am running Django server with postgresql, using same venv which contains psycopg2. And also I can connect to db in a test file and enquiry as well. In addition I can run import psycopg2 in Scrapy shell with no issue. So it has puzzled me that I might be missing something,
I appreciate if someone can help me,


问:
How to check which RecyclerView has been clicked
I have a view with two RecyclerViews. They have different ArrayLists, but the same kind of adapters. In the OnClick method in my activity, I want to get which of the Recyclers has been clicked, and then get the item selected.

I tried using view instanceof RecylcerView but that didn't do the trick.

答:
In your activity's on click listener, you just need to check which View matches the RecyclerView's Row Id.

RecyclerView_row.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recyclerView1I"
android:layout_width="match_parent"
android:layout_height="wrap_content">

   <!---  RecyclerView's other Views -->

</RelativeLayout>
</code>```

MainActivity

```<code>override fun onItemClick(view: View, position: Int) {

     if(view.id == R.id.recyclerView1I){
         //Do stuff
     }
</code>```

This is how you determine which RecyclerView was clicked, assuming you have your OnClickListener Interfaces already setup in your adapters. I wrote this answer in Kotlin but you should be able to easily convert to Java :)

Body:
In your activity's on click listener, you just need to check which View matches the RecyclerView's Row Id.

RecyclerView_row.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/recyclerView1I"
android:layout_width="match_parent"
android:layout_height="wrap_content">

   <!---  RecyclerView's other Views -->

</RelativeLayout>

MainActivity

override fun onItemClick(view: View, position: Int) {

     if(view.id == R.id.recyclerView1I){
         //Do stuff
     }

This is how you determine which RecyclerView was clicked, assuming you have your OnClickListener Interfaces already setup in your adapters. I wrote this answer in Kotlin but you should be able to easily convert to Java :)


问:
How can I find out why Git is suddenly pushing up large amounts of data?
I've been working on a site's theme that consists only of a few .scss and .php files. I've been pushing my work up to Github with git.

Today, as with any other day, I made some changes and went push my files up but I noticed git was pushing up megabytes worth of data, not the usual kilobytes.

Of course I checked the commit and there's nothing special there - just 3 .scss files worth maybe 10kb all up.

I ran git diff --stat --cached origin/master and, again, nothing there that could be megabytes worth of data.

I checked my local and the remote repo - still nothing unusual.

Would anyone know how I could check what's causing the commit to be so large?

答:
I generally go with this question, and use:

```<code>git rev-list --objects --all|git cat-file --batch-check="%(objecttype) %(objectname) %(objectsize) %(rest)"| \
  sed -n "s/^blob //p"| \
  sort --numeric-sort --key=2 | \
  grep -E ".* [[:digit:]]{6,}"
</code>```

That will list only 100KB and more objects.

Body:
I generally go with this question, and use:

git rev-list --objects --all|git cat-file --batch-check="%(objecttype) %(objectname) %(objectsize) %(rest)"| \
  sed -n "s/^blob //p"| \
  sort --numeric-sort --key=2 | \
  grep -E ".* [[:digit:]]{6,}"

That will list only 100KB and more objects.


问:
Reading an audio file from listview item
How can i get to read the audio of a song that i can see in a listview?</p>

```<code>    listAllSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.selectTrack(position);
            mediaPlayer.start();
        }
    });

}
</code>```

答:
Get your audio file from the list using position as index.

```<code>listAllSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.selectTrack(audioList.get(position).getSong()); //use appropriate method to get your audio file
            mediaPlayer.start();
        }
    });
</code>```

Body:
How can i get to read the audio of a song that i can see in a listview?

    listAllSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.selectTrack(position);
            mediaPlayer.start();
        }
    });

}

Body:
Get your audio file from the list using position as index.

listAllSongs.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            MediaPlayer mediaPlayer = new MediaPlayer();
            mediaPlayer.selectTrack(audioList.get(position).getSong()); //use appropriate method to get your audio file
            mediaPlayer.start();
        }
    });


问:
Inferred generic function typechecks as a return type but not an argument type
I'm learning about SYB and rank n types, and came across a confusing case of what seems like the monomorphism restriction.

I wrote a function to find the shallowest entry that matches a predicate. Instead of a reducing function, I wanted to accept a more predicate-like function using Alternative, and transform it into a generic function myself. I decided to omit the type annotation in the let block to see how the monomorphism reduction would affect the type in this implementation:

```<code>shallowest :: (Alternative f, Typeable b) => (b -> f a) -> GenericQ (f a)
shallowest p z =
  let op = (empty `mkQ` p) in
    op z <|> foldl (<|>) empty (gmapQ op z)
</code>```

This produces an error that suggests that the ambiguity in the let binding prevents the typechecker from solving the constraint Data a1.

```<code>Error: • Couldn't match type ‘d’ with ‘a1’
  ‘d’ is a rigid type variable bound by
    a type expected by the context:
      forall d. Data d => d -> m a
  ‘a1’ is a rigid type variable bound by
    the type signature for:
      shallowest :: (b -> m a) -> GenericQ (m a)
</code>```

(Other bodies like head (gmapQ op z) cause an explicit error about ambiguity for the let binding along the lines of "Could not deduce (Typeable a0) arising from a use of ‘mkQ’"; I also haven't figured out why the above form doesn't).

The type error goes away when we add an annotation in the let block for op :: GenericQ (f a) (requiring ScopedTypeVariables).

However, I'm confused that it seems the Data constraint on op can be inferred: the follow typechecks when it's the return type:

```<code>shallowest p = let { op = (empty `mkQ` p) } in op
</code>```

What's the difference? Both cases require op to be forall d. Data d => d -> f a; the only difference I see is that the first is in an argument position and the second is in a return position.

答:
In your second snippet, op is actually not polymorphic.

shallowest p = let { op = (empty `mkQ` p) } in op
```

<p>It is a subtle difference: <code>op</code> is in fact monomorphic, but in an open context. With the usual notation for typing judgements, the typing of <code>op</code> to the right of <code>in</code> looks as follows:</p>

``` types         values
 ↓             ↓
 x, a, f, ...; op :: x -> f a, ... |- op :: x -> f a
                                            ↑
                                            monotype (no "forall")

 In English: "op has type (x -> f a) in the context consisting of type variables (x, a, f, ...) and values (op :: x -> f a, ...)"
```

<p><code>shallowest</code> is made polymorphic by a <em>generalization</em> step that happens at the toplevel. If, in a context with type variables <code>x, a, f, ...</code>, the body of <code>shallowest</code> has type <code>x -> f a</code>, then we can "close the context" and move the type variables into the type of <code>shallowest :: forall x a f. x -> f a</code>. The type derivation looks like this:</p>

```     x, a, f |- (let op = ... in op) :: x -> f a
 ⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻ (generalization)
   |- (let op = .... in op) :: forall x a f. x -> f a
```

(Things are complicated further by type classes and unification algorithms, but that's beside the point of this answer.)

The main problem for typechecking with polymorphism is to decide when generalization should happen. There is no general solution, by lack of principal types and by undecidability. So a typechecker implementation has to make some choices.

In Haskell, generalization happens at the following locations (the list might not be exhaustive), which are fairly natural choices:

function definitions, i.e., let and toplevel bindings with at least one explicit argument (here is the monomorphism restriction);

polymorphic arguments of higher-rank functions: if you have a function f :: (forall a. w a) -> r, then f x is going to generalize a when typechecking x;

and of course, when instructed by an explicit annotation _ :: forall a. t a.

Body:
I'm learning about SYB and rank n types, and came across a confusing case of what seems like the monomorphism restriction.

I wrote a function to find the shallowest entry that matches a predicate. Instead of a reducing function, I wanted to accept a more predicate-like function using Alternative, and transform it into a generic function myself. I decided to omit the type annotation in the let block to see how the monomorphism reduction would affect the type in this implementation:

shallowest :: (Alternative f, Typeable b) => (b -> f a) -> GenericQ (f a)
shallowest p z =
  let op = (empty `mkQ` p) in
    op z <|> foldl (<|>) empty (gmapQ op z)

This produces an error that suggests that the ambiguity in the let binding prevents the typechecker from solving the constraint Data a1.

Error: • Couldn't match type ‘d’ with ‘a1’
  ‘d’ is a rigid type variable bound by
    a type expected by the context:
      forall d. Data d => d -> m a
  ‘a1’ is a rigid type variable bound by
    the type signature for:
      shallowest :: (b -> m a) -> GenericQ (m a)

(Other bodies like head (gmapQ op z) cause an explicit error about ambiguity for the let binding along the lines of "Could not deduce (Typeable a0) arising from a use of ‘mkQ’"; I also haven't figured out why the above form doesn't).

The type error goes away when we add an annotation in the let block for op :: GenericQ (f a) (requiring ScopedTypeVariables).

However, I'm confused that it seems the Data constraint on op can be inferred: the follow typechecks when it's the return type:

shallowest p = let { op = (empty `mkQ` p) } in op

What's the difference? Both cases require op to be forall d. Data d => d -> f a; the only difference I see is that the first is in an argument position and the second is in a return position.

Body:
In your second snippet, op is actually not polymorphic.

shallowest p = let { op = (empty `mkQ` p) } in op

It is a subtle difference: op is in fact monomorphic, but in an open context. With the usual notation for typing judgements, the typing of op to the right of in looks as follows:

 types         values
 ↓             ↓
 x, a, f, ...; op :: x -> f a, ... |- op :: x -> f a
                                            ↑
                                            monotype (no "forall")

 In English: "op has type (x -> f a) in the context consisting of type variables (x, a, f, ...) and values (op :: x -> f a, ...)"

shallowest is made polymorphic by a generalization step that happens at the toplevel. If, in a context with type variables x, a, f, ..., the body of shallowest has type x -> f a, then we can "close the context" and move the type variables into the type of shallowest :: forall x a f. x -> f a. The type derivation looks like this:

     x, a, f |- (let op = ... in op) :: x -> f a
 ⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻⸻ (generalization)
   |- (let op = .... in op) :: forall x a f. x -> f a

(Things are complicated further by type classes and unification algorithms, but that's beside the point of this answer.)

The main problem for typechecking with polymorphism is to decide when generalization should happen. There is no general solution, by lack of principal types and by undecidability. So a typechecker implementation has to make some choices.

In Haskell, generalization happens at the following locations (the list might not be exhaustive), which are fairly natural choices:

function definitions, i.e., let and toplevel bindings with at least one explicit argument (here is the monomorphism restriction);

polymorphic arguments of higher-rank functions: if you have a function f :: (forall a. w a) -> r, then f x is going to generalize a when typechecking x;

and of course, when instructed by an explicit annotation _ :: forall a. t a.


问:
How do I run .py files through the Anaconda interpreter by double-clicking on them in Linux?
I'm setting up my home computer for basic python development. I've managed to install Anaconda through the command line but I'm not sure how to make .py files run through the Anaconda interpreter when double-clicked.

i.e. I did this on my Windows computer at work by right clicking on a .py file and then choosing open with > open with another application > navigating to {C:\Users\\AppData\Local\Continuum\anaconda3} > clicking on python.exe and then clicking 'open'. Is there an equivalent way of doing this on Linux? I'm running Pop!_OS.

I've tried clicking 'open with' but there was no option to open with another application. I also wouldn't know what type of file I would be looking for whereas I knew in Windows I was looking for a .exe

I've also tried right clicking on a .py file, going on the 'Permissions' tab, checking the box for 'Allow executing file as a program' and going to Files > preferences > Behaviour and changed the Executable Text Files option from 'Display them' to 'Run them'.

答:
The most common way on linux to make things executable is by adding the executable flag to the file. On command line, if your file is called script.py:

```<code>chmod +x script.py
</code>```

It is important that your script starts with a description of how to execute it.

For python, your script should start with:

```<code>#!/usr/bin/env python
</code>```

Also, for clarification, there is no .exe file in Linux. The equivalent to that is the previously mentioned executable flag.

Body:
The most common way on linux to make things executable is by adding the executable flag to the file. On command line, if your file is called script.py:

chmod +x script.py

It is important that your script starts with a description of how to execute it.

For python, your script should start with:

#!/usr/bin/env python

Also, for clarification, there is no .exe file in Linux. The equivalent to that is the previously mentioned executable flag.


问:
How we run a .NET 32-bit application in a 64-bit Windows server?
We are installing a third party application in one of our 64-bit Windows servers.  This application apparently was build with the compiler option set to choose the platform at run time.  When we run the application it gives us an error:

```<code>System.BadImageFormatException: is not a valid Win32 application.
</code>```

I have seen in MSDN forums that in order to fix this error I have to build the application set to 32-bit, and that way it will run fine on a 64-bit server.  I check on other StackOverflow links Other Posts.

How to get around this situation?  For everyone that wants to know more information:

The application is running fine in a 32-bit test server.

IIS version 6

using SQL Server Express 2005

On the Web Service Extension there are both Framework64\v2.0.50727\aspnet_isapi.dll

and Framework\v2.0.50727\aspnet_isapi.dll

答:
The details of the question is a little confusing but I'll take a punt.

You need to the version aspnet_regiis.exe found in the Framework\v2.0.50727\ folder against the web site where this code is running

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

Body:
We are installing a third party application in one of our 64-bit Windows servers.  This application apparently was build with the compiler option set to choose the platform at run time.  When we run the application it gives us an error:

System.BadImageFormatException: is not a valid Win32 application.

I have seen in MSDN forums that in order to fix this error I have to build the application set to 32-bit, and that way it will run fine on a 64-bit server.  I check on other StackOverflow links Other Posts.

How to get around this situation?  For everyone that wants to know more information:

The application is running fine in a 32-bit test server.

IIS version 6

using SQL Server Express 2005

On the Web Service Extension there are both Framework64\v2.0.50727\aspnet_isapi.dll

and Framework\v2.0.50727\aspnet_isapi.dll

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: AnthonyWJones


问:
What do you call a DLL that is placed on the same directory as the EXE?
I need a little help in terminology.

You can put an assembly in the GAC to "share" these assembly globally in the machine. What do you call if you put the assembly in the same directory where the executable is?

I have been calling it "side-by-side" because the EXE and the DLL is "side-by-side". I've done some reading and it seems that "side-by-side" stands for something else

EDIT: Are those DLLs called "Private assemblies"?

答: One suggestion is using the terms local versions (NOT GAC) and system versions (GAC)</p>

ContentLicense: CC BY-SA 3.0


问:
Some one can explain why return its not back?
I tried this code work, but I can understand what's happened.

```<code>save: function(req, res){
    // Recoger los parametros de la peticion
    var params = req.body;

    // Validar los datos
    var validate_name = !validator.isEmpty(params.name);
    var validate_surname = !validator.isEmpty(params.surname);;
    var validate_email = !validator.isEmpty(params.email) && validator.isEmail(params.email);
    var validate_password = !validator.isEmpty(params.password);

    if(validate_name && validate_surname && validate_email &&validate_password){
        console.log('Validado');
        // Crear Objeto de usuario
        var user = new User();

        // Asignar valores al usuario
        user.name = params.name;
        user.surname = params.surname;
        user.email = params.email.toLowerCase();
        user.role = 'ROLE_USER';
        user.image = null;

        user.password = bcrypt.hashSync(params.password,10);

        //Comprobar si el usuario existe
        User.findOne({email: user.email}, (err, issetUser) => {
            if(err){
                return res.status(400).send({
                    'message': "Registro de usuario fallido por duplicidad 1"
                });
            }else{
                console.log('Estoy por aca');
                if(!issetUser){
                    console.log('Estoy por aca2');
                    //Guardar el usuario
                    user.save((err, userStored)=>{
                        if(err){
                            return res.status(500).send({
                                'message': "No se pudo grabar el usuario"
                            });
                        } else{
                            if(!userStored){
                                return res.status(500).send({
                                    'message': "No se pudo grabar el usuario"
                                });
                            } else{
                                // Devolver respuesta
                                return res.status(500).send({'message': "Registro de usuario exitoso" });
                            }}
                    });
                    console.log('No deberia estar aca');
                }else{
                    console.log('El usuario esta registrado en la DB');
                    return res.status(500).send({
                        'message': "Registro de usuario fallido 3"
                    });
                }
            }
        });
    }else{
        return res.status(500).send({'message': "El usuario existe en la DB 5"});
    }
    return res.status(500).send({'message': "Registro de usuario fallido 6" });
}
</code>```

for example, I send (by postman) a register than exist in the database. So I expect show in the console: El usuario esta registrado en la DB and return "Registro de usuario fallido 3", but, by console show:

Validado

  Estoy por aca

  El usuario esta registrado en la DB

and crash with message:

throw er; // Unhandled 'error' event

In postman return: "message": "Registro de usuario fallido 6"
So, how the program, continues at the end if i put a return before ?!
why the program crash ?

thank you and sorry for my english

答:
The crash happens because you are calling res.send() twice.

The last line of your code:

```<code>return res.status(500).send({'message': "Registro de usuario fallido 6" });
</code>```

is executed irrespective of the response from mongo.

This is why you get the message "Registro de usuario fallido 6" in postman.

Post that you mongoose request returns with the existing user and you try to call res.send again.

Comment the last line and your code should work fine.

Body:
I tried this code work, but I can understand what's happened.

save: function(req, res){
    // Recoger los parametros de la peticion
    var params = req.body;

    // Validar los datos
    var validate_name = !validator.isEmpty(params.name);
    var validate_surname = !validator.isEmpty(params.surname);;
    var validate_email = !validator.isEmpty(params.email) && validator.isEmail(params.email);
    var validate_password = !validator.isEmpty(params.password);

    if(validate_name && validate_surname && validate_email &&validate_password){
        console.log('Validado');
        // Crear Objeto de usuario
        var user = new User();

        // Asignar valores al usuario
        user.name = params.name;
        user.surname = params.surname;
        user.email = params.email.toLowerCase();
        user.role = 'ROLE_USER';
        user.image = null;

        user.password = bcrypt.hashSync(params.password,10);

        //Comprobar si el usuario existe
        User.findOne({email: user.email}, (err, issetUser) => {
            if(err){
                return res.status(400).send({
                    'message': "Registro de usuario fallido por duplicidad 1"
                });
            }else{
                console.log('Estoy por aca');
                if(!issetUser){
                    console.log('Estoy por aca2');
                    //Guardar el usuario
                    user.save((err, userStored)=>{
                        if(err){
                            return res.status(500).send({
                                'message': "No se pudo grabar el usuario"
                            });
                        } else{
                            if(!userStored){
                                return res.status(500).send({
                                    'message': "No se pudo grabar el usuario"
                                });
                            } else{
                                // Devolver respuesta
                                return res.status(500).send({'message': "Registro de usuario exitoso" });
                            }}
                    });
                    console.log('No deberia estar aca');
                }else{
                    console.log('El usuario esta registrado en la DB');
                    return res.status(500).send({
                        'message': "Registro de usuario fallido 3"
                    });
                }
            }
        });
    }else{
        return res.status(500).send({'message': "El usuario existe en la DB 5"});
    }
    return res.status(500).send({'message': "Registro de usuario fallido 6" });
}

for example, I send (by postman) a register than exist in the database. So I expect show in the console: El usuario esta registrado en la DB and return "Registro de usuario fallido 3", but, by console show:

Validado

  Estoy por aca

  El usuario esta registrado en la DB

and crash with message:

throw er; // Unhandled 'error' event

In postman return: "message": "Registro de usuario fallido 6"
So, how the program, continues at the end if i put a return before ?!
why the program crash ?

thank you and sorry for my english

Body:
The crash happens because you are calling res.send() twice.

The last line of your code:

return res.status(500).send({'message': "Registro de usuario fallido 6" });

is executed irrespective of the response from mongo.

This is why you get the message "Registro de usuario fallido 6" in postman.

Post that you mongoose request returns with the existing user and you try to call res.send again.

Comment the last line and your code should work fine.


问:
vuex empty state on logout
Quick story of my problem:

Absolutely no data is stored in my vuex state when the page loads

If the user is logged in(or has info stored in window.localStorage and therefore gets auto logged in) my vuex store retrieves all the info from a socket that requires authentication.

Then the user logs out, But my vuex state save still retains all its data

This would be a security issue as not logged in people(or hackers) on a public pc could view what the state was before the user logged out.

I have seen How to clear state in vuex store?
But I feel that this is a hack and should be avoided.

My current solution is just to refresh the page using location.reload();

Is there a better way to prevent this data leak?

答:
All objects stored in Vue act as an observable. So if the reference of a value is changed/mutated it triggers the actual value to be changed too.

So, In order to reset the state the initial store modules has to be copied as a value.

On logging out of a user, the same value has to be assigned for each module as a copy.

This can be achieved as follows:

// store.js

// Initial store with modules as an object
export const initialStoreModules = {
    user,
    recruitment,
};

export default new Vuex.Store({
    /**
     * Assign the modules to the store
     * using lodash deepClone to avoid changing the initial store module values
     */
    modules: _.cloneDeep(initialStoreModules),
    mutations: {
        // reset default state modules by looping around the initialStoreModules
        resetState(state) {
        _.forOwn(initialStoreModules, (value, key) => {
            state[key] = _.cloneDeep(value.state);
        });
        },
    }
});
```

Then call commit("resetState"); when the user logs out.

Title: vuex empty state on logout

Body:
All objects stored in Vue act as an observable. So if the reference of a value is changed/mutated it triggers the actual value to be changed too.

So, In order to reset the state the initial store modules has to be copied as a value.

On logging out of a user, the same value has to be assigned for each module as a copy.

This can be achieved as follows:

// store.js

// Initial store with modules as an object
export const initialStoreModules = {
    user,
    recruitment,
};

export default new Vuex.Store({
    /**
     * Assign the modules to the store
     * using lodash deepClone to avoid changing the initial store module values
     */
    modules: _.cloneDeep(initialStoreModules),
    mutations: {
        // reset default state modules by looping around the initialStoreModules
        resetState(state) {
        _.forOwn(initialStoreModules, (value, key) => {
            state[key] = _.cloneDeep(value.state);
        });
        },
    }
});

Then call commit("resetState"); when the user logs out.


问:
"Command not found" after pipe
Some commands return "Command not found" if they are called after a pipe.

I checked if/where they are installed, and in recent versions, and if they are in the $PATH.
Background: MacOS 10.14.5, gnu utilities and other commands installed via homebrew, manually set $PATHS and $MANPATHS.

```<code>$ echo -e ${PATH//:/\\n} | cut -d '/' -f 1
-bash:  cut: Command not found.
$ echo -e ${PATH//:/\\n} | grep '/usr/'
-bash:  grep: Command not found.

$ which cut
/usr/local/opt/coreutils/libexec/gnubin/cut
$ which grep
/usr/local/opt/grep/libexec/gnubin/grep

$ cut --version
cut (GNU coreutils) 8.31...
$ grep --version
grep (GNU grep) 3.3...

$ bash --version
GNU bash, Version 5.0.7(1)-release (x86_64-apple-darwin18.5.0)...

$ echo -e ${PATH//:/\\n}
/usr/local/opt/openssl/bin
/usr/local/opt/coreutils/libexec/gnubin
/usr/local/opt/ed/libexec/gnubin
/usr/local/opt/findutils/libexec/gnubin
/usr/local/opt/gawk/libexec/gnubin
/usr/local/opt/gnu-indent/libexec/gnubin
/usr/local/opt/gnu-sed/libexec/gnubin
/usr/local/opt/gnu-tar/libexec/gnubin
/usr/local/opt/gnu-time/libexec/gnubin
/usr/local/opt/gnu-units/libexec/gnubin
/usr/local/opt/gnu-which/libexec/gnubin
/usr/local/opt/grep/libexec/gnubin
/usr/local/opt/inetutils/libexec/gnubin
/usr/local/opt/make/libexec/gnubin
/Users/xxxx/.jenv/shims
/Users/xxxx/.jenv/bin
/usr/local/opt/icu4c/sbin
/usr/local/opt/icu4c/bin
/usr/local/opt/gettext/bin
/usr/local/opt/binutils/bin
/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin
/opt/X11/bin
/usr/local/opt/e2fsprogs/bin
/usr/local/opt/e2fsprogs/sbin
</code>```

The commands do work in single lines and other multiline inputs:

```<code>$ echo "asdfdfasdfsadf" | cut -c 4-8
fdfas
$ echo "asdfdfasdfsadf" | grep 'df'
asdfdfasdfsadf
$ echo "asdfdfasdfsadf" | grep -v 'df'
$ ls -l | grep aps
drwx------   25 xxxx staff  800 Mai 17 23:33 Maps
</code>```

I also tried sort and xargs after a pipe: same behaviour.

Maybe the multiline return of echo -e ${PATH//:/\\n} is the culprit, or the installation/setup is faulty?

The latter is more likely, because of this:

```<code>$ which cut
/usr/local/opt/coreutils/libexec/gnubin/cut
$ whereis cut
/usr/bin/cut
$ which grep
/usr/local/opt/grep/libexec/gnubin/grep
$ whereis grep
/usr/bin/grep
</code>```

I admit being thoroughly confused.

答:
@Kamil Cuk
All your suggestions worked, via copy-paste. And you were right about the unreadable character.

I opened the bash history in BBEdit and looked for unusual characters, and found \x{A0} (non-breaking space) between | and the following commands.

...And because I always had reused the line via up-arrow key, that gremlin had persisted in all tries.

Thank you for your fast help! Can you make the comment an answer?

Title: "Command not found" after pipe

Body:
Some commands return "Command not found" if they are called after a pipe.

I checked if/where they are installed, and in recent versions, and if they are in the $PATH.
Background: MacOS 10.14.5, gnu utilities and other commands installed via homebrew, manually set $PATHS and $MANPATHS.

$ echo -e ${PATH//:/\\n} | cut -d '/' -f 1
-bash:  cut: Command not found.
$ echo -e ${PATH//:/\\n} | grep '/usr/'
-bash:  grep: Command not found.

$ which cut
/usr/local/opt/coreutils/libexec/gnubin/cut
$ which grep
/usr/local/opt/grep/libexec/gnubin/grep

$ cut --version
cut (GNU coreutils) 8.31...
$ grep --version
grep (GNU grep) 3.3...

$ bash --version
GNU bash, Version 5.0.7(1)-release (x86_64-apple-darwin18.5.0)...

$ echo -e ${PATH//:/\\n}
/usr/local/opt/openssl/bin
/usr/local/opt/coreutils/libexec/gnubin
/usr/local/opt/ed/libexec/gnubin
/usr/local/opt/findutils/libexec/gnubin
/usr/local/opt/gawk/libexec/gnubin
/usr/local/opt/gnu-indent/libexec/gnubin
/usr/local/opt/gnu-sed/libexec/gnubin
/usr/local/opt/gnu-tar/libexec/gnubin
/usr/local/opt/gnu-time/libexec/gnubin
/usr/local/opt/gnu-units/libexec/gnubin
/usr/local/opt/gnu-which/libexec/gnubin
/usr/local/opt/grep/libexec/gnubin
/usr/local/opt/inetutils/libexec/gnubin
/usr/local/opt/make/libexec/gnubin
/Users/xxxx/.jenv/shims
/Users/xxxx/.jenv/bin
/usr/local/opt/icu4c/sbin
/usr/local/opt/icu4c/bin
/usr/local/opt/gettext/bin
/usr/local/opt/binutils/bin
/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin
/opt/X11/bin
/usr/local/opt/e2fsprogs/bin
/usr/local/opt/e2fsprogs/sbin

The commands do work in single lines and other multiline inputs:

$ echo "asdfdfasdfsadf" | cut -c 4-8
fdfas
$ echo "asdfdfasdfsadf" | grep 'df'
asdfdfasdfsadf
$ echo "asdfdfasdfsadf" | grep -v 'df'
$ ls -l | grep aps
drwx------   25 xxxx staff  800 Mai 17 23:33 Maps

I also tried sort and xargs after a pipe: same behaviour.

Maybe the multiline return of echo -e ${PATH//:/\\n} is the culprit, or the installation/setup is faulty?

The latter is more likely, because of this:

$ which cut
/usr/local/opt/coreutils/libexec/gnubin/cut
$ whereis cut
/usr/bin/cut
$ which grep
/usr/local/opt/grep/libexec/gnubin/grep
$ whereis grep
/usr/bin/grep

I admit being thoroughly confused.


问:
Is the code signature crucial to prove ownership?
I am developing an iOS game (closed source), but working in partnership with publisher company. The ownership should be mine and then I should authorize the publisher to just distribute the game in some countries/regions via legal agreement. However I need to sign the code with p12 cert and a provisioning profile... The publisher sent me their certificates, but is it safe to use them since I should remain the owner of the game?</p>

答:
To be on the safer side I would suggest you to add the publisher's apple Id to your team(in your apple Id). You can then assign particular roles to the publisher and restrict the actions which can be performed. You car get more detailed information from below sources :

https://developer.apple.com/support/roles/

https://sandeshsardar.com/2017/04/01/how-to-manage-your-developer-account-team/

Hope this helps you in some way.


问:
Python JSON Google Translator parsing with Simplejson problem
I am trying to parse the Google Translation result using simplejson in Python. But I am getting the following Exception.

```<code>Traceback (most recent call last):
  File "Translator.py", line 45, in <module>
    main()
  File "Translator.py", line 41, in main
    parse_json(trans_text)
  File "Translator.py", line 29, in parse_json
    json = simplejson.loads(str(trans_text))
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 418, in raw_decode
    obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting property name: line 1 column 1 (char 1)
</code>```

This is my json object looks like

```<code>{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}
</code>```

could anyone tell me what is the problem here?

答:
JSON syntax doesn’t support full syntax of JavaScript. Unlike JavaScript, JSON strings and attribute names have to be double-quoted.

string ::= "" | " chars "

Body:
I am trying to parse the Google Translation result using simplejson in Python. But I am getting the following Exception.

Traceback (most recent call last):
  File "Translator.py", line 45, in <module>
    main()
  File "Translator.py", line 41, in main
    parse_json(trans_text)
  File "Translator.py", line 29, in parse_json
    json = simplejson.loads(str(trans_text))
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/__init__.py", line 385, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 402, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.6/dist-packages/simplejson-2.1.3-py2.6-linux-i686.egg/simplejson/decoder.py", line 418, in raw_decode
    obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting property name: line 1 column 1 (char 1)

This is my json object looks like

{'translations': [{'translatedText': 'fleur'}, {'translatedText': 'voiture'}]}

could anyone tell me what is the problem here?


问:
Error when running npm run prod in production
I'm experiencing the same error over and over again when I run npm run prod in my VPS. There is no issue with my local dev machine:

This is the error message, my app is a Laravel app with Vue, I use laravel-mix to compile my assets, my production dev is a DigitalOcean VPS with Ubuntu and LEMP stack:

```<code>
$ npm run prod

> @ prod /var/www/dtcburger.es
> npm run production

> @ production /var/www/dtcburger.es
> cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

internal/child_process.js:313
    throw errnoException(err, 'spawn');
    ^

Error: spawn ENOMEM
    at ChildProcess.spawn (internal/child_process.js:313:11)
    at exports.spawn (child_process.js:508:9)
    at Object.exports.fork (child_process.js:109:10)
    at fork (/var/www/dtcburger.es/node_modules/worker-farm/lib/fork.js:17:36)
    at Farm.startChild (/var/www/dtcburger.es/node_modules/worker-farm/lib/farm.js:106:16)
    at Farm.processQueue (/var/www/dtcburger.es/node_modules/worker-farm/lib/farm.js:279:10)
    at Farm.<anonymous> (/var/www/dtcburger.es/node_modules/worker-farm/lib/farm.js:97:21)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ production: `cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ production script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/gabotron/.npm/_logs/2019-05-26T16_59_29_167Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ prod: `npm run production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ prod script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/gabotron/.npm/_logs/2019-05-26T16_59_29_200Z-debug.log
</code>```

答:
You might have forgotten to do npm install first. Also maybe composer install. It's hard to say as the error message is rather unspecific. It might be helpful to see the contents of:

/home/gabotron/.npm/_logs/2019-05-26T16_59_29_167Z-debug.log

Body:
I'm experiencing the same error over and over again when I run npm run prod in my VPS. There is no issue with my local dev machine:

This is the error message, my app is a Laravel app with Vue, I use laravel-mix to compile my assets, my production dev is a DigitalOcean VPS with Ubuntu and LEMP stack:

$ npm run prod

> @ prod /var/www/dtcburger.es
> npm run production

> @ production /var/www/dtcburger.es
> cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

internal/child_process.js:313
    throw errnoException(err, 'spawn');
    ^

Error: spawn ENOMEM
    at ChildProcess.spawn (internal/child_process.js:313:11)
    at exports.spawn (child_process.js:508:9)
    at Object.exports.fork (child_process.js:109:10)
    at fork (/var/www/dtcburger.es/node_modules/worker-farm/lib/fork.js:17:36)
    at Farm.startChild (/var/www/dtcburger.es/node_modules/worker-farm/lib/farm.js:106:16)
    at Farm.processQueue (/var/www/dtcburger.es/node_modules/worker-farm/lib/farm.js:279:10)
    at Farm.<anonymous> (/var/www/dtcburger.es/node_modules/worker-farm/lib/farm.js:97:21)
    at ontimeout (timers.js:498:11)
    at tryOnTimeout (timers.js:323:5)
    at Timer.listOnTimeout (timers.js:290:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ production: `cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ production script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/gabotron/.npm/_logs/2019-05-26T16_59_29_167Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ prod: `npm run production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ prod script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/gabotron/.npm/_logs/2019-05-26T16_59_29_200Z-debug.log


问:
How to remove the title block from the mobile version in wordpress
Here is the image for an overview

I want to remove the yellow portion with the title means the total block but there is a problem I can't inspect element as that is a static page and I have used wptouch to redirect to the custom mobile version website and only customized for mobile version, not tablet or desktop and the page is made using elementor so please provide any solution for this to solve the problem for the mobile version created page using elementor.

答: you can use wp_is_mobile() function to check for mobile device if it’s a static page. </p>


问:
How does ListView save items data?
Let I have a StatefulWidget with

```<code>ListView.builder(
  itemBuilder: (ctx, i) => TextField(),
  itemCount: _count,
)
</code>```

inside. When I do

```<code>setState(() {
  _count += 1;
});
</code>```

the ListView rebuilds, but all data entered in text fields is kept. Complete example

How does it work? How do I achieve such behavior in custom widgets?

答:
TextField creates default TextEditingController for itself, if no controller was assigned to it initially.

Also, didUpdateWidget method is used to maintain & update TextField's State. On rebuild TextField reuses the value from its previous TextEditingController.

I assume that is the method you are looking for, as it gets called whenever a parent widget rebuilds and requests its subtree to present new states.

For instance, this is how didUpdateWidget is used by TextField:

@override
void didUpdateWidget(TextField oldWidget) {
  super.didUpdateWidget(oldWidget);

  if (widget.controller == null && oldWidget.controller != null)
    _controller = TextEditingController.fromValue(oldWidget.controller.value);
  else if (widget.controller != null && oldWidget.controller == null)
    _controller = null;

  // ...
}
```

Title: How does ListView save items data?

Body:
Let I have a StatefulWidget with

ListView.builder(
  itemBuilder: (ctx, i) => TextField(),
  itemCount: _count,
)

inside. When I do

setState(() {
  _count += 1;
});

the ListView rebuilds, but all data entered in text fields is kept. Complete example

How does it work? How do I achieve such behavior in custom widgets?


问:
CMake subdirectories dependency
I am very new to CMake. In fact, I am trying it through Kdevelop4 widh C++.

I have the habit of creating subdirs for every namespace I create, even if all the sources must be compiled and linked into a single executable. Well, when i create a directory under kdevelop, it updates CMakeLists.txt with a add_subdirectory command and creates a new CMakeLists.txt under it, but that alone does not add the sources under it to the compilation list.

I have the root CMakeLists.txt as follows:

```

project(gear2d)

add_executable(gear2d object.cc main.cc)

add_subdirectory(component)
```

Under component/ I have the sources I want to be compiled and linked to produce the gear2d executables. How can I accomplish that?

CMake FAQ have this entry but if thats the answer I'd rather stay with plain Makefiles.

Is there a way of doing this?

答:
Adding a subdirectory does not do much more than specify to CMake that it should enter the directory and look for another CMakeLists.txt there. You still need to create a library with the source files with add_library and link it to your executable with target_link_libraries. Something like the following:

In the subdir CMakeLists.txt

```<code>set( component_SOURCES ... ) # Add the source-files for the component here
# Optionally you can use file glob (uncomment the next line)
# file( GLOB component_SOURCES *.cpp )below

add_library( component ${component_SOURCES} )
</code>```

Top-dir CMakeLists.txt

```<code>project( gear2d )
add_subdirectory( component )
add_executable( gear2d object.cc main.cc )
target_link_libraries( gear2d component )
</code>```

Title: CMake subdirectories dependency

Body:
I am very new to CMake. In fact, I am trying it through Kdevelop4 widh C++.

I have the habit of creating subdirs for every namespace I create, even if all the sources must be compiled and linked into a single executable. Well, when i create a directory under kdevelop, it updates CMakeLists.txt with a add_subdirectory command and creates a new CMakeLists.txt under it, but that alone does not add the sources under it to the compilation list.

I have the root CMakeLists.txt as follows:

project(gear2d)

add_executable(gear2d object.cc main.cc)

add_subdirectory(component)

Under component/ I have the sources I want to be compiled and linked to produce the gear2d executables. How can I accomplish that?

CMake FAQ have this entry but if thats the answer I'd rather stay with plain Makefiles.

Is there a way of doing this?

Body:
Adding a subdirectory does not do much more than specify to CMake that it should enter the directory and look for another CMakeLists.txt there. You still need to create a library with the source files with add_library and link it to your executable with target_link_libraries. Something like the following:

In the subdir CMakeLists.txt

set( component_SOURCES ... ) # Add the source-files for the component here
# Optionally you can use file glob (uncomment the next line)
# file( GLOB component_SOURCES *.cpp )below

add_library( component ${component_SOURCES} )

Top-dir CMakeLists.txt

project( gear2d )
add_subdirectory( component )
add_executable( gear2d object.cc main.cc )
target_link_libraries( gear2d component )


问:
postgresql serial pk reverts to integer after restore
I built a db with serial type for the pks, I migrated to another server and the pk columns are now integer and as a result I cannot add new data due to the not null restriction of a pk. Is there any Alter command which can fix this?</p>

答:
SERIAL is not a data type in postgresql just a convenience word when creating tables that makes the column an integer type and adds auto-incrementing. All you have to do is add back auto-incrementing (a sequence) to the column and make sure its next value is greater than anything in the table.

This question covers adding serial to an existing column

This answer explains how to reset the counter


问:
realm updating data + DispatchQueue
I have update DataBase in background. My data can contain ~2000 items and it take time to update.

```<code>func updateData(items: [JSON], _ complete:@escaping() -> Void) {
    DispatchQueue.global(qos: .userInitiated).async {

       let currentModels = EgrnModel.getAllModels()
       var newModels: [EgrnModel] = []
       var toDelete: [EgrnModel] = []

       for model in currentModels {
           let contain = items.contains(where: {$0["id"].intValue == model.id})
           if !contain {
               toDelete.append(model)
           }
       }

       let realm = try! Realm()
       try! realm.write {
           for item in items {
               if let model = currentModels.first(where: {$0.id == item["id"].intValue}) {
                   model.update(item)
               }
               else {
                   newModels.append(EgrnModel(item))
               }
           }
           realm.delete(toDelete)
           realm.add(newModels)
       }

       DispatchQueue.main.async {
           complete()
       }
    }
}
</code>```

and I have a function in which I need update data momentarily. When I tap checkmark I have a freeze. (I think it because at this time other data is updating in background)

```<code>func checkMark(index: Int) {

    let model = models[index]
    let realm = try! Realm()

    try! realm.write {
        model.needToUpdateOnServer = true
        model.lastEditUpdate = Date()
        model.read = true
    }
}
</code>```

I try next code to fix a freeze. But in this code I have a crash Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.

```<code>func checkMark(index: Int) {

    let model = models[index]

    DispatchQueue.global(qos: .userInitiated).async {

        let realm = try! Realm()

        try! realm.write {
            model.needToUpdateOnServer = true
            model.lastEditUpdate = Date()
            model.read = true
        }
    }
}
</code>```

答:
What you need to is "move" realm objects from one thread to another because realm objects are not thread-safe but Thread Confined. To achieve this you have to use ThreadSafeReference API.

To solve this problem do the following:

Create an extension on the realm class

```<code>extension Realm {
    func writeAsync<T : ThreadConfined>(obj: T, errorHandler: @escaping ((_ error : Swift.Error) -> Void) = { _ in return }, block: @escaping ((Realm, T?) -> Void)) {
        let wrappedObj = ThreadSafeReference(to: obj)
        let config = self.configuration
        DispatchQueue(label: "background").async {
            autoreleasepool {
                do {
                    let realm = try Realm(configuration: config)
                    let obj = realm.resolve(wrappedObj)

                    try realm.write {
                        block(realm, obj)
                    }
                }
                catch {
                    errorHandler(error)
                }
            }
        }
    }
}
</code>```

Use it in your code this way

```<code>func checkMark(index: Int) {

    let model = models[index]
    let realm = try! Realm()

    realm.asyncWrite(model) { realm, model in
        model.needToUpdateOnServer = true
        model.lastEditUpdate = Date()
        model.read = true
    }
}
</code>```

HAPPY SWIFTING!

Title: realm updating data + DispatchQueue

Body:
I have update DataBase in background. My data can contain ~2000 items and it take time to update.

func updateData(items: [JSON], _ complete:@escaping() -> Void) {
    DispatchQueue.global(qos: .userInitiated).async {

       let currentModels = EgrnModel.getAllModels()
       var newModels: [EgrnModel] = []
       var toDelete: [EgrnModel] = []

       for model in currentModels {
           let contain = items.contains(where: {$0["id"].intValue == model.id})
           if !contain {
               toDelete.append(model)
           }
       }

       let realm = try! Realm()
       try! realm.write {
           for item in items {
               if let model = currentModels.first(where: {$0.id == item["id"].intValue}) {
                   model.update(item)
               }
               else {
                   newModels.append(EgrnModel(item))
               }
           }
           realm.delete(toDelete)
           realm.add(newModels)
       }

       DispatchQueue.main.async {
           complete()
       }
    }
}

and I have a function in which I need update data momentarily. When I tap checkmark I have a freeze. (I think it because at this time other data is updating in background)

func checkMark(index: Int) {

    let model = models[index]
    let realm = try! Realm()

    try! realm.write {
        model.needToUpdateOnServer = true
        model.lastEditUpdate = Date()
        model.read = true
    }
}

I try next code to fix a freeze. But in this code I have a crash Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.

func checkMark(index: Int) {

    let model = models[index]

    DispatchQueue.global(qos: .userInitiated).async {

        let realm = try! Realm()

        try! realm.write {
            model.needToUpdateOnServer = true
            model.lastEditUpdate = Date()
            model.read = true
        }
    }
}

Body:
What you need to is "move" realm objects from one thread to another because realm objects are not thread-safe but Thread Confined. To achieve this you have to use ThreadSafeReference API.

To solve this problem do the following:

Create an extension on the realm class

extension Realm {
    func writeAsync<T : ThreadConfined>(obj: T, errorHandler: @escaping ((_ error : Swift.Error) -> Void) = { _ in return }, block: @escaping ((Realm, T?) -> Void)) {
        let wrappedObj = ThreadSafeReference(to: obj)
        let config = self.configuration
        DispatchQueue(label: "background").async {
            autoreleasepool {
                do {
                    let realm = try Realm(configuration: config)
                    let obj = realm.resolve(wrappedObj)

                    try realm.write {
                        block(realm, obj)
                    }
                }
                catch {
                    errorHandler(error)
                }
            }
        }
    }
}

Use it in your code this way

func checkMark(index: Int) {

    let model = models[index]
    let realm = try! Realm()

    realm.asyncWrite(model) { realm, model in
        model.needToUpdateOnServer = true
        model.lastEditUpdate = Date()
        model.read = true
    }
}

HAPPY SWIFTING!


问:
Why is my node script waiting 60 seconds to terminate after a Cloud Firestore query?
When I run this script from the command line (node script.js), it seems to work fine. All the activities from Firestore get printed to the console, followed by "done.". But then the script doesn't exit right away. It hangs for exactly 60 seconds, and then I get my prompt back. What's up with that?

Update: Yes, this is the whole script.

```<code>const firebase = require('firebase')

const config = {
  apiKey: 'AIzaSyBmauMItX-bkUO1GGO_Nvrycy1Y6Pj1o_s',
  authDomain: 'fir-test-app-501b1.firebaseapp.com',
  databaseURL: 'https://fir-test-app-501b1.firebaseio.com',
  projectId: 'fir-test-app-501b1',
}

firebase.initializeApp(config)
firebase.firestore().collection('activities')
  .get()
  .then(qs => qs.docs.forEach(doc => console.log(doc.data())))
  .then(() => console.log('done.'))
</code>```

I am using Node v8.11.3 and Firebase v5.11.1. GitHub link: https://github.com/danbockapps/firebase60

答:
Here you go:

```<code>var firebaseApp = firebase.initializeApp(config);
var database = firebase.firestore();

database.collection('activities')
  .get()
  .then(qs => qs.docs.forEach(doc => console.log(doc.data())))
  .then(() => {
      console.log('done.');
      firebaseApp.delete();
      // database.disableNetwork(); // Another way to do this, though not as clean
  });
</code>```

Managed to dig into the code of the .get() call on the collection and see that there is a 60 second timeout in AsyncQueue that lives after everything is done. Figured there must be a disconnect switch somewhere that shortcircuits the inner timers that that google library runs on and found it in firebaseApp.delete() which does the following according to its docs:

(method) firebase.app.App.delete(): Promise

Renders this app unusable and frees the resources of all associated services.

This works for 5.11.1 as well as 6.0.4, I highly recommend upgrading now while you're early in the project. I was using the npm package firebase-admin instead of firebase like you're using and did NOT need to make this call to free resources.

Body:
When I run this script from the command line (node script.js), it seems to work fine. All the activities from Firestore get printed to the console, followed by "done.". But then the script doesn't exit right away. It hangs for exactly 60 seconds, and then I get my prompt back. What's up with that?

Update: Yes, this is the whole script.

const firebase = require('firebase')

const config = {
  apiKey: 'AIzaSyBmauMItX-bkUO1GGO_Nvrycy1Y6Pj1o_s',
  authDomain: 'fir-test-app-501b1.firebaseapp.com',
  databaseURL: 'https://fir-test-app-501b1.firebaseio.com',
  projectId: 'fir-test-app-501b1',
}

firebase.initializeApp(config)
firebase.firestore().collection('activities')
  .get()
  .then(qs => qs.docs.forEach(doc => console.log(doc.data())))
  .then(() => console.log('done.'))

I am using Node v8.11.3 and Firebase v5.11.1. GitHub link: https://github.com/danbockapps/firebase60

Body:
Here you go:

var firebaseApp = firebase.initializeApp(config);
var database = firebase.firestore();

database.collection('activities')
  .get()
  .then(qs => qs.docs.forEach(doc => console.log(doc.data())))
  .then(() => {
      console.log('done.');
      firebaseApp.delete();
      // database.disableNetwork(); // Another way to do this, though not as clean
  });

Managed to dig into the code of the .get() call on the collection and see that there is a 60 second timeout in AsyncQueue that lives after everything is done. Figured there must be a disconnect switch somewhere that shortcircuits the inner timers that that google library runs on and found it in firebaseApp.delete() which does the following according to its docs:

(method) firebase.app.App.delete(): Promise

Renders this app unusable and frees the resources of all associated services.

This works for 5.11.1 as well as 6.0.4, I highly recommend upgrading now while you're early in the project. I was using the npm package firebase-admin instead of firebase like you're using and did NOT need to make this call to free resources.


问:
How to clear state in vuex store?
My state in vuex store is huge.

Is there a way to reset all the data in state in one go, instead of manually setting everything to null?

答:
Myself has read above and implemented a solution. could help you as well!!

All objects stored in Vue act as an observable. So if reference of a  value is changed/mutated it triggers the actual value to be changed too.

So, Inorder to reset the state the initial store modules has to be copied as a value.

On logging out of an user, the same value has to be assigned for each modules as a copy.

This can be achieved as following:

Step 1: Create a copy of your initial module.

```<code>// store.ts

// Initial store with modules as an object
export const initialStoreModules = {
    user,
    recruitment,
};

export default new Vuex.Store({
    /**
     * Assign the modules to the store
     * using lodash deepClone to avoid changing the initial store module values
     */
    modules: _.cloneDeep(initialStoreModules),
    mutations: {
        // reset default state modules by looping around the initialStoreModules
        [types.RESET_STATE](state: any) {
        _.forOwn(initialStoreModules, (value: IModule, key: string) => {
            state[key] = _.cloneDeep(value.state);
        });
        },
    }
});
</code>```

Step 2: Call the action to mutate the state to initial state.

```<code>// user_action.ts
const logout = ({ commit }: any) => {
    commit(types.LOGOUT_INIT);
    new UserProxy().logout().then((response: any) => {
      router.push({
        name: 'login',
      });
      // reset the state
      commit(types.RESET_STATE);
    }).catch((err: any) => {
      commit(types.LOGOUT_FAIL, err);
    });
};
</code>```

Title: How to clear state in vuex store?

Body:
Myself has read above and implemented a solution. could help you as well!!

All objects stored in Vue act as an observable. So if reference of a  value is changed/mutated it triggers the actual value to be changed too.

So, Inorder to reset the state the initial store modules has to be copied as a value.

On logging out of an user, the same value has to be assigned for each modules as a copy.

This can be achieved as following:

Step 1: Create a copy of your initial module.

// store.ts

// Initial store with modules as an object
export const initialStoreModules = {
    user,
    recruitment,
};

export default new Vuex.Store({
    /**
     * Assign the modules to the store
     * using lodash deepClone to avoid changing the initial store module values
     */
    modules: _.cloneDeep(initialStoreModules),
    mutations: {
        // reset default state modules by looping around the initialStoreModules
        [types.RESET_STATE](state: any) {
        _.forOwn(initialStoreModules, (value: IModule, key: string) => {
            state[key] = _.cloneDeep(value.state);
        });
        },
    }
});

Step 2: Call the action to mutate the state to initial state.

// user_action.ts
const logout = ({ commit }: any) => {
    commit(types.LOGOUT_INIT);
    new UserProxy().logout().then((response: any) => {
      router.push({
        name: 'login',
      });
      // reset the state
      commit(types.RESET_STATE);
    }).catch((err: any) => {
      commit(types.LOGOUT_FAIL, err);
    });
};


问:
How to hide multiple columns in multiple worksheets
I am going through 25 workbooks in a specific directory and need to hide the same columns in each workbook.

I've set the code up so that it cycles through each workbook, but it fails when it comes to the hiding of the columns. I've done the googling, but am missing something.

The specific code that isn't working:

```<code>Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
                 Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
</code>```

And the whole thing:

```<code> Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.xls*")
        Do While xFileName <> ""
            With Workbooks.Open(xFdItem & xFileName)
                 'your code here
                 Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
                 Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
            End With
        xFileName = Dir
        Loop
   End If
</code>```

I receive a runtime error code '9' subscript out of range.

答:
Can be streamlined a bit better, but this should do the trick. Just reusing your code:

Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Dim X As Long, C As Long, lCol As Long
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & ".xls")
        Do While xFileName <> ""
            With Workbooks.Open(xFdItem & xFileName)
                'not sure if all your sheets are called OpsX, might need to change this
                For X = 1 To 2  'Loop through all the sheets
                    With .Worksheets("Ops" & X) 'Note the use of <[ . ]> (DOT) in the With statement
                        lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column   'Get the last column, relative to row 1

                        For C = lCol To 1 Step -1           'Loop through all columns, starting at last one
                            Select Case C
                                Case 5 To 31 'F:AE
                                   .Cells(1, C).EntireColumn.Hidden = True
                                Case 33 To 43 'AG:AQ
                                   .Cells(1, C).EntireColumn.Hidden = True
                                Case 45 To 94 'AS:CP
                                   .Cells(1, C).EntireColumn.Hidden = True
                                Case 101 To 136 'CW:EF
                                   .Cells(1, C).EntireColumn.Hidden = True
                            End Select
                        Next C
                    End With
                Next X
            End With
        xFileName = Dir
        Loop
    End If
```

Body:
I am going through 25 workbooks in a specific directory and need to hide the same columns in each workbook.

I've set the code up so that it cycles through each workbook, but it fails when it comes to the hiding of the columns. I've done the googling, but am missing something.

The specific code that isn't working:

Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
                 Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True

And the whole thing:

 Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.xls*")
        Do While xFileName <> ""
            With Workbooks.Open(xFdItem & xFileName)
                 'your code here
                 Worksheets("Ops1").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
                 Worksheets("Ops2").Range("F:AE,AG:AQ,AS:CP,CW:EF").EntireColumn.Hidden = True
            End With
        xFileName = Dir
        Loop
   End If

I receive a runtime error code '9' subscript out of range.


问:
Null values for variables in VBA
How do I define a Null string, date or integer in VBA?

I need to be able to assign a Null value to some fields for certain records when data is incomplete or irrelevant, but if I declare a variable as a String, Date or Integer, I get errors when trying to assign a Null value.

Is the only solution to use Variant? If so, then what is the point of all other datatypes in VBA?

答:
```<code>Dim x As Variant
x = Null
</code>```

Only the Variant data type can hold the value Null.

A Variant is a special data type that can contain any kind of data [...] A Variant can also contain the special values Empty, Error, Nothing, and Null.

The "point" of all the other data types is precisely that they cannot contain any ol' kind of data. This has two advantages that I can think of:

It's more difficult for the programmer to assign data of an unintended type to the variable by mistake, since this will be detected at compile time. This can help prevent bugs and make things clearer for you and the next person who will be maintaining your code.

Narrow data types save storage space. Putting integers in a Variant (16 bytes) takes up way more memory than putting them in an Int (2 bytes). This becomes significant if you have large arrays.

Of course, Variants do have their place, as other threads on this site discuss.

Title: Null values for variables in VBA

Body:
Dim x As Variant
x = Null

Only the Variant data type can hold the value Null.

A Variant is a special data type that can contain any kind of data [...] A Variant can also contain the special values Empty, Error, Nothing, and Null.

The "point" of all the other data types is precisely that they cannot contain any ol' kind of data. This has two advantages that I can think of:

It's more difficult for the programmer to assign data of an unintended type to the variable by mistake, since this will be detected at compile time. This can help prevent bugs and make things clearer for you and the next person who will be maintaining your code.

Narrow data types save storage space. Putting integers in a Variant (16 bytes) takes up way more memory than putting them in an Int (2 bytes). This becomes significant if you have large arrays.

Of course, Variants do have their place, as other threads on this site discuss.


问:
Component isn't re-rendering after state change in reducer
Let's say I have a link that, when clicked, adds a random number to an array in my state object called queue. The entire state.queue array is displayed on my page and gets updated as we click the link. I currently have a link that is supposed to be doing something similar but after my reducer alters the state (adds a new item to the array), my page isn't (re-?)rendering my component and so the page does not update.

What should I be doing to show the entirety of state.queue on my page, including dynamically updating as I click the link? Here's what I have:

Channel.js

```<code>class Channel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            queue: [],
            // more initializations
        };
      ...
    }
    ...
    render() {
        return (
            <div>
            {/*This part is never called because this.state.queue never has anything in it! */}
             {this.state.queue &&
                this.state.queue.length > 0 &&
                    <div>
                        <ul>
                            {this.state.queue.map((queuedItem, i) =>
                                <li key={i}>{queuedItem}</li>
                            )}
                        </ul>
                    </div>}

                <div>

                    <QResults
                        allQueryResults={this.state.queryState}
                        requestHandler={queueNewRequest}
                    />
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    const{queue} = state
    return {queue}
}

 function mapDispatchToProps(dispatch) {
    return ({
        queueNewRequest: (newRequestData) => { dispatch({type: newRequestData}) }
    })
}

export default withRouter(connect(mapStateToProps , mapDispatchToProps )(Channel))
</code>```

QResults.js

```<code>export default class QResults extends Component {
    render() {
        const {requestHandler} = this.props

        return (
            <ul>
                {this.props.allQueryResults.items.map((trackAlbum, i) =>
                    <li key={i}>
                        <a href='#'
                        onClick={
                            () => requestHandler(trackAlbum.name)}>
                            Some link
                        </a>
                    </li>
                )}
            </ul>
        )
    }
}
</code>```

actions.js

```<code>export const QUEUE_NEW_REQUEST = 'QUEUE_NEW_REQUEST'

export function queueNewRequest(newRequestInfo) {
    return dispatch => {
        dispatch({
            type: QUEUE_NEW_REQUEST,
            payload: newRequestInfo
        })
    }
}
</code>```

reducers.js

```<code>import { combineReducers } from 'redux'

function reducer1(state = {}, action) {
    ...
}

function reducer2(state = {}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
             return {
                ...state,
                /*queue: [...state.queue,action.payload],*/ //compiler complains that 'TypeError: state.queue is not iterable'
                queue:[action.payload]
            }
        default:
            return state
    }
}
const rootReducer = combineReducers({
    reducer1,
    reducer2
})

export default rootReducer
</code>```

答:
In addition to all the responses about changing this.state.queue to this.props.queue, I needed to do a few things. Initialize queue in my reducer2:

```<code>function reducer2(state = {queue:[]}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
            return {
                ...state,
                queue: [...state.queue,action.payload],
            }
        default:
            return state
    }
}
</code>```

Change mapStateToProps in Channel.js:

```<code>function mapStateToProps(state) {
    const{queue} = state.reducer2
    return {queue}
}
</code>```

Body:
Let's say I have a link that, when clicked, adds a random number to an array in my state object called queue. The entire state.queue array is displayed on my page and gets updated as we click the link. I currently have a link that is supposed to be doing something similar but after my reducer alters the state (adds a new item to the array), my page isn't (re-?)rendering my component and so the page does not update.

What should I be doing to show the entirety of state.queue on my page, including dynamically updating as I click the link? Here's what I have:

Channel.js

class Channel extends Component {
    constructor(props) {
        super(props);
        this.state = {
            queue: [],
            // more initializations
        };
      ...
    }
    ...
    render() {
        return (

            {/*This part is never called because this.state.queue never has anything in it! */}
             {this.state.queue &&
                this.state.queue.length > 0 &&

                            {this.state.queue.map((queuedItem, i) =>

{queuedItem}

                            )}

}

                    <QResults
                        allQueryResults={this.state.queryState}
                        requestHandler={queueNewRequest}
                    />

        );
    }
}

function mapStateToProps(state) {
    const{queue} = state
    return {queue}
}

 function mapDispatchToProps(dispatch) {
    return ({
        queueNewRequest: (newRequestData) => { dispatch({type: newRequestData}) }
    })
}

export default withRouter(connect(mapStateToProps , mapDispatchToProps )(Channel))

QResults.js

export default class QResults extends Component {
    render() {
        const {requestHandler} = this.props

        return (

                {this.props.allQueryResults.items.map((trackAlbum, i) =>

                         requestHandler(trackAlbum.name)}>
                            Some link

                )}

        )
    }
}

actions.js

export const QUEUE_NEW_REQUEST = 'QUEUE_NEW_REQUEST'

export function queueNewRequest(newRequestInfo) {
    return dispatch => {
        dispatch({
            type: QUEUE_NEW_REQUEST,
            payload: newRequestInfo
        })
    }
}

reducers.js

import { combineReducers } from 'redux'

function reducer1(state = {}, action) {
    ...
}

function reducer2(state = {}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
             return {
                ...state,
                /*queue: [...state.queue,action.payload],*/ //compiler complains that 'TypeError: state.queue is not iterable'
                queue:[action.payload]
            }
        default:
            return state
    }
}
const rootReducer = combineReducers({
    reducer1,
    reducer2
})

export default rootReducer

Body:
In addition to all the responses about changing this.state.queue to this.props.queue, I needed to do a few things. Initialize queue in my reducer2:

function reducer2(state = {queue:[]}, action) {
    switch (action.type) {
        case QUEUE_NEW_REQUEST:
            return {
                ...state,
                queue: [...state.queue,action.payload],
            }
        default:
            return state
    }
}

Change mapStateToProps in Channel.js:

function mapStateToProps(state) {
    const{queue} = state.reducer2
    return {queue}
}


问:
Reading an excel file : connection error from c#?
My program needs to read some data in an Excel file.

My configuration :

Windows 10 x64 / Visual Studio 2019 / Office 2019 x64

And I've some trouble with this code :

```<code>string connectionString1 = @"Provider=Microsoft.ACE.OLEDB.15.0;Data Source=" + filePath22 + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";";
</code>```

The connection string seems to be incorrect seen that I receive an error message :

"The 'Microsoft.ACE.OLEDB.15.0' provider is not registered on the local machine."

I've already tried to install the "Microsoft Access database engine 2010 x64" and the "Microsoft Access database engine 2016 x64" but the problem continues...

Thanks for your help !  ;)

答:
I found this forum post that suggests installing the Microsoft access 2013 runtime.

Forum link: https://answers.microsoft.com/en-us/msoffice/forum/all/the-microsoftaceoledb150-provider-is-not/6430a47d-263c-43af-aabc-f134da4b830e

Runtime link: https://microsoft.com/en-us/download/details.aspx?id=39358

Body:
My program needs to read some data in an Excel file.

My configuration :

Windows 10 x64 / Visual Studio 2019 / Office 2019 x64

And I've some trouble with this code :

string connectionString1 = @"Provider=Microsoft.ACE.OLEDB.15.0;Data Source=" + filePath22 + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";";

The connection string seems to be incorrect seen that I receive an error message :

"The 'Microsoft.ACE.OLEDB.15.0' provider is not registered on the local machine."

I've already tried to install the "Microsoft Access database engine 2010 x64" and the "Microsoft Access database engine 2016 x64" but the problem continues...

Thanks for your help !  ;)