问:
thread 'main' panicked at 'assertion failed: `(left == right)` left: `22`, right: `4`' when installing Rust for WSL
I go to the website and see a script to download the Rust installer:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```

<p>I changed some things in the <code>Customize Installation</code> option and proceed with the installation then get the following error:</p>

<pre class="lang-none prettyprint-override"><code>info: profile set to 'complete'
info: setting default host triple to x86_64-unknown-linux-gnu
info: syncing channel updates for 'nightly-x86_64-unknown-linux-gnu'
info: latest update on 2020-05-04, rust version 1.45.0-nightly (65b448273 2020-05-03)
warning: Force-skipping unavailable component 'lldb-preview-x86_64-unknown-linux-gnu'
warning: Force-skipping unavailable component 'rls-x86_64-unknown-linux-gnu'
info: downloading component 'cargo'
  5.0 MiB /   5.0 MiB (100 %)   3.2 MiB/s in  2s ETA:  0s
info: downloading component 'clippy'
info: downloading component 'llvm-tools-preview'
info: downloading component 'miri'
  1.7 MiB /   1.7 MiB (100 %) 672.4 KiB/s in  2s ETA:  0s
info: downloading component 'rust-analysis'
info: downloading component 'rust-docs'
 12.2 MiB /  12.2 MiB (100 %)   3.2 MiB/s in  4s ETA:  0s
info: downloading component 'rust-src'
info: downloading component 'rust-std'
 15.8 MiB /  15.8 MiB (100 %)   3.9 MiB/s in  4s ETA:  0s
info: downloading component 'rustc'
 60.5 MiB /  60.5 MiB (100 %)   3.0 MiB/s in 17s ETA:  0s
info: downloading component 'rustc-dev'
 63.4 MiB /  63.4 MiB (100 %)   3.7 MiB/s in 19s ETA:  0s
info: downloading component 'rustfmt'
  3.4 MiB /   3.4 MiB (100 %)   3.0 MiB/s in  1s ETA:  0s
info: installing component 'cargo'
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `22`,
 right: `4`', src/libstd/sys/unix/thread.rs:166:21
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `22`,
 right: `4`', src/libstd/sys/unix/thread.rs:166:21
stack backtrace:
   0:     0x7fb935adbc9c - backtrace::backtrace::libunwind::trace::h65597d255cb1398b
                               at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/libunwind.rs:88
   1:     0x7fb935adbc9c - backtrace::backtrace::trace_unsynchronized::hd4f479d7150ec4a0
                               at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/mod.rs:66
   2:     0x7fb935adbc9c - std::sys_common::backtrace::_print_fmt::h015072984a2b172c
                               at src/libstd/sys_common/backtrace.rs:77
   3:     0x7fb935adbc9c - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h6df05d3335f32194
                               at src/libstd/sys_common/backtrace.rs:61
   4:     0x7fb9357ba81c - core::fmt::write::h1f444f4312eb6c27
                               at src/libcore/fmt/mod.rs:1028
   5:     0x7fb935adb526 - std::io::Write::write_fmt::h8d147888220078ef
                               at src/libstd/io/mod.rs:1412
   6:     0x7fb935adb19e - std::sys_common::backtrace::_print::h8a6df0fa81d6af62
                               at src/libstd/sys_common/backtrace.rs:65
   7:     0x7fb935adb19e - std::sys_common::backtrace::print::h6f05b4733407e509
                               at src/libstd/sys_common/backtrace.rs:50
   8:     0x7fb935adb19e - std::panicking::default_hook::{{closure}}::h0d0a23bd02315dd8
                               at src/libstd/panicking.rs:188
   9:     0x7fb935ada943 - std::panicking::default_hook::h8d15a9aecb4efac6
                               at src/libstd/panicking.rs:205
  10:     0x7fb935ada943 - std::panicking::rust_panic_with_hook::hbe174577402a475d
                               at src/libstd/panicking.rs:464
  11:     0x7fb935ada4be - std::panicking::continue_panic_fmt::h4d855dad868accf3
                               at src/libstd/panicking.rs:373
  12:     0x7fb935ada450 - std::panicking::begin_panic_fmt::ha0f013e3301a9528
                               at src/libstd/panicking.rs:328
  13:     0x7fb935aaae86 - <rustup::diskio::threaded::Threaded as rustup::diskio::Executor>::join::hf33124263a81d2a4
  14:     0x7fb935aaa636 - core::ptr::real_drop_in_place::haa8255139d9471a2
  15:     0x7fb9357d5190 - core::ptr::real_drop_in_place::h04c627b98e68397b
  16:     0x7fb935a9e777 - rustup::dist::component::package::unpack_without_first_dir::h352b57d236248e9a
  17:     0x7fb935a762f6 - rustup::dist::manifestation::Manifestation::update::h8c800deec8167b5b
  18:     0x7fb935a64b8a - rustup::dist::dist::try_update_from_dist_::h113375517e7a85ca
  19:     0x7fb935a4964c - rustup::toolchain::Toolchain::install::h048b51ffab245b48
  20:     0x7fb935a46c8c - rustup::toolchain::Toolchain::install_from_dist::h00b9aafeb93470e5
  21:     0x7fb9357143ee - rustup_init::self_update::install::h4cee0e396cee456b
  22:     0x7fb935725ca2 - rustup_init::run_rustup_inner::ha545371fd2dc19a6
  23:     0x7fb935722d64 - rustup_init::main::hba9a23e308c96901
  24:     0x7fb9356b7a03 - std::rt::lang_start::{{closure}}::h1778d9ce6385bef5
  25:     0x7fb93572c458 - main
  26:     0x7fb9352070b3 - __libc_start_main
  27:     0x7fb9356b4029 - <unknown>
thread panicked while panicking. aborting.
Illegal instruction (core dumped)
</code>```

I also tried installing with stable as default and the same thing happened where it panics on the assertion (left == right). What might have caused this?

答:
```<code>pacman -U https://archive.archlinux.org/packages/g/glibc/glibc-2.30-3-x86_64.pkg.tar.xz
</code>```

this is for arch wsl installation
using this to rollback glibc if you recently installed wsl
and this is just adding to the answer given by @tgiachetti

Body:
I go to the website and see a script to download the Rust installer:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

I changed some things in the Customize Installation option and proceed with the installation then get the following error:

info: profile set to 'complete'
info: setting default host triple to x86_64-unknown-linux-gnu
info: syncing channel updates for 'nightly-x86_64-unknown-linux-gnu'
info: latest update on 2020-05-04, rust version 1.45.0-nightly (65b448273 2020-05-03)
warning: Force-skipping unavailable component 'lldb-preview-x86_64-unknown-linux-gnu'
warning: Force-skipping unavailable component 'rls-x86_64-unknown-linux-gnu'
info: downloading component 'cargo'
  5.0 MiB /   5.0 MiB (100 %)   3.2 MiB/s in  2s ETA:  0s
info: downloading component 'clippy'
info: downloading component 'llvm-tools-preview'
info: downloading component 'miri'
  1.7 MiB /   1.7 MiB (100 %) 672.4 KiB/s in  2s ETA:  0s
info: downloading component 'rust-analysis'
info: downloading component 'rust-docs'
 12.2 MiB /  12.2 MiB (100 %)   3.2 MiB/s in  4s ETA:  0s
info: downloading component 'rust-src'
info: downloading component 'rust-std'
 15.8 MiB /  15.8 MiB (100 %)   3.9 MiB/s in  4s ETA:  0s
info: downloading component 'rustc'
 60.5 MiB /  60.5 MiB (100 %)   3.0 MiB/s in 17s ETA:  0s
info: downloading component 'rustc-dev'
 63.4 MiB /  63.4 MiB (100 %)   3.7 MiB/s in 19s ETA:  0s
info: downloading component 'rustfmt'
  3.4 MiB /   3.4 MiB (100 %)   3.0 MiB/s in  1s ETA:  0s
info: installing component 'cargo'
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `22`,
 right: `4`', src/libstd/sys/unix/thread.rs:166:21
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `22`,
 right: `4`', src/libstd/sys/unix/thread.rs:166:21
stack backtrace:
   0:     0x7fb935adbc9c - backtrace::backtrace::libunwind::trace::h65597d255cb1398b
                               at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/libunwind.rs:88
   1:     0x7fb935adbc9c - backtrace::backtrace::trace_unsynchronized::hd4f479d7150ec4a0
                               at /cargo/registry/src/github.com-1ecc6299db9ec823/backtrace-0.3.40/src/backtrace/mod.rs:66
   2:     0x7fb935adbc9c - std::sys_common::backtrace::_print_fmt::h015072984a2b172c
                               at src/libstd/sys_common/backtrace.rs:77
   3:     0x7fb935adbc9c - <std::sys_common::backtrace::_print::DisplayBacktrace as core::fmt::Display>::fmt::h6df05d3335f32194
                               at src/libstd/sys_common/backtrace.rs:61
   4:     0x7fb9357ba81c - core::fmt::write::h1f444f4312eb6c27
                               at src/libcore/fmt/mod.rs:1028
   5:     0x7fb935adb526 - std::io::Write::write_fmt::h8d147888220078ef
                               at src/libstd/io/mod.rs:1412
   6:     0x7fb935adb19e - std::sys_common::backtrace::_print::h8a6df0fa81d6af62
                               at src/libstd/sys_common/backtrace.rs:65
   7:     0x7fb935adb19e - std::sys_common::backtrace::print::h6f05b4733407e509
                               at src/libstd/sys_common/backtrace.rs:50
   8:     0x7fb935adb19e - std::panicking::default_hook::{{closure}}::h0d0a23bd02315dd8
                               at src/libstd/panicking.rs:188
   9:     0x7fb935ada943 - std::panicking::default_hook::h8d15a9aecb4efac6
                               at src/libstd/panicking.rs:205
  10:     0x7fb935ada943 - std::panicking::rust_panic_with_hook::hbe174577402a475d
                               at src/libstd/panicking.rs:464
  11:     0x7fb935ada4be - std::panicking::continue_panic_fmt::h4d855dad868accf3
                               at src/libstd/panicking.rs:373
  12:     0x7fb935ada450 - std::panicking::begin_panic_fmt::ha0f013e3301a9528
                               at src/libstd/panicking.rs:328
  13:     0x7fb935aaae86 - <rustup::diskio::threaded::Threaded as rustup::diskio::Executor>::join::hf33124263a81d2a4
  14:     0x7fb935aaa636 - core::ptr::real_drop_in_place::haa8255139d9471a2
  15:     0x7fb9357d5190 - core::ptr::real_drop_in_place::h04c627b98e68397b
  16:     0x7fb935a9e777 - rustup::dist::component::package::unpack_without_first_dir::h352b57d236248e9a
  17:     0x7fb935a762f6 - rustup::dist::manifestation::Manifestation::update::h8c800deec8167b5b
  18:     0x7fb935a64b8a - rustup::dist::dist::try_update_from_dist_::h113375517e7a85ca
  19:     0x7fb935a4964c - rustup::toolchain::Toolchain::install::h048b51ffab245b48
  20:     0x7fb935a46c8c - rustup::toolchain::Toolchain::install_from_dist::h00b9aafeb93470e5
  21:     0x7fb9357143ee - rustup_init::self_update::install::h4cee0e396cee456b
  22:     0x7fb935725ca2 - rustup_init::run_rustup_inner::ha545371fd2dc19a6
  23:     0x7fb935722d64 - rustup_init::main::hba9a23e308c96901
  24:     0x7fb9356b7a03 - std::rt::lang_start::{{closure}}::h1778d9ce6385bef5
  25:     0x7fb93572c458 - main
  26:     0x7fb9352070b3 - __libc_start_main
  27:     0x7fb9356b4029 - <unknown>
thread panicked while panicking. aborting.
Illegal instruction (core dumped)

I also tried installing with stable as default and the same thing happened where it panics on the assertion (left == right). What might have caused this?

Body:
pacman -U https://archive.archlinux.org/packages/g/glibc/glibc-2.30-3-x86_64.pkg.tar.xz

this is for arch wsl installation
using this to rollback glibc if you recently installed wsl
and this is just adding to the answer given by @tgiachetti


来源: stackexchange

问:
Filling between two lines on python
I have the formula below:

```<code>ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.gca().fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)
plt.show()
</code>```

I would like to fill between the two lines on the line graph below, but somehow my code is not working. Could anyone help understand why?

I thought that the fill_between command would work but for some reason it is not...

When I try:

```<code>ax.fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)
</code>```

I get the error message:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

My graph currently looks like this:

The dataframe datamax looks like this:

```<code> Date           ID Element  Data_Value
0     2005-01-01  USW00094889    TMAX         156
1     2005-01-02  USW00094889    TMAX         139
2     2005-01-03  USW00094889    TMAX         133
3     2005-01-04  USW00094889    TMAX          39
4     2005-01-05  USW00094889    TMAX          33
5     2005-01-06  USW00094889    TMAX           0
6     2005-01-07  USW00094889    TMAX           6
7     2005-01-08  USW00094889    TMAX          17
8     2005-01-09  USW00094889    TMAX          28
9     2005-01-10  USW00094889    TMAX          44
10    2005-01-11  USW00094889    TMAX          44
11    2005-01-12  USW00094889    TMAX         139
12    2005-01-13  USW00094889    TMAX         161
13    2005-01-14  USW00094889    TMAX         150
14    2005-01-15  USW00094889    TMAX         -33
15    2005-01-16  USW00094889    TMAX         -33
16    2005-01-17  USW00094889    TMAX         -50
17    2005-01-18  USW00094889    TMAX         -33
18    2005-01-19  USW00094889    TMAX          11
19    2005-01-20  USW00094889    TMAX          11
20    2005-01-21  USW00094889    TMAX         -39
21    2005-01-22  USW00094889    TMAX         -72
22    2005-01-23  USW00094889    TMAX         -44
23    2005-01-24  USW00094889    TMAX          11
24    2005-01-25  USW00094889    TMAX          28
25    2005-01-26  USW00094889    TMAX          28
26    2005-01-27  USW00094889    TMAX           6
27    2005-01-28  USW00094889    TMAX         -11
28    2005-01-29  USW00094889    TMAX          17
29    2005-01-30  USW00094889    TMAX          28
...          ...          ...     ...         ...
3603  2014-11-13  USW00094889    TMAX          39
3604  2014-11-14  USW00094889    TMAX          33
3605  2014-11-15  USW00094889    TMAX          28
3606  2014-11-16  USW00094889    TMAX          28
3607  2014-11-17  USW00094889    TMAX          17
3608  2014-11-18  USW00094889    TMAX          11
3609  2014-11-19  USW00094889    TMAX          11
3610  2014-11-20  USW00094889    TMAX           6
3611  2014-11-21  USW00094889    TMAX         -10
3612  2014-11-22  USW00094889    TMAX         106
3613  2014-11-23  USW00094889    TMAX         156
3614  2014-11-24  USW00094889    TMAX         172
3615  2014-11-25  USW00094889    TMAX         172
3616  2014-11-26  USW00094889    TMAX          28
3617  2014-11-27  USW00094889    TMAX          39
3618  2014-11-28  USW00094889    TMAX          22
3619  2014-11-29  USW00094889    TMAX         117
3620  2014-11-30  USW00094889    TMAX         178
3621  2014-12-01  USW00094889    TMAX         172
3622  2014-12-02  USW00094889    TMAX          33
3623  2014-12-03  USW00094889    TMAX          61
3624  2014-12-04  USW00094889    TMAX          50
3625  2014-12-05  USW00094889    TMAX          50
3626  2014-12-06  USW00094889    TMAX          67
3627  2014-12-07  USW00094889    TMAX          67
3628  2014-12-08  USW00094889    TMAX          72
3629  2014-12-09  USW00094889    TMAX          56
3630  2014-12-10  USW00094889    TMAX          50
3631  2014-12-11  USW00094889    TMAX          61
3632  2014-12-12  USW00094889    TMAX          50

[3631 rows x 4 columns]
</code>```

And the dataframe datamin like this:

```<code> Date           ID Element  Data_Value
0     2005-01-01  USC00200032    TMIN         -56
1     2005-01-02  USC00200032    TMIN         -56
2     2005-01-03  USC00200032    TMIN           0
3     2005-01-04  USC00200032    TMIN         -39
4     2005-01-05  USC00200032    TMIN         -94
5     2005-01-06  USC00200032    TMIN        -106
6     2005-01-07  USC00200032    TMIN        -111
7     2005-01-08  USC00200032    TMIN        -100
8     2005-01-09  USC00200032    TMIN         -67
9     2005-01-10  USC00200032    TMIN         -56
10    2005-01-11  USC00200032    TMIN         -22
11    2005-01-12  USC00200032    TMIN         -17
12    2005-01-13  USC00200032    TMIN         -83
13    2005-01-14  USC00200032    TMIN        -128
14    2005-01-15  USC00200032    TMIN        -144
15    2005-01-16  USC00200032    TMIN        -150
16    2005-01-17  USC00200032    TMIN        -189
17    2005-01-18  USC00200032    TMIN        -217
18    2005-01-19  USC00200228    TMIN        -300
19    2005-01-20  USC00200032    TMIN        -156
20    2005-01-21  USC00200032    TMIN        -178
21    2005-01-22  USC00200032    TMIN        -178
22    2005-01-23  USC00200032    TMIN        -250
23    2005-01-24  USC00200032    TMIN        -267
24    2005-01-25  USC00200032    TMIN        -228
25    2005-01-26  USC00200032    TMIN        -206
26    2005-01-27  USC00200032    TMIN        -239
27    2005-01-28  USC00200032    TMIN        -250
28    2005-01-29  USC00200032    TMIN        -222
29    2005-01-30  USC00200228    TMIN        -217
...          ...          ...     ...         ...
3603  2014-11-13  USC00200032    TMIN         -71
3604  2014-11-14  USC00200032    TMIN         -78
3605  2014-11-15  USC00200032    TMIN         -94
3606  2014-11-16  USC00200032    TMIN         -72
3607  2014-11-17  USC00200032    TMIN        -106
3608  2014-11-18  USC00200032    TMIN        -144
3609  2014-11-19  USC00200032    TMIN        -128
3610  2014-11-20  USC00200032    TMIN        -122
3611  2014-11-21  USC00200032    TMIN        -182
3612  2014-11-22  USC00200032    TMIN        -172
3613  2014-11-23  USC00200032    TMIN        -100
3614  2014-11-24  USC00200032    TMIN          -5
3615  2014-11-25  USC00200032    TMIN         -33
3616  2014-11-26  USC00200032    TMIN         -67
3617  2014-11-27  USC00200032    TMIN         -82
3618  2014-11-28  USC00200032    TMIN        -133
3619  2014-11-29  USC00200032    TMIN        -106
3620  2014-11-30  USC00200032    TMIN         -56
3621  2014-12-01  USC00200032    TMIN         -88
3622  2014-12-02  USC00200032    TMIN         -99
3623  2014-12-03  USC00200032    TMIN         -71
3624  2014-12-04  USC00200032    TMIN         -77
3625  2014-12-05  USC00200032    TMIN         -61
3626  2014-12-06  USC00200032    TMIN         -50
3627  2014-12-07  USC00200032    TMIN         -78
3628  2014-12-08  USC00200032    TMIN         -78
3629  2014-12-09  USC00200032    TMIN         -39
3630  2014-12-10  USC00200032    TMIN         -72
3631  2014-12-11  USC00200032    TMIN         -88
3632  2014-12-12  USC00200032    TMIN         -78

[3631 rows x 4 columns]
</code>```

答:
Python code which returns a line graph of the record high and record low temperatures by day of the year over the period 2005-2014. The area between the record high and record low temperatures for each day should be shaded.

Then, overlay a scatter of the 2015 data for any points (highs and lows) for which the ten year record (2005-2014) record high or record low was broken in 2015.

Remove leap year dates (i.e. 29th February).

/

```<code>from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

pd.set_option("display.max_rows",None,"display.max_columns",None)
data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax = datamax.groupby('day_of_year').max()
datamin["day_of_year"] = datamin["Date"].dt.dayofyear
datamin = datamin.groupby('day_of_year').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d')
datamax['Date'] = datamax['Date'].dt.strftime('%Y-%m-%d')
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamin2015['Date'] = pd.to_datetime(datamin2015['Date'])
datamax2015["day_of_year"] = datamax2015["Date"].dt.dayofyear
datamax2015 = datamax2015.groupby('day_of_year').max()
datamin2015["day_of_year"] = datamin2015["Date"].dt.dayofyear
datamin2015 = datamin2015.groupby('day_of_year').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamin2015['Date'] = datamin2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015['Date'] = datamax2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

dataminappend = datamin2015.join(datamin,on="day_of_year",rsuffix="_new")
lower = dataminappend.loc[dataminappend["Data_Value_new"]>dataminappend["Data_Value"]]
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper['Date'] = pd.to_datetime(upper['Date'])
lower['Date'] = pd.to_datetime(lower['Date'])
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])

ax = plt.gca()
plt.plot(datamax['day_of_year'],datamax['Data_Value'],color='red')
plt.plot(datamin['day_of_year'],datamin['Data_Value'], color='blue')
plt.scatter(upper['day_of_year'],upper['Data_Value'],color='purple')
plt.scatter(lower['day_of_year'],lower['Data_Value'], color='cyan')

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Day of the year",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day between 2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()
</code>```

/

I have converted the 'Date' column to a string using Datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d').

I have then converted this back to 'datetime' format using upper['Date'] = pd.to_datetime(upper['Date'])

I then used 'date of year' as the x-value.

ContentLicense: CC BY-SA 4.0

Title: Filling between two lines on python

Body:
I have the formula below:

ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.gca().fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)
plt.show()

I would like to fill between the two lines on the line graph below, but somehow my code is not working. Could anyone help understand why?

I thought that the fill_between command would work but for some reason it is not...

When I try:

ax.fill_between(datamax['Date'],datamax['Data_Value'],datamin['Data_Value'],facecolor='yellow',alpha=0.25)

I get the error message:

ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

My graph currently looks like this:

The dataframe datamax looks like this:

 Date           ID Element  Data_Value
0     2005-01-01  USW00094889    TMAX         156
1     2005-01-02  USW00094889    TMAX         139
2     2005-01-03  USW00094889    TMAX         133
3     2005-01-04  USW00094889    TMAX          39
4     2005-01-05  USW00094889    TMAX          33
5     2005-01-06  USW00094889    TMAX           0
6     2005-01-07  USW00094889    TMAX           6
7     2005-01-08  USW00094889    TMAX          17
8     2005-01-09  USW00094889    TMAX          28
9     2005-01-10  USW00094889    TMAX          44
10    2005-01-11  USW00094889    TMAX          44
11    2005-01-12  USW00094889    TMAX         139
12    2005-01-13  USW00094889    TMAX         161
13    2005-01-14  USW00094889    TMAX         150
14    2005-01-15  USW00094889    TMAX         -33
15    2005-01-16  USW00094889    TMAX         -33
16    2005-01-17  USW00094889    TMAX         -50
17    2005-01-18  USW00094889    TMAX         -33
18    2005-01-19  USW00094889    TMAX          11
19    2005-01-20  USW00094889    TMAX          11
20    2005-01-21  USW00094889    TMAX         -39
21    2005-01-22  USW00094889    TMAX         -72
22    2005-01-23  USW00094889    TMAX         -44
23    2005-01-24  USW00094889    TMAX          11
24    2005-01-25  USW00094889    TMAX          28
25    2005-01-26  USW00094889    TMAX          28
26    2005-01-27  USW00094889    TMAX           6
27    2005-01-28  USW00094889    TMAX         -11
28    2005-01-29  USW00094889    TMAX          17
29    2005-01-30  USW00094889    TMAX          28
...          ...          ...     ...         ...
3603  2014-11-13  USW00094889    TMAX          39
3604  2014-11-14  USW00094889    TMAX          33
3605  2014-11-15  USW00094889    TMAX          28
3606  2014-11-16  USW00094889    TMAX          28
3607  2014-11-17  USW00094889    TMAX          17
3608  2014-11-18  USW00094889    TMAX          11
3609  2014-11-19  USW00094889    TMAX          11
3610  2014-11-20  USW00094889    TMAX           6
3611  2014-11-21  USW00094889    TMAX         -10
3612  2014-11-22  USW00094889    TMAX         106
3613  2014-11-23  USW00094889    TMAX         156
3614  2014-11-24  USW00094889    TMAX         172
3615  2014-11-25  USW00094889    TMAX         172
3616  2014-11-26  USW00094889    TMAX          28
3617  2014-11-27  USW00094889    TMAX          39
3618  2014-11-28  USW00094889    TMAX          22
3619  2014-11-29  USW00094889    TMAX         117
3620  2014-11-30  USW00094889    TMAX         178
3621  2014-12-01  USW00094889    TMAX         172
3622  2014-12-02  USW00094889    TMAX          33
3623  2014-12-03  USW00094889    TMAX          61
3624  2014-12-04  USW00094889    TMAX          50
3625  2014-12-05  USW00094889    TMAX          50
3626  2014-12-06  USW00094889    TMAX          67
3627  2014-12-07  USW00094889    TMAX          67
3628  2014-12-08  USW00094889    TMAX          72
3629  2014-12-09  USW00094889    TMAX          56
3630  2014-12-10  USW00094889    TMAX          50
3631  2014-12-11  USW00094889    TMAX          61
3632  2014-12-12  USW00094889    TMAX          50

[3631 rows x 4 columns]

And the dataframe datamin like this:

 Date           ID Element  Data_Value
0     2005-01-01  USC00200032    TMIN         -56
1     2005-01-02  USC00200032    TMIN         -56
2     2005-01-03  USC00200032    TMIN           0
3     2005-01-04  USC00200032    TMIN         -39
4     2005-01-05  USC00200032    TMIN         -94
5     2005-01-06  USC00200032    TMIN        -106
6     2005-01-07  USC00200032    TMIN        -111
7     2005-01-08  USC00200032    TMIN        -100
8     2005-01-09  USC00200032    TMIN         -67
9     2005-01-10  USC00200032    TMIN         -56
10    2005-01-11  USC00200032    TMIN         -22
11    2005-01-12  USC00200032    TMIN         -17
12    2005-01-13  USC00200032    TMIN         -83
13    2005-01-14  USC00200032    TMIN        -128
14    2005-01-15  USC00200032    TMIN        -144
15    2005-01-16  USC00200032    TMIN        -150
16    2005-01-17  USC00200032    TMIN        -189
17    2005-01-18  USC00200032    TMIN        -217
18    2005-01-19  USC00200228    TMIN        -300
19    2005-01-20  USC00200032    TMIN        -156
20    2005-01-21  USC00200032    TMIN        -178
21    2005-01-22  USC00200032    TMIN        -178
22    2005-01-23  USC00200032    TMIN        -250
23    2005-01-24  USC00200032    TMIN        -267
24    2005-01-25  USC00200032    TMIN        -228
25    2005-01-26  USC00200032    TMIN        -206
26    2005-01-27  USC00200032    TMIN        -239
27    2005-01-28  USC00200032    TMIN        -250
28    2005-01-29  USC00200032    TMIN        -222
29    2005-01-30  USC00200228    TMIN        -217
...          ...          ...     ...         ...
3603  2014-11-13  USC00200032    TMIN         -71
3604  2014-11-14  USC00200032    TMIN         -78
3605  2014-11-15  USC00200032    TMIN         -94
3606  2014-11-16  USC00200032    TMIN         -72
3607  2014-11-17  USC00200032    TMIN        -106
3608  2014-11-18  USC00200032    TMIN        -144
3609  2014-11-19  USC00200032    TMIN        -128
3610  2014-11-20  USC00200032    TMIN        -122
3611  2014-11-21  USC00200032    TMIN        -182
3612  2014-11-22  USC00200032    TMIN        -172
3613  2014-11-23  USC00200032    TMIN        -100
3614  2014-11-24  USC00200032    TMIN          -5
3615  2014-11-25  USC00200032    TMIN         -33
3616  2014-11-26  USC00200032    TMIN         -67
3617  2014-11-27  USC00200032    TMIN         -82
3618  2014-11-28  USC00200032    TMIN        -133
3619  2014-11-29  USC00200032    TMIN        -106
3620  2014-11-30  USC00200032    TMIN         -56
3621  2014-12-01  USC00200032    TMIN         -88
3622  2014-12-02  USC00200032    TMIN         -99
3623  2014-12-03  USC00200032    TMIN         -71
3624  2014-12-04  USC00200032    TMIN         -77
3625  2014-12-05  USC00200032    TMIN         -61
3626  2014-12-06  USC00200032    TMIN         -50
3627  2014-12-07  USC00200032    TMIN         -78
3628  2014-12-08  USC00200032    TMIN         -78
3629  2014-12-09  USC00200032    TMIN         -39
3630  2014-12-10  USC00200032    TMIN         -72
3631  2014-12-11  USC00200032    TMIN         -88
3632  2014-12-12  USC00200032    TMIN         -78

[3631 rows x 4 columns]

Body:
Python code which returns a line graph of the record high and record low temperatures by day of the year over the period 2005-2014. The area between the record high and record low temperatures for each day should be shaded.

Then, overlay a scatter of the 2015 data for any points (highs and lows) for which the ten year record (2005-2014) record high or record low was broken in 2015.

Remove leap year dates (i.e. 29th February).

/

from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt

pd.set_option("display.max_rows",None,"display.max_columns",None)
data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])
datamax["day_of_year"] = datamax["Date"].dt.dayofyear
datamax = datamax.groupby('day_of_year').max()
datamin["day_of_year"] = datamin["Date"].dt.dayofyear
datamin = datamin.groupby('day_of_year').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d')
datamax['Date'] = datamax['Date'].dt.strftime('%Y-%m-%d')
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015['Date'] = pd.to_datetime(datamax2015['Date'])
datamin2015['Date'] = pd.to_datetime(datamin2015['Date'])
datamax2015["day_of_year"] = datamax2015["Date"].dt.dayofyear
datamax2015 = datamax2015.groupby('day_of_year').max()
datamin2015["day_of_year"] = datamin2015["Date"].dt.dayofyear
datamin2015 = datamin2015.groupby('day_of_year').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamin2015['Date'] = datamin2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015['Date'] = datamax2015['Date'].dt.strftime('%Y-%m-%d')
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

dataminappend = datamin2015.join(datamin,on="day_of_year",rsuffix="_new")
lower = dataminappend.loc[dataminappend["Data_Value_new"]>dataminappend["Data_Value"]]
datamaxappend = datamax2015.join(datamax,on="day_of_year",rsuffix="_new")
upper = datamaxappend.loc[datamaxappend["Data_Value_new"]<datamaxappend["Data_Value"]]

upper['Date'] = pd.to_datetime(upper['Date'])
lower['Date'] = pd.to_datetime(lower['Date'])
datamax['Date'] = pd.to_datetime(datamax['Date'])
datamin['Date'] = pd.to_datetime(datamin['Date'])

ax = plt.gca()
plt.plot(datamax['day_of_year'],datamax['Data_Value'],color='red')
plt.plot(datamin['day_of_year'],datamin['Data_Value'], color='blue')
plt.scatter(upper['day_of_year'],upper['Data_Value'],color='purple')
plt.scatter(lower['day_of_year'],lower['Data_Value'], color='cyan')

plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Day of the year",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day between 2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()

/

I have converted the 'Date' column to a string using Datamin['Date'] = datamin['Date'].dt.strftime('%Y-%m-%d').

I have then converted this back to 'datetime' format using upper['Date'] = pd.to_datetime(upper['Date'])

I then used 'date of year' as the x-value.


问:
Create new column from existing dataframe column with condition
GroupID column has two values one alphanumeric and other is numeric, I want use alphanumeric part of column to create new column, with some condition like if alphanumeric is present in o_dict then it should return value else it should just return "NOT IN DIC"

```<code>GroupID
0   ad32s;#1214;#rf343;#4343
1   wd435;#6464;#ed532;#5454
2   av345e:#3132
3   ok132d;#8897
4   tn123h;#0980
5   as845;#657;#un567t;#456;#qw147;#123
6   ok132d;#8897
7   as845;#657;#un567t;#456;#qw147;#123
8   wd435;#6464;#ed532;#5454

o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal",
         "qw147":"ilesh","av345e":'carls'}
</code>```

below is my code:

```<code>def function01(row):
o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal","qw147":"ilesh","av345e":'carls'}
    if element.isalnum():
        if element in o_dict:
            return owner_dict[element]
        else:
            return "NOT IN DIC"
    else:
        continue
df['New_column'] = df.apply(lambda x: function01(x), axis=1)
</code>```

This code works if the alphanumeric value is at first position but does not work if it is at 3 or 5 position. It works for row 0,2,3,4 6, but does not work for 1,5,7,8.

O/p should have two columns with values from dict which matched with groupid else it should be populated with  "NOT IN DIC".

I not sure what i can do now, is there another approach to get this values ?
is there any search function which can be used to search for this values ??

Thanks for helping :)

答:
I found that in my code for-loop was only working for first value in list and it was populating "NOT IN DIC" without checking for other values. I have made below changes now and I am getting expected output.</p>

```<code>def function01(row):
o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal","qw147":"ilesh","av345e":'carls'}
listA = row['Assigned'].split(";#")
listB = [i for i in listA if i.isdigit()==False]
for element in listA:
    if element in owner_dict:
        return owner_dict[element]
    else:
        continue
return "NOT IN DIC"

df['New_column'] = df.apply(lambda x: function01(x), axis=1)
</code>```

Body:
GroupID column has two values one alphanumeric and other is numeric, I want use alphanumeric part of column to create new column, with some condition like if alphanumeric is present in o_dict then it should return value else it should just return "NOT IN DIC"

GroupID
0   ad32s;#1214;#rf343;#4343
1   wd435;#6464;#ed532;#5454
2   av345e:#3132
3   ok132d;#8897
4   tn123h;#0980
5   as845;#657;#un567t;#456;#qw147;#123
6   ok132d;#8897
7   as845;#657;#un567t;#456;#qw147;#123
8   wd435;#6464;#ed532;#5454

o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal",
         "qw147":"ilesh","av345e":'carls'}

below is my code:

def function01(row):
o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal","qw147":"ilesh","av345e":'carls'}
    if element.isalnum():
        if element in o_dict:
            return owner_dict[element]
        else:
            return "NOT IN DIC"
    else:
        continue
df['New_column'] = df.apply(lambda x: function01(x), axis=1)

This code works if the alphanumeric value is at first position but does not work if it is at 3 or 5 position. It works for row 0,2,3,4 6, but does not work for 1,5,7,8.

O/p should have two columns with values from dict which matched with groupid else it should be populated with  "NOT IN DIC".

I not sure what i can do now, is there another approach to get this values ?
is there any search function which can be used to search for this values ??

Thanks for helping :)

Body:
I found that in my code for-loop was only working for first value in list and it was populating "NOT IN DIC" without checking for other values. I have made below changes now and I am getting expected output.

def function01(row):
o_dict= {"ad32s":"rupesh","ed532":"Frank","dr501u":"David","ok132d":"Ripal","qw147":"ilesh","av345e":'carls'}
listA = row['Assigned'].split(";#")
listB = [i for i in listA if i.isdigit()==False]
for element in listA:
    if element in owner_dict:
        return owner_dict[element]
    else:
        continue
return "NOT IN DIC"

df['New_column'] = df.apply(lambda x: function01(x), axis=1)


问:
Unable to read data from the transport connection: the connection was closed
The exception is Remoting Exception - Authentication Failure. The detailed message says "Unable to read data from the transport connection: the connection was closed."

I'm having trouble with creating two simple servers that can comunicate as remote objects in C#. ServerInfo is just a class I created that holds the IP and Port and can give back the address. It works fine, as I used it before, and I've debugged it. Also the server is starting just fine, no exception is thrown, and the channel is registered without problems. I'm using Forms to do the interfaces, and call some of the methods on the server, but didn't find any problems in passing the parameters from the FormsApplication to the server when debugging. All seems fine in that chapter.

```<code>public ChordServerProgram()
        {
            RemotingServices.Marshal(this, "PADIBook");
            nodeInt = 0;
        }

        public void startServer()
        {
            try
            {
                serverChannel = new TcpChannel(serverInfo.Port);
                ChannelServices.RegisterChannel(serverChannel, true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
</code>```

I run two instances of this program. Then startNode is called on one of the instances of the application. The port is fine, the address generated is fine as well. As you can see, I'm using the IP for localhost, since this server is just for testing purposes.

```<code>public void startNode(String portStr)
            {
                IPAddress address = IPAddress.Parse("127.0.0.1");
                Int32 port = Int32.Parse(portStr);
                serverInfo = new ServerInfo(address, port);

                startServer();

                //node = new ChordNode(serverInfo,this);

            }
</code>```

Then, in the other istance, through the interface again, I call another startNode method, giving it a seed server to get information from. This is where it goes wrong. When it calls the method on the seedServer proxy it just got, a RemotingException is thrown, due to an authentication failure. (The parameter I'll want to get is the node, I'm just using the int to make sure the ChordNode class has nothing to do with this error.)

```<code>        public void startNode(String portStr, String seedStr)
        {
            IPAddress address = IPAddress.Parse("127.0.0.1");
            Int32 port = Int32.Parse(portStr);
            serverInfo = new ServerInfo(address, port);

            IPAddress addressSeed = IPAddress.Parse("127.0.0.1");
            Int32 portSeed = Int32.Parse(seedStr);
            ServerInfo seedInfo = new ServerInfo(addressSeed, portSeed);

            startServer();

            ChordServerProgram seedServer = (ChordServerProgram)Activator.GetObject(typeof(ChordServerProgram), seedInfo.GetFullAddress());

//            node = new ChordNode(serverInfo,this);
            int seedNode = seedServer.nodeInt;
//            node.chordJoin(seedNode.self);

        }
</code>```

答:
Try setting the ensureSecurity to false, and it should start working.

    ChannelServices.RegisterChannel(serverChannel, false);

ContentLicense: CC BY-SA 2.5

Body:
The exception is Remoting Exception - Authentication Failure. The detailed message says "Unable to read data from the transport connection: the connection was closed."

I'm having trouble with creating two simple servers that can comunicate as remote objects in C#. ServerInfo is just a class I created that holds the IP and Port and can give back the address. It works fine, as I used it before, and I've debugged it. Also the server is starting just fine, no exception is thrown, and the channel is registered without problems. I'm using Forms to do the interfaces, and call some of the methods on the server, but didn't find any problems in passing the parameters from the FormsApplication to the server when debugging. All seems fine in that chapter.

public ChordServerProgram()
        {
            RemotingServices.Marshal(this, "PADIBook");
            nodeInt = 0;
        }

        public void startServer()
        {
            try
            {
                serverChannel = new TcpChannel(serverInfo.Port);
                ChannelServices.RegisterChannel(serverChannel, true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

I run two instances of this program. Then startNode is called on one of the instances of the application. The port is fine, the address generated is fine as well. As you can see, I'm using the IP for localhost, since this server is just for testing purposes.

public void startNode(String portStr)
            {
                IPAddress address = IPAddress.Parse("127.0.0.1");
                Int32 port = Int32.Parse(portStr);
                serverInfo = new ServerInfo(address, port);

                startServer();

                //node = new ChordNode(serverInfo,this);

            }

Then, in the other istance, through the interface again, I call another startNode method, giving it a seed server to get information from. This is where it goes wrong. When it calls the method on the seedServer proxy it just got, a RemotingException is thrown, due to an authentication failure. (The parameter I'll want to get is the node, I'm just using the int to make sure the ChordNode class has nothing to do with this error.)

        public void startNode(String portStr, String seedStr)
        {
            IPAddress address = IPAddress.Parse("127.0.0.1");
            Int32 port = Int32.Parse(portStr);
            serverInfo = new ServerInfo(address, port);

            IPAddress addressSeed = IPAddress.Parse("127.0.0.1");
            Int32 portSeed = Int32.Parse(seedStr);
            ServerInfo seedInfo = new ServerInfo(addressSeed, portSeed);

            startServer();

            ChordServerProgram seedServer = (ChordServerProgram)Activator.GetObject(typeof(ChordServerProgram), seedInfo.GetFullAddress());

//            node = new ChordNode(serverInfo,this);
            int seedNode = seedServer.nodeInt;
//            node.chordJoin(seedNode.self);

        }

ContentLicense: CC BY-SA 3.0


问:
How can I convert a string to boolean in JavaScript?
Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

```<code>var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
</code>```

Is there a better way to accomplish this?

答:
Use an if statment:

function parseBool(str) {
  if (str.toLowerCase() == 'true') {
    var val = true;
  } else if (str.toLowerCase() == 'false') {
    var val = false;
  } else {
    //If it is not true of false it returns undefined.//
    var val = undefined;
  }
  return val;
}
console.log(parseBool(''), typeof parseBool(''));
console.log(parseBool('TrUe'), typeof parseBool('TrUe'));
console.log(parseBool('false'), typeof parseBool('false'));```

OwnerDisplayName: Kevin

Body:
Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better way to accomplish this?


问:
Svelte 3, async onMount or a valid alternative?
What I need is to use async-await in Svelte onMount().

Or maybe you can suggest me what is wrong and what I can use alternatively.

To Reproduce

go here: https://svelte.dev/repl/000ae69c0fe14d9483678d4ace874726?version=3.23.0

open the console

click on the button

you should see messages: "Mounting..." and "A lot of background work..."

if you click again the destroy message is not written

WHY?

Did onMount() recognizes the async function promise? Should it?

I need that async behavior because I need to wait for function lazyLoading() before rendering the Child component.

Is there an alternative way to do this in Svelte?

答:
Just to explain why onMount can't be an async function (this might change in future, but don't expect it to):

You can return a function from an onMount handler that is called when the component is destroyed. But async functions can only return a promise. Since a promise isn't a function, Svelte will ignore the return value.

This is the same as useEffect in React, incidentally — the function must be synchronous in order to avoid race conditions. The recommended solution for onMount is the same as for useEffect — place an async function inside the handler:

onMount(() => {
  async function foo() {
    bar = await baz();
  }

  foo();

  return () => console.log('destroyed');
});
```

(Note that you're responsible for handling any race conditions that arise as a result of the component being destroyed before the promise resolves, though assigning state inside a destroyed component is harmless.)

I've opened an issue to discuss providing more useful feedback in these situations: https://github.com/sveltejs/svelte/issues/4944

Body:
Just to explain why onMount can't be an async function (this might change in future, but don't expect it to):

You can return a function from an onMount handler that is called when the component is destroyed. But async functions can only return a promise. Since a promise isn't a function, Svelte will ignore the return value.

This is the same as useEffect in React, incidentally — the function must be synchronous in order to avoid race conditions. The recommended solution for onMount is the same as for useEffect — place an async function inside the handler:

onMount(() => {
  async function foo() {
    bar = await baz();
  }

  foo();

  return () => console.log('destroyed');
});

(Note that you're responsible for handling any race conditions that arise as a result of the component being destroyed before the promise resolves, though assigning state inside a destroyed component is harmless.)

I've opened an issue to discuss providing more useful feedback in these situations: https://github.com/sveltejs/svelte/issues/4944


问:
Boolean statement logic not correct
I have the following code:

```<code>if (date.datetime.today().weekday == 5) or (date.datetime.today().weekday == 6):
     print('True')
</code>```

What i am trying to do here is that the if statement should be true if today is saturday or sunday.
The output is false even though today is Sunday. Why is this not True?

答:
Your code has several problems:

Your imports are likely wrong, and you didn't make it clear what you are using.

weekday is a function, so you must call it, e.g. weekday().

You are calling today() twice, which means it could give you a race condition near midnight.

Therefore it should probably be:

```<code>import datetime
weekday = datetime.date.today().weekday()
# Or: weekday = datetime.datetime.today().weekday()
if ((weekday == 5) or (weekday == 6)):
    print("True")
</code>```

Title: Boolean statement logic not correct

Body:
I have the following code:

if (date.datetime.today().weekday == 5) or (date.datetime.today().weekday == 6):
     print('True')

What i am trying to do here is that the if statement should be true if today is saturday or sunday.
The output is false even though today is Sunday. Why is this not True?

Body:
Your code has several problems:

Your imports are likely wrong, and you didn't make it clear what you are using.

weekday is a function, so you must call it, e.g. weekday().

You are calling today() twice, which means it could give you a race condition near midnight.

Therefore it should probably be:

import datetime
weekday = datetime.date.today().weekday()
# Or: weekday = datetime.datetime.today().weekday()
if ((weekday == 5) or (weekday == 6)):
    print("True")


问:
Retrieving ordered data from firebase real-time database Kotlin
I have a real-time firebase database that looks like this.

There are many elements along with 3 shown in the image on the same level as those 3.

What I want to do is fetch them in Kotlin based on parameter OrderCount.

Therefore when I fetch I want Dragon Fruit to be 1st, Cherimoya to be 2nd,Ackee to be 3rd and so on.

Based on Stackoverflow and other resources this is what I tried.

```<code>            val refFeatured1 = FirebaseDatabase.getInstance().getReference("/all_items/Exotic_Fruits")
                .orderByChild("OrderCount")
            refFeatured1.addValueEventListener(object : ValueEventListener {
                override fun onCancelled(p0: DatabaseError) {
                    Log.d("LoadingActivity", "Error in Fetching all items data : ${p0}")
                    return
                }
                override fun onDataChange(p0: DataSnapshot) {
                    Log.d("LoadingActivity", "${p0}")
            }
        })
</code>```

The result of the following query gives me other elements.

This result does not change even if I change the parameter of orderByChild.

This is the code for getting the result.
What I also want is getting only the first 5 results after ordering.

Will limitToFirst(5) attribute be used to achieve this or is there any other way.

The same code when I tried from python gives me perfect result:
The code is:

```<code>ref = db.reference('all_items/Exotic_Fruits').order_by_child("OrderCount").limit_to_first(5)
refData = ref.get()
</code>```

答:
When you request ordered data from Firebase, you get a DataSnapshot with the results. For each matching node, that contains:

The value of the node

The key of the node

The position of the node, relative to the other results.

When you request the value of the node as a whole (by calling value or as you do by printing it), the results are converted into a Map object. In a map there is no order between the keys, so the ordering information gets lost.

To maintain the information on the order of the results, you need to loop over the DataSnapshot.children list.

```<code>val refFeatured1 = FirebaseDatabase.getInstance().getReference("/all_items/Exotic_Fruits")
    .orderByChild("OrderCount")
refFeatured1.addValueEventListener(object : ValueEventListener {
    override fun onCancelled(p0: DatabaseError) {
        Log.d("LoadingActivity", "Error in Fetching all items data : ${p0}")
        return
    }
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        for (snapshot in dataSnapshot.children) {
            Log.d("LoadingActivity", "${snapshot}")
        }
    }
})
</code>```

Also see the Firebase documentation of read lists with a value listener, where I got the loop from.

Body:
I have a real-time firebase database that looks like this.

There are many elements along with 3 shown in the image on the same level as those 3.

What I want to do is fetch them in Kotlin based on parameter OrderCount.

Therefore when I fetch I want Dragon Fruit to be 1st, Cherimoya to be 2nd,Ackee to be 3rd and so on.

Based on Stackoverflow and other resources this is what I tried.

            val refFeatured1 = FirebaseDatabase.getInstance().getReference("/all_items/Exotic_Fruits")
                .orderByChild("OrderCount")
            refFeatured1.addValueEventListener(object : ValueEventListener {
                override fun onCancelled(p0: DatabaseError) {
                    Log.d("LoadingActivity", "Error in Fetching all items data : ${p0}")
                    return
                }
                override fun onDataChange(p0: DataSnapshot) {
                    Log.d("LoadingActivity", "${p0}")
            }
        })

The result of the following query gives me other elements.

This result does not change even if I change the parameter of orderByChild.

This is the code for getting the result.
What I also want is getting only the first 5 results after ordering.

Will limitToFirst(5) attribute be used to achieve this or is there any other way.

The same code when I tried from python gives me perfect result:
The code is:

ref = db.reference('all_items/Exotic_Fruits').order_by_child("OrderCount").limit_to_first(5)
refData = ref.get()

Body:
When you request ordered data from Firebase, you get a DataSnapshot with the results. For each matching node, that contains:

The value of the node

The key of the node

The position of the node, relative to the other results.

When you request the value of the node as a whole (by calling value or as you do by printing it), the results are converted into a Map object. In a map there is no order between the keys, so the ordering information gets lost.

To maintain the information on the order of the results, you need to loop over the DataSnapshot.children list.

val refFeatured1 = FirebaseDatabase.getInstance().getReference("/all_items/Exotic_Fruits")
    .orderByChild("OrderCount")
refFeatured1.addValueEventListener(object : ValueEventListener {
    override fun onCancelled(p0: DatabaseError) {
        Log.d("LoadingActivity", "Error in Fetching all items data : ${p0}")
        return
    }
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        for (snapshot in dataSnapshot.children) {
            Log.d("LoadingActivity", "${snapshot}")
        }
    }
})

Also see the Firebase documentation of read lists with a value listener, where I got the loop from.


问:
I need to make a sql
**

```<code>SELECT clientName, orderID FROM
Orders INNER JOIN clients ON orders.clientID = clients.clientID;
</code>```

**

I can show every client and each of their orders. Help me correct my SQL syntax, so I am showing the number of orders for each client?

I also want my results to be ordered alphabetically by client name,

please write a new SQL syntax for me!

答:
You can use aggregation:

```<code>select c.clientName, count(*) no_orders
from clients c
inner join orders o on o.clientID = c.clientID
group by c.clientID, c.clientName
</code>```

Notes:

table aliases make the query easier to read and write

adding the id of the client to the group by clause handles the possibility that different clients might have the same name

in general, you want to avoid camel case identifiers (ClientName) and use snake case instead (client_name): from database perspective, identifiers are case insensitive (unless quoted)

Title: I need to make a sql

Body:
**

SELECT clientName, orderID FROM
Orders INNER JOIN clients ON orders.clientID = clients.clientID;

**

I can show every client and each of their orders. Help me correct my SQL syntax, so I am showing the number of orders for each client?

I also want my results to be ordered alphabetically by client name,

please write a new SQL syntax for me!

Body:
You can use aggregation:

select c.clientName, count(*) no_orders
from clients c
inner join orders o on o.clientID = c.clientID
group by c.clientID, c.clientName

Notes:

table aliases make the query easier to read and write

adding the id of the client to the group by clause handles the possibility that different clients might have the same name

in general, you want to avoid camel case identifiers (ClientName) and use snake case instead (client_name): from database perspective, identifiers are case insensitive (unless quoted)


问:
Extract features from pretrained resnet50 in pytorch
Hy guys, i want to extract the in_features of Fully connected layer of my pretrained resnet50.

I create before a method that give me the vector of features:

```<code>def get_vector(image):

#layer = model._modules.get('fc')

layer = model.fc
my_embedding = torch.zeros(2048) #2048 is the in_features of FC , output of avgpool

def copy_data(m, i, o):

    my_embedding.copy_(o.data)

h = layer.register_forward_hook(copy_data)
tmp = model(image)

h.remove()

# return the vector
return my_embedding
</code>```

after I call this method here:

```<code>column = ["FlickrID", "Features"]

path = "./train_dataset/train_imgs/"

pathCSV = "./train_dataset/features/img_info_TRAIN.csv"

f_id=[]
features_extr=[]

df = pd.DataFrame(columns=column)

tr=transforms.Compose([transforms.Resize(256),
                       transforms.CenterCrop(224),
                       transforms.ToTensor(),
                       transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])

test = Dataset(path, pathCSV, transform=tr)

test_loader = DataLoader(test, batch_size=1, num_workers=2, shuffle = False)

#Leggiamo le immagini
for batch in test_loader:
    nome = batch['FlickrID']
    f_id.append(nome)
    image = batch['image']

    #print(image)
    with torch.no_grad():
        pred = get_vector(image)

    features_extr.append(pred)

df["FlickrID"] = f_id
df["Features"] = features_extr

df.to_hdf("Places.h5", key='df', mode='w')

</code>```

I have an error like this:
output with shape [2048] doesn't match the broadcast shape [1, 2048, 1, 2048]

How can I take the in_feature of Fully Connected of this resnet50?
The Dataset is a customized Dataset class.

Sorry for my bad english

答:
The model takes batched inputs, that means the input to the fully connected layer has size [batch_size, 2048]. Because you are using a batch size of 1, that becomes [1, 2048]. Therefore that doesn't fit into a the tensor torch.zeros(2048), so it should be torch.zeros(1, 2048) instead.

You are also trying to use the output (o) of the layer model.fc instead of the input (i).

Besides that, using hooks is overly complicated for this and a much easier way to get features is to modify the model by replacing model.fc with nn.Identity, which just returns the input as the output, and since the features are its input, the output of the entire model will be the features.

model.fc = nn.Identity()

features = model(image)
```

Body:
Hy guys, i want to extract the in_features of Fully connected layer of my pretrained resnet50.

I create before a method that give me the vector of features:

def get_vector(image):

#layer = model._modules.get('fc')

layer = model.fc
my_embedding = torch.zeros(2048) #2048 is the in_features of FC , output of avgpool

def copy_data(m, i, o):

    my_embedding.copy_(o.data)

h = layer.register_forward_hook(copy_data)
tmp = model(image)

h.remove()

# return the vector
return my_embedding

after I call this method here:

column = ["FlickrID", "Features"]

path = "./train_dataset/train_imgs/"

pathCSV = "./train_dataset/features/img_info_TRAIN.csv"

f_id=[]
features_extr=[]

df = pd.DataFrame(columns=column)

tr=transforms.Compose([transforms.Resize(256),
                       transforms.CenterCrop(224),
                       transforms.ToTensor(),
                       transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])

test = Dataset(path, pathCSV, transform=tr)

test_loader = DataLoader(test, batch_size=1, num_workers=2, shuffle = False)

#Leggiamo le immagini
for batch in test_loader:
    nome = batch['FlickrID']
    f_id.append(nome)
    image = batch['image']

    #print(image)
    with torch.no_grad():
        pred = get_vector(image)

    features_extr.append(pred)

df["FlickrID"] = f_id
df["Features"] = features_extr

df.to_hdf("Places.h5", key='df', mode='w')

I have an error like this:
output with shape [2048] doesn't match the broadcast shape [1, 2048, 1, 2048]

How can I take the in_feature of Fully Connected of this resnet50?
The Dataset is a customized Dataset class.

Sorry for my bad english


问:
Rcpp select/subset NumericMatrix column by a NumericVector
I can select all the rows of a matrix and a range of columns of a matrix as follows:

```<code>library(Rcpp)
cppFunction('
NumericMatrix subset(NumericMatrix x){
  return x(_, Range(0, 1));
}
')
</code>```

However, I would like to select columns based on a NumericVector y which, for instance, could be something like c(0, 1, 0, 0, 1). I tried this:

```<code>library(Rcpp)
cppFunction('
NumericMatrix subset(NumericMatrix x, NumericVector y){
  return x(_, y);
}
')
</code>```

but it doesn't compile. How do I do it?

答:
Alas, Rcpp doesn't have great support for non-contiguous views or selecting in a single statement only columns 1 and 4. As you saw, selecting contiguous views or selecting all columns is accessible with Rcpp::Range(). You'll likely want to upgrade to RcppArmadillo for better control over matrix subsets.

RcppArmadillo subset examples

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::mat matrix_subset_idx(const arma::mat& x,
                            const arma::uvec& y) {

    // y must be an integer between 0 and columns - 1
    // Allows for repeated draws from same columns.
    return x.cols( y );
}

// [[Rcpp::export]]
arma::mat matrix_subset_logical(const arma::mat& x,
                                const arma::vec& y) {
    // Assumes that y is 0/1 coded.
    // find() retrieves the integer index when y is equivalent 1.
    return x.cols( arma::find(y == 1) );
}
```

<h3>Test</h3>

<pre class="lang-r prettyprint-override"><code># Sample data
x = matrix(1:15, ncol = 5)
x
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    4    7   10   13
# [2,]    2    5    8   11   14
# [3,]    3    6    9   12   15

# Subset only when 1 (TRUE) is found:
matrix_subset_logical(x, c(0, 1, 0, 0, 1))
#      [,1] [,2]
# [1,]    4   13
# [2,]    5   14
# [3,]    6   15

# Subset with an index representing the location
# Note: C++ indices start at 0 not 1!
matrix_subset_idx(x, c(1, 3))
#      [,1] [,2]
# [1,]    4   13
# [2,]    5   14
# [3,]    6   15
</code>```

Pure Rcpp logic

If you do not want to take on the dependency of armadillo, then the equivalent for the matrix subset in Rcpp is:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericMatrix matrix_subset_idx_rcpp(
        Rcpp::NumericMatrix x, Rcpp::IntegerVector y) {

    // Determine the number of observations
    int n_cols_out = y.size();

    // Create an output matrix
    Rcpp::NumericMatrix out = Rcpp::no_init(x.nrow(), n_cols_out);

    // Loop through each column and copy the data.
    for(unsigned int z = 0; z < n_cols_out; ++z) {
        out(Rcpp::_, z) = x(Rcpp::_, y[z]);
    }

    return out;
}
```

Body:
I can select all the rows of a matrix and a range of columns of a matrix as follows:

library(Rcpp)
cppFunction('
NumericMatrix subset(NumericMatrix x){
  return x(_, Range(0, 1));
}
')

However, I would like to select columns based on a NumericVector y which, for instance, could be something like c(0, 1, 0, 0, 1). I tried this:

library(Rcpp)
cppFunction('
NumericMatrix subset(NumericMatrix x, NumericVector y){
  return x(_, y);
}
')

but it doesn't compile. How do I do it?

Body:
Alas, Rcpp doesn't have great support for non-contiguous views or selecting in a single statement only columns 1 and 4. As you saw, selecting contiguous views or selecting all columns is accessible with Rcpp::Range(). You'll likely want to upgrade to RcppArmadillo for better control over matrix subsets.

RcppArmadillo subset examples

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::mat matrix_subset_idx(const arma::mat& x,
                            const arma::uvec& y) {

    // y must be an integer between 0 and columns - 1
    // Allows for repeated draws from same columns.
    return x.cols( y );
}

// [[Rcpp::export]]
arma::mat matrix_subset_logical(const arma::mat& x,
                                const arma::vec& y) {
    // Assumes that y is 0/1 coded.
    // find() retrieves the integer index when y is equivalent 1.
    return x.cols( arma::find(y == 1) );
}

Test

# Sample data
x = matrix(1:15, ncol = 5)
x
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    4    7   10   13
# [2,]    2    5    8   11   14
# [3,]    3    6    9   12   15

# Subset only when 1 (TRUE) is found:
matrix_subset_logical(x, c(0, 1, 0, 0, 1))
#      [,1] [,2]
# [1,]    4   13
# [2,]    5   14
# [3,]    6   15

# Subset with an index representing the location
# Note: C++ indices start at 0 not 1!
matrix_subset_idx(x, c(1, 3))
#      [,1] [,2]
# [1,]    4   13
# [2,]    5   14
# [3,]    6   15

Pure Rcpp logic

If you do not want to take on the dependency of armadillo, then the equivalent for the matrix subset in Rcpp is:

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericMatrix matrix_subset_idx_rcpp(
        Rcpp::NumericMatrix x, Rcpp::IntegerVector y) {

    // Determine the number of observations
    int n_cols_out = y.size();

    // Create an output matrix
    Rcpp::NumericMatrix out = Rcpp::no_init(x.nrow(), n_cols_out);

    // Loop through each column and copy the data.
    for(unsigned int z = 0; z < n_cols_out; ++z) {
        out(Rcpp::_, z) = x(Rcpp::_, y[z]);
    }

    return out;
}


问:
delete all sharedPreferences for my app when user signs out
I have an android app with a number of activities, and a number of specific preference files that are created. When a user sign out of my app, I want to delete absolutely all shared preferences. Understand that I cannot use context.getSharedPreferences("A_PREFS_FILE", 0).edit().clear().commit() as that would only clear one specific file. I want to clear all the preference files associated with my app. Is there a way to do that?

答:
SharedPreferences directory path : Environment.getDataDirectory() + "/data/" + ActivateAccountActivity.this.getPackageName() + "/shared_prefs"

Use "for" loop to delete all the files, like so :

```<code>File sprefs_directory = new File(Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/shared_prefs");
File[] files = filesirectory.listFiles();
for(File file : files) {
  file.delete();
}
</code>```

Body:
SharedPreferences directory path : Environment.getDataDirectory() + "/data/" + ActivateAccountActivity.this.getPackageName() + "/shared_prefs"

Use "for" loop to delete all the files, like so :

File sprefs_directory = new File(Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/shared_prefs");
File[] files = filesirectory.listFiles();
for(File file : files) {
  file.delete();
}


问:
update one value in JsonStore
How to update particular value in Jsone store dynamically?
When adding one new record to store, based on new record, update existing records in store</p>

答:
it depends you want to update existing record before adding new records to store or after adding new records to store. for updating after adding new records to store you can do something like:

```<code>store.on('add', function(store, newRecordsArray, indexWhereRecordsAdded ){
    /* handle update here */
});
store.loadData( newDataArray, true /* to append data */ );
</code>```

for updating before adding new records to store just do it before passing data to loadData

Title: update one value in JsonStore

Body:
it depends you want to update existing record before adding new records to store or after adding new records to store. for updating after adding new records to store you can do something like:

store.on('add', function(store, newRecordsArray, indexWhereRecordsAdded ){
    /* handle update here */
});
store.loadData( newDataArray, true /* to append data */ );

for updating before adding new records to store just do it before passing data to loadData


问:
Uncaught TypeError: Cannot read property 'cloneNode' of undefined
I am trying to add a duplicate content via clicking the add button, But getting  "Uncaught TypeError: Cannot read property 'cloneNode' of undefined".Whats wrgg>>????

this is the code:

```<code>  var item = document.getElementById("question")[0];
  var cloneItem = item.cloneNode(true);
  document.body.appendChild(cloneItem);
}
</code>```

http://jsfiddle.net/syr9vtwx/

答:
you just remove "[0]"</p>

```<code>var item = document.getElementById("question");
</code>```

Body:
I am trying to add a duplicate content via clicking the add button, But getting  "Uncaught TypeError: Cannot read property 'cloneNode' of undefined".Whats wrgg>>????

this is the code:

  var item = document.getElementById("question")[0];
  var cloneItem = item.cloneNode(true);
  document.body.appendChild(cloneItem);
}

http://jsfiddle.net/syr9vtwx/

Body:
you just remove "[0]"

var item = document.getElementById("question");


问:
Angular resolver observable completes too early
I am passing a subject as an observable from a service to a resolver. The service may complete the observable when an http request completes or when it finds that the data it needs is cached. In the second case, where the data is cached it looks like the observable completes too early because the route transition does not happen. if i put the requestSubject.complete() inside a setTimeout with some timeout it works but otherwise it doesnt.</p>

```<code>//resolve function from resolver
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
  const id = +route.paramMap.get('id');
  const language = route.queryParamMap.get('language');
  const request = this.service.get(id, language);
  request.pipe(share()).subscribe(
    () => {},
    () => { this.router.navigateByUrl(AppRoutingConfig.search); });
  return request;
}

//the service get function
get(id: number, language: string): Observable<any> {
  const requestSubject = new Subject();
  if (!isDataCached(id)) {
    const url = `some url`;
    const sub = this.http.get(url).subscribe((item: any) => {
      requestSubject.next(1);
    }, () => {
        requestSubject.error(0);
    }, () => {
      requestSubject.complete();
    });
  } else {
    requestSubject.complete();
  }
  return requestSubject.asObservable();
}
</code>```

答:
looks like the observable completes too early because the route transition does not happen

I'd say that the Subject does not do anything.

If the data is not cached, requestSubject.complete(); will run, which will synchronously emit a complete notification to all its subscribers.

This means that returning the requestSubject after won't do anything, because the requestSubject won't emit a value.

It works when the data is not cached because the by the time that Subject emits and completes, it would already have a subscriber which can decide whether or not the route transition should continue.

For example, this is how Angular internally subscribes to all the observables provided in a resolve property:

return from(keys).pipe(
      mergeMap(
          (key: string) => getResolver(resolve[key], futureARS, futureRSS, moduleInjector)
                               .pipe(tap((value: any) => {
                                 data[key] = value;
                               }))),
      takeLast(1),
      mergeMap(() => {
        // Ensure all resolvers returned values, otherwise don't emit any "next" and just complete
        // the chain which will cancel navigation
        if (Object.keys(data).length === keys.length) {
          return of(data);
        }
        return EMPTY;
      }),
  );
```

<p><em>Source</em>,</p>

<p>as you can see, if the <code>resolve()</code> fn didn't emit any values, an <code>EMPTY</code> observable will be emitted, which will in turn cause the navigation to be cancelled.</p>

<hr>

<p>I'd also modify a bit your <code>resolve</code> function:</p>

<pre class="lang-js prettyprint-override"><code>resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
  const id = +route.paramMap.get('id');
  const language = route.queryParamMap.get('language');
  const request$ = this.service.get(id, language);

  return request$.pipe(
    tap(
      null,
      err => this.router.navigateByUrl(AppRoutingConfig.search),
    ),
  );
}
</code>```

I considered share() to be unnecessary, as you'll have only one subscriber.

So, a quick fix(which I wouldn't recommend at all) I think would be to also send the cached value when it's the case:

// Inside `service.get()`

else {
  // The value is cached

  of(getCachedValue(id)).pipe(
    subscribeOn(asyncScheduler) // delay(0) would also work
  ).subscribe(v => {
    requestSubject.next(v)
    requestSubject.complete()
  })
}

return requestSubject.
```

Another solution would be to consider adding the caching layer at the interceptors level, as I think this will simplify a lot your code. If you decide to switch to this approach, your resolve() fn can return something like this.service.get(...), because eveerything will be intercepted by the interceptors so you can return from there the cached values.

Body:
I am passing a subject as an observable from a service to a resolver. The service may complete the observable when an http request completes or when it finds that the data it needs is cached. In the second case, where the data is cached it looks like the observable completes too early because the route transition does not happen. if i put the requestSubject.complete() inside a setTimeout with some timeout it works but otherwise it doesnt.

//resolve function from resolver
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
  const id = +route.paramMap.get('id');
  const language = route.queryParamMap.get('language');
  const request = this.service.get(id, language);
  request.pipe(share()).subscribe(
    () => {},
    () => { this.router.navigateByUrl(AppRoutingConfig.search); });
  return request;
}

//the service get function
get(id: number, language: string): Observable<any> {
  const requestSubject = new Subject();
  if (!isDataCached(id)) {
    const url = `some url`;
    const sub = this.http.get(url).subscribe((item: any) => {
      requestSubject.next(1);
    }, () => {
        requestSubject.error(0);
    }, () => {
      requestSubject.complete();
    });
  } else {
    requestSubject.complete();
  }
  return requestSubject.asObservable();
}

Body:
looks like the observable completes too early because the route transition does not happen

I'd say that the Subject does not do anything.

If the data is not cached, requestSubject.complete(); will run, which will synchronously emit a complete notification to all its subscribers.

This means that returning the requestSubject after won't do anything, because the requestSubject won't emit a value.

It works when the data is not cached because the by the time that Subject emits and completes, it would already have a subscriber which can decide whether or not the route transition should continue.

For example, this is how Angular internally subscribes to all the observables provided in a resolve property:

return from(keys).pipe(
      mergeMap(
          (key: string) => getResolver(resolve[key], futureARS, futureRSS, moduleInjector)
                               .pipe(tap((value: any) => {
                                 data[key] = value;
                               }))),
      takeLast(1),
      mergeMap(() => {
        // Ensure all resolvers returned values, otherwise don't emit any "next" and just complete
        // the chain which will cancel navigation
        if (Object.keys(data).length === keys.length) {
          return of(data);
        }
        return EMPTY;
      }),
  );

Source,

as you can see, if the resolve() fn didn't emit any values, an EMPTY observable will be emitted, which will in turn cause the navigation to be cancelled.

I'd also modify a bit your resolve function:

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): any {
  const id = +route.paramMap.get('id');
  const language = route.queryParamMap.get('language');
  const request$ = this.service.get(id, language);

  return request$.pipe(
    tap(
      null,
      err => this.router.navigateByUrl(AppRoutingConfig.search),
    ),
  );
}

I considered share() to be unnecessary, as you'll have only one subscriber.

So, a quick fix(which I wouldn't recommend at all) I think would be to also send the cached value when it's the case:

// Inside `service.get()`

else {
  // The value is cached

  of(getCachedValue(id)).pipe(
    subscribeOn(asyncScheduler) // delay(0) would also work
  ).subscribe(v => {
    requestSubject.next(v)
    requestSubject.complete()
  })
}

return requestSubject.

Another solution would be to consider adding the caching layer at the interceptors level, as I think this will simplify a lot your code. If you decide to switch to this approach, your resolve() fn can return something like this.service.get(...), because eveerything will be intercepted by the interceptors so you can return from there the cached values.


问:
Save UITextView String With \n Instead of Line Breaks (Swift)
I have a UITextView in my Swift app in which users can input text. They can input text with as many line breaks as they like but I need to save the string with the newline command (\n). How would I do this?

For example, my user inputs

```<code>Line 1
Line 2
Line 3
</code>```

in the UITextView. If I was to retrieve the string...

```<code>let string = textview.text!
</code>```

this would return

```<code>"Line 1
Line 2
Line 3"
</code>```

when I would like for it to return

```<code>"Line1\nLine2\nLine3"
</code>```

How would I go about doing this? Can I use a form of replacingOccurrences(of:with:)? I feel like I'm missing a fairly obvious solution...

答:
Eureka! After WAY too much research and learning all about String escapes, I found a very simple solution. I'm quite surprised that this isn't an answer out there already (as far as I can tell haha) so hopefully, this helps someone!

It's actually quite simple and this will work of any String you could be using.

```<code>textView.text!.replacingOccurrences(of: "\n", with: "\\n")
</code>```

Explanation:
Ok so as you can tell, it's quite simple. We want to replace the newline command \n with the string "\n". The problem is that if we replace \n with \n, it's just going to transfer over to a newline, not a string. This is why escapes are so important. As you can see, I am replacing \n with \\n. By adding an extra \ we escape the command \n entirely which turns it into a string.

I hope this helps someone! Have a great day!

Body:
I have a UITextView in my Swift app in which users can input text. They can input text with as many line breaks as they like but I need to save the string with the newline command (\n). How would I do this?

For example, my user inputs

Line 1
Line 2
Line 3

in the UITextView. If I was to retrieve the string...

let string = textview.text!

this would return

"Line 1
Line 2
Line 3"

when I would like for it to return

"Line1\nLine2\nLine3"

How would I go about doing this? Can I use a form of replacingOccurrences(of:with:)? I feel like I'm missing a fairly obvious solution...

Body:
Eureka! After WAY too much research and learning all about String escapes, I found a very simple solution. I'm quite surprised that this isn't an answer out there already (as far as I can tell haha) so hopefully, this helps someone!

It's actually quite simple and this will work of any String you could be using.

textView.text!.replacingOccurrences(of: "\n", with: "\\n")

Explanation:
Ok so as you can tell, it's quite simple. We want to replace the newline command \n with the string "\n". The problem is that if we replace \n with \n, it's just going to transfer over to a newline, not a string. This is why escapes are so important. As you can see, I am replacing \n with \\n. By adding an extra \ we escape the command \n entirely which turns it into a string.

I hope this helps someone! Have a great day!


问:
Storing lots of small files: archive vs. filesystem
I am creating an application that requires a lot of image thumbnails (~3000, 5-25KB). Because speed is essential I plan on loading these images into memory when the application starts. At runtime, new thumbnails will be downloaded and added to the collective.

I could store them all in a folder, but reading thousands of files into memory when a program starts hardly seems efficient.

My second option would be to save them in some kind of (compressed) archive. This would make storage itself and loading more efficient (I think). However, new files will be added regularly, and that will probably not go as smoothly as just saving them in a folder.

Is storing a cache of small files in a (compressed) archive a bad idea or not? Are ZIP files the way to go? Would I be better off using uncompressed archives (and if so, what kind)?

All image files will be JPEG's.

Thanks in advance!

EDIT: I am considering to drop the "load everything into memory on application start" thing. This would simplify my question a little. My initial idea to put everything in one big file now seems less beneficial, since the problem of many files in one directory can be solved by hashing into subdirectories.

答:
I know this question has already answered but I think you need more options other than zipping.

While zip is good, It's not really affect much for JPEG since JPEG has already compressed.

Other thing you may want to consider is :

Put the image in Content Delivery Network (CDN)

Compress components with gzip ( mean the server will automatically zip every response ) and you dont need to write any code to unzip it later - it's handled by the browser automatically.

Since you mention JPEG, you may want to use JPEGTran.Run jpegtran on all your JPEGs.

This tool does lossless JPEG operations such as rotation and can also be used to optimize and remove comments and other useless information (such as EXIF information) from your images.
jpegtran -copy none -optimize -perfect src.jpg dest.jpg

Use Image Sprites. Instead of asking browser to download many image at same time, ask the browser to only download one.

For the details read : http://developer.yahoo.com/performance/rules.html#opt_images

For the basic examination how to improve your website performance you can try install YSlow ( plugin to detect uneffecient code ) in Firefox.

Hope that helps.


问:
Is there a way to add a cum sum to a fviz_eig plot?
I'm trying to realize a nice plot of PC together with the cumulative variance explained.
The dataframe I'm working on is available at https://www.kaggle.com/miroslavsabo/young-people-survey?select=responses.csv

```<code>df.responses <- read.csv("Data/responses.csv")
pref <- colnames(df.responses[0:63]) #columns for Music, Movies and Hobbies preferences
for(i in 1:length(pref)){
  df.responses[is.na(df.responses[,i]), i] <- median(df.responses[,i], na.rm = TRUE)
}
df.movies <- data.frame(df.responses[20:31])
</code>```

Above I just loaded the df, removed the na for the cols I'm interested in and selected the subset I want to PCA.

```<code>library(ggplot2)
library(factoextra)

pca.movies <- prcomp(df.movies, scale = TRUE,)
pca.movies$rotation <- -pca.movies$rotation
pca.movies$x <- -pca.movies$x

fviz_pca_var(pca.movies,
             col.var = "contrib",
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
             repel = TRUE
)

pv.movies <- pca.movies$sdev^2
pvp.movies <- pv.movies/sum(pv.movies)

pvp.movies

fviz_eig(pca.movies,
         addlabels = T,
         barcolor = "#E7B800",
         barfill = "#E7B800",
         linecolor = "#00AFBB",
         choice = "variance",
         ylim=c(0,25))

plot(cumsum(pvp.movies),xlab = "Cumulative proportion of Variance Explained", ylim=c(0,1),type = 'b')
</code>```

With the above I managed to obtain two nice plots for PCA, I would like to add to the second plot the line of cumulative sum (the one showed in the third ugly plot)
Is there a way to add such line to the fviz_eig plot?
I know this PCA is not really efficient, I'm just challenging myself with some dataviz.

答:
The object returned by fviz_eig is a ggplot object, thus you can merge the two plots as follows:

```<code>p <- fviz_eig(pca.movies,
         addlabels = T,
         barcolor = "#E7B800",
         barfill = "#E7B800",
         linecolor = "#00AFBB",
         choice = "variance",
         ylim=c(0,25))

df <- data.frame(x=1:length(pvp.movies),
                 y=cumsum(pvp.movies)*100/4)
p <- p +
     geom_point(data=df, aes(x, y), size=2, color="#00AFBB") +
     geom_line(data=df, aes(x, y), color="#00AFBB") +
     scale_y_continuous(sec.axis = sec_axis(~ . * 4,
                                   name = "Cumulative proportion of Variance Explained") )
print(p)
</code>```

Body:
I'm trying to realize a nice plot of PC together with the cumulative variance explained.
The dataframe I'm working on is available at https://www.kaggle.com/miroslavsabo/young-people-survey?select=responses.csv

df.responses <- read.csv("Data/responses.csv")
pref <- colnames(df.responses[0:63]) #columns for Music, Movies and Hobbies preferences
for(i in 1:length(pref)){
  df.responses[is.na(df.responses[,i]), i] <- median(df.responses[,i], na.rm = TRUE)
}
df.movies <- data.frame(df.responses[20:31])

Above I just loaded the df, removed the na for the cols I'm interested in and selected the subset I want to PCA.

library(ggplot2)
library(factoextra)

pca.movies <- prcomp(df.movies, scale = TRUE,)
pca.movies$rotation <- -pca.movies$rotation
pca.movies$x <- -pca.movies$x

fviz_pca_var(pca.movies,
             col.var = "contrib",
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
             repel = TRUE
)

pv.movies <- pca.movies$sdev^2
pvp.movies <- pv.movies/sum(pv.movies)

pvp.movies

fviz_eig(pca.movies,
         addlabels = T,
         barcolor = "#E7B800",
         barfill = "#E7B800",
         linecolor = "#00AFBB",
         choice = "variance",
         ylim=c(0,25))

plot(cumsum(pvp.movies),xlab = "Cumulative proportion of Variance Explained", ylim=c(0,1),type = 'b')

With the above I managed to obtain two nice plots for PCA, I would like to add to the second plot the line of cumulative sum (the one showed in the third ugly plot)
Is there a way to add such line to the fviz_eig plot?
I know this PCA is not really efficient, I'm just challenging myself with some dataviz.

Body:
The object returned by fviz_eig is a ggplot object, thus you can merge the two plots as follows:

p <- fviz_eig(pca.movies,
         addlabels = T,
         barcolor = "#E7B800",
         barfill = "#E7B800",
         linecolor = "#00AFBB",
         choice = "variance",
         ylim=c(0,25))

df <- data.frame(x=1:length(pvp.movies),
                 y=cumsum(pvp.movies)*100/4)
p <- p +
     geom_point(data=df, aes(x, y), size=2, color="#00AFBB") +
     geom_line(data=df, aes(x, y), color="#00AFBB") +
     scale_y_continuous(sec.axis = sec_axis(~ . * 4,
                                   name = "Cumulative proportion of Variance Explained") )
print(p)


问:
Error during Insert JSON object in variant data type -snowflake stored procedure
I'm facing an error when inserting a JSON object into a VARIANT data type column, from within a stored procedure in Snowflake.

Below is the reference code:

create or replace procedure test1234()
returns varchar not null
language javascript
as
$$
       var birthDateVar = 'BIRTH_DATE';
       var genderVar = 'GENDER';
       var countryVar = 'COUNTRY';
       var loanVar = 'LOAN_AMOUNT';
       var emailVar = 'EMAIL';
       var tableName = 'SF_STRUCT_STAGE_RAW';
       var UPDATE_DATE = "2019-01-01";
       var email = "XXX@gmail.com";
       var row_num = "1";
       var person_id = "1";
       var EMAILERROR = {
        "row_num": row_num,
        "person_id": person_id,
        "tableName": tableName,
        "fieldName": emailVar,
        "fieldValue": email,
        "errorDesc":  'value is invalid email'
       };

       var cmd = "insert into error_details_log values(:1,:2);";
       var stmt = snowflake.createStatement(
        {
            sqlText: cmd,
            binds: [EMAILERROR, UPDATE_DATE]
        }
        );
       stmt.execute();
       return emailError;
$$;
```

答:
Inserting Object types via binding variables directly is not currently supported from within Stored Procedures. Quoting the relevant portion from the Snowflake documentation:

When you bind JavaScript variables to SQL statements, Snowflake converts from the JavaScript data types to the SQL data types. You can bind variables of the following JavaScript data types:

number

string

SfDate

However, the example in the documentation for TIMESTAMP datatypes involving use of strings and recasting can be adapted for your use-case, using the PARSE_JSON(…) function and JSON.stringify(…) JavaScript API:

[…]
// Convert Object -> String
var EMAILERROR_str = JSON.stringify(EMAILERROR);

// Ask Snowflake to parse String as JSON (String -> Object)
var cmd = "insert into error_details_log select PARSE_JSON(:1), :2;";

var stmt = snowflake.createStatement(
  {
    sqlText: cmd,

    // Bind the String value, not the Object one
    binds: [EMAILERROR_str, UPDATE_DATE]

  }
);
[…]
```