问:
Boost property_tree error: conversion of data to type "j" failed when getting an element in a .ini file
I have a .ini file contains below data

```<code>[SYSTEM]
num_of_vps = 1
</code>```

And I have this code to read an element in .ini file. (uint defined as typedef unsigned int uint)

```<code>boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini(iniFilePath, pt);
hwCount = pt.get<uint>("SYSTEM.num_of_vps");
</code>```

I created a from files including above code and called it in a wrapper function in main.cc file. Then I am getting below error

terminate called after throwing an instance of 'boost_1_68_0::exception_detail::clone_impl<boost_1_68_0::exception_detail::error_info_injector<boost_1_68_0::property_tree::ptree_bad_data> >'
what():  conversion of data to type "j" failed
stack trace

```<code>#12 0x00002aaab613fcd5 in abort () from /lib64/libc.so.6
#13 0x00002aaab9b29315 in __gnu_cxx::__verbose_terminate_handler () at ../../../../src/gcc-7.3.0/libstdc++-v3/libsupc++/vterminate.cc:95
#14 0x00002aaab9a9e8f6 in __cxxabiv1::__terminate (handler=<optimized out>) at ../../../../src/gcc-7.3.0/libstdc++-v3/libsupc++/eh_terminate.cc:47
#15 0x00002aaab9a9e941 in std::terminate () at ../../../../src/gcc-7.3.0/libstdc++-v3/libsupc++/eh_terminate.cc:57
#16 0x00002aaab9a9ea74 in __cxxabiv1::__cxa_throw (obj=<optimized out>, tinfo=0x2aaab9e1ff60 <typeinfo for boost_1_68_0::exception_detail::clone_impl<boost_1_68_0::exception_detail::error_info_injector<boost_1_68_0::property_tree::ptree_bad_data> >>, dest=0x2aaab99bef18 <boost_1_68_0::exception_detail::clone_impl<boost_1_68_0::exception_detail::error_info_injector<boost_1_68_0::property_tree::ptree_bad_data> >::~clone_impl()>) at ../../../../src/gcc-7.3.0/libstdc++-v3/libsupc++/eh_throw.cc:93
#17 0x00002aaab99bec82 in boost_1_68_0::throw_exception<boost_1_68_0::exception_detail::error_info_injector<boost_1_68_0::property_tree::ptree_bad_data> > (e=...) at throw_exception.hpp:72
#18 0x00002aaab99be576 in boost_1_68_0::exception_detail::throw_exception_<boost_1_68_0::property_tree::ptree_bad_data> (x=..., current_function=0x2aaab9b45fc0 <boost_1_68_0::enable_if<boost_1_68_0::property_tree::detail::is_translator<boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int> >, unsigned int>::type boost_1_68_0::property_tree::basic_ptree<std::string, std::string, std::less<std::string> >::get_value<unsigned int, boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int> >(boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int>) const::__PRETTY_FUNCTION__> "typename boost_1_68_0::enable_if<boost_1_68_0::property_tree::detail::is_translator<Translator>, Type>::type boost_1_68_0::property_tree::basic_ptree<Key, Data, KeyCompare>::get_value(T"..., file=0x2aaab9b45830 "property_tree/detail/ptree_implementation.hpp", line=675) at throw_exception.hpp:89
#19 0x00002aaab99be01e in boost_1_68_0::property_tree::basic_ptree<std::string, std::string, std::less<std::string> >::get_value<unsigned int, boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int> > (this=0xbc86c8, tr=...) at property_tree/detail/ptree_implementation.hpp:673
#20 0x00002aaab99bd6a5 in boost_1_68_0::property_tree::basic_ptree<std::string, std::string, std::less<std::string> >::get_value<unsigned int> (this=0xbc86c8) at property_tree/detail/ptree_implementation.hpp:683
#21 0x00002aaab99bc545 in boost_1_68_0::property_tree::basic_ptree<std::string, std::string, std::less<std::string> >::get<unsigned int> (this=0x7fffffff9470, path=...) at property_tree/detail/ptree_implementation.hpp:754
#22 0x00002aaab99bba83 in MyRT::DUTConfigFile::readIniFile (this=0xbc5d50, iniFilePath=...) at DUTConfigFile.cpp:231
#23 0x00002aaab99ba8d2 in MyRT::DUTConfigFile::DUTConfigFile (this=0xbc5d50, iniFilePath=..., configFilePath=...) at DUTConfigFile.cpp:26
#24 0x00002aaab99c0839 in setupMyConfigs () at SimXLInterface.cpp:83
#31 0x0000000000408847 in main ()
</code>```

I tried gdb and it is throwing an exception when converting string to uint using istringstream. Below are the two types of the transition

```<code>template<class K, class D, class C>
template<class Type> inline
Type basic_ptree<K, D, C>::get_value() const
{
    return get_value<Type>(
        typename translator_between<data_type, Type>::type());
}

(gdb) p typeid(Type).name()
$2 = 0x2aaab5c33c91 <typeinfo name for unsigned int> "j"
(gdb) p typeid(data_type).name()
could not find typeinfo symbol for 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >'
</code>```

Below function in basic_ios.h throws a __throw_bad_cast() exception (here this->_M_num_get = NULL)

```<code>const __num_get_type& __ng = __check_facet(this->_M_num_get);
</code>```

Internal build automation Makefile is addding -D_GLIBCXX_USE_CXX11_ABI=0 to object file creation by default

```<code>g++ -I/usr/myboost/boost/boost -Wall -std=c++14 -fopenmp -m64 -msse2 -fPIC \
  -D_GLIBCXX_USE_CXX11_ABI=0 -g -o *.o -fPIC -c *.cpp
</code>```

.so building command

```<code>g++ -m64 -msse2 -pthread -shared -static-libstdc++ -static-libgcc  \
  -Wl,-znoexecstack -g -o runtime.so *.o -ldl -lrt -lz -fopenmp -lcrypto
</code>```

If I change it to read a std::string type and later convert it to uint, it is working without an exception

```<code>std::string strHwCount = pt.get<std::string>("SYSTEM.num_of_vps");
hwCount = static_cast<uint>(std::stoul(strHwCount));
</code>```

I am using boost-1.68 and gcc-7.3. Dose this have to do with the ABI macro that I'm using? Is there a way to resolve this without above workaround

UPDATE

First of all I am migrating project from cmake to a internal custom build automation (some enhanced version of Makefile). In cmake this worked fine. Based on sehe's answer I did some further analysis.
In a small standalone example this error is not reproducible (using both local string and actual .ini file read).

When going through gdb, In file boost/property_tree/stream_translator.hpp, I could find the read value from the file (changed to num_of_vps = 4 in file) in the both string and istringstream.

```<code>optional<Type> basic_ptree<K, D, C>
    ::get_value_optional(Translator tr) const
{
    return tr.get_value(data());
}

(gdb) p data()
$1 = "4"

boost_1_68_0::optional<E> get_value(const internal_type &v) {
    std::basic_istringstream<Ch, Traits, Alloc> iss(v);
    iss.imbue(m_loc);
    E e;
    customized::extract(iss, e);
    ....
}

(gdb) p v
$1 = "4"
(gdb) p iss.str()
$2 = "4"
</code>```

Inside above customized::extract(iss, e) function there is a string to unsigned int conversion using a basic_istream

```<code>static void extract(std::basic_istream<Ch, Traits>& s, E& e) {
    s >> e;
    if(!s.eof()) { s >> std::ws; }
}
</code>```

Inside this >> operator there is a _M_extract function and inside that __check_facet function throws the exception (by cheking NULL of this->_M_num_get )

```<code>basic_istream<_CharT, _Traits>::
_M_extract(_ValueT& __v) {
  __try {
    const __num_get_type& __ng = __check_facet(this->_M_num_get);
    ...

inline const _Facet&
__check_facet(const _Facet* __f) {
  if (!__f)
    __throw_bad_cast();
  return *__f;
}
</code>```

stack trace above scenario

```<code>#0  std::istream::_M_extract<unsigned int>(unsigned int&) (__f=0x0) at gcc-7.3.0/objdir/x86_64-centos-linux/libstdc++-v3/include/bits/basic_ios.h:49
#1  std::istream::operator>>(unsigned int&) (this=0x7fffffff9980, __n=@0x7fffffff997c: 0)
#2  boost_1_68_0::property_tree::customize_stream::extract(std::istream&, unsigned int&) (s=..., e=@0x7fffffff997c: 0)
#3  boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int>::get_value(std::string const&) (this=0x7fffffff9b58, v="4")
</code>```

I could see the same behavior in the another place that we are using std::stringstream . Variable ss shows empty even with << operator adding strings

```<code>std::stringstream ss;
ss << std::setw(8) << std::setfill('0') << std::hex << firmId;
</code>```

I had a concern about that the ABI flag causing this, but I was able to remove it and the issue is still there. I searched about this kind of istream issues but couldn't find anything useful.

答:
Your input is corrupt. Likely it's using an encoding or code-points that you didn't expect, but don't stand out for a human reader.

Live On Coliru

```<code>#include <boost/property_tree/ini_parser.hpp>
#include <iostream>

int main() {
    std::istringstream iss(R"([SYSTEM]
num_of_vps = 1)");
    boost::property_tree::ptree pt;
    read_ini(iss, pt);

    uint hwCount = pt.get<uint>("SYSTEM.num_of_vps");

    std::cout << "hwCount: " << hwCount << "\n";
}
</code>```

Prints

```<code>hwCount: 1
</code>```

However, if you change the input to be e.g.

```<code>    std::istringstream iss(R"([SYSTEM]
num_of_vps = 1)");
</code>```

(Note that the space after = is now < > 160, \240, U+00A0 NO-BREAK SPACE, ^KNS,  ) it prints:

Live On Coliru

Prints

```<code>terminate called after throwing an instance of 'boost::wrapexcept<boost::property_tree::ptree_bad_data>'
  what():  conversion of data to type "j" failed
</code>```

Body:
I have a .ini file contains below data

[SYSTEM]
num_of_vps = 1

And I have this code to read an element in .ini file. (uint defined as typedef unsigned int uint)

boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini(iniFilePath, pt);
hwCount = pt.get<uint>("SYSTEM.num_of_vps");

I created a from files including above code and called it in a wrapper function in main.cc file. Then I am getting below error

terminate called after throwing an instance of 'boost_1_68_0::exception_detail::clone_impl<boost_1_68_0::exception_detail::error_info_injector<boost_1_68_0::property_tree::ptree_bad_data> >'
what():  conversion of data to type "j" failed
stack trace

#12 0x00002aaab613fcd5 in abort () from /lib64/libc.so.6
#13 0x00002aaab9b29315 in __gnu_cxx::__verbose_terminate_handler () at ../../../../src/gcc-7.3.0/libstdc++-v3/libsupc++/vterminate.cc:95
#14 0x00002aaab9a9e8f6 in __cxxabiv1::__terminate (handler=<optimized out>) at ../../../../src/gcc-7.3.0/libstdc++-v3/libsupc++/eh_terminate.cc:47
#15 0x00002aaab9a9e941 in std::terminate () at ../../../../src/gcc-7.3.0/libstdc++-v3/libsupc++/eh_terminate.cc:57
#16 0x00002aaab9a9ea74 in __cxxabiv1::__cxa_throw (obj=<optimized out>, tinfo=0x2aaab9e1ff60 <typeinfo for boost_1_68_0::exception_detail::clone_impl<boost_1_68_0::exception_detail::error_info_injector<boost_1_68_0::property_tree::ptree_bad_data> >>, dest=0x2aaab99bef18 <boost_1_68_0::exception_detail::clone_impl<boost_1_68_0::exception_detail::error_info_injector<boost_1_68_0::property_tree::ptree_bad_data> >::~clone_impl()>) at ../../../../src/gcc-7.3.0/libstdc++-v3/libsupc++/eh_throw.cc:93
#17 0x00002aaab99bec82 in boost_1_68_0::throw_exception<boost_1_68_0::exception_detail::error_info_injector<boost_1_68_0::property_tree::ptree_bad_data> > (e=...) at throw_exception.hpp:72
#18 0x00002aaab99be576 in boost_1_68_0::exception_detail::throw_exception_<boost_1_68_0::property_tree::ptree_bad_data> (x=..., current_function=0x2aaab9b45fc0 <boost_1_68_0::enable_if<boost_1_68_0::property_tree::detail::is_translator<boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int> >, unsigned int>::type boost_1_68_0::property_tree::basic_ptree<std::string, std::string, std::less<std::string> >::get_value<unsigned int, boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int> >(boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int>) const::__PRETTY_FUNCTION__> "typename boost_1_68_0::enable_if<boost_1_68_0::property_tree::detail::is_translator<Translator>, Type>::type boost_1_68_0::property_tree::basic_ptree<Key, Data, KeyCompare>::get_value(T"..., file=0x2aaab9b45830 "property_tree/detail/ptree_implementation.hpp", line=675) at throw_exception.hpp:89
#19 0x00002aaab99be01e in boost_1_68_0::property_tree::basic_ptree<std::string, std::string, std::less<std::string> >::get_value<unsigned int, boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int> > (this=0xbc86c8, tr=...) at property_tree/detail/ptree_implementation.hpp:673
#20 0x00002aaab99bd6a5 in boost_1_68_0::property_tree::basic_ptree<std::string, std::string, std::less<std::string> >::get_value<unsigned int> (this=0xbc86c8) at property_tree/detail/ptree_implementation.hpp:683
#21 0x00002aaab99bc545 in boost_1_68_0::property_tree::basic_ptree<std::string, std::string, std::less<std::string> >::get<unsigned int> (this=0x7fffffff9470, path=...) at property_tree/detail/ptree_implementation.hpp:754
#22 0x00002aaab99bba83 in MyRT::DUTConfigFile::readIniFile (this=0xbc5d50, iniFilePath=...) at DUTConfigFile.cpp:231
#23 0x00002aaab99ba8d2 in MyRT::DUTConfigFile::DUTConfigFile (this=0xbc5d50, iniFilePath=..., configFilePath=...) at DUTConfigFile.cpp:26
#24 0x00002aaab99c0839 in setupMyConfigs () at SimXLInterface.cpp:83
#31 0x0000000000408847 in main ()

I tried gdb and it is throwing an exception when converting string to uint using istringstream. Below are the two types of the transition

template<class K, class D, class C>
template<class Type> inline
Type basic_ptree<K, D, C>::get_value() const
{
    return get_value<Type>(
        typename translator_between<data_type, Type>::type());
}

(gdb) p typeid(Type).name()
$2 = 0x2aaab5c33c91 <typeinfo name for unsigned int> "j"
(gdb) p typeid(data_type).name()
could not find typeinfo symbol for 'std::basic_string<char, std::char_traits<char>, std::allocator<char> >'

Below function in basic_ios.h throws a __throw_bad_cast() exception (here this->_M_num_get = NULL)

const __num_get_type& __ng = __check_facet(this->_M_num_get);

Internal build automation Makefile is addding -D_GLIBCXX_USE_CXX11_ABI=0 to object file creation by default

g++ -I/usr/myboost/boost/boost -Wall -std=c++14 -fopenmp -m64 -msse2 -fPIC \
  -D_GLIBCXX_USE_CXX11_ABI=0 -g -o *.o -fPIC -c *.cpp

.so building command

g++ -m64 -msse2 -pthread -shared -static-libstdc++ -static-libgcc  \
  -Wl,-znoexecstack -g -o runtime.so *.o -ldl -lrt -lz -fopenmp -lcrypto

If I change it to read a std::string type and later convert it to uint, it is working without an exception

std::string strHwCount = pt.get<std::string>("SYSTEM.num_of_vps");
hwCount = static_cast<uint>(std::stoul(strHwCount));

I am using boost-1.68 and gcc-7.3. Dose this have to do with the ABI macro that I'm using? Is there a way to resolve this without above workaround

UPDATE

First of all I am migrating project from cmake to a internal custom build automation (some enhanced version of Makefile). In cmake this worked fine. Based on sehe's answer I did some further analysis.
In a small standalone example this error is not reproducible (using both local string and actual .ini file read).

When going through gdb, In file boost/property_tree/stream_translator.hpp, I could find the read value from the file (changed to num_of_vps = 4 in file) in the both string and istringstream.

optional<Type> basic_ptree<K, D, C>
    ::get_value_optional(Translator tr) const
{
    return tr.get_value(data());
}

(gdb) p data()
$1 = "4"

boost_1_68_0::optional<E> get_value(const internal_type &v) {
    std::basic_istringstream<Ch, Traits, Alloc> iss(v);
    iss.imbue(m_loc);
    E e;
    customized::extract(iss, e);
    ....
}

(gdb) p v
$1 = "4"
(gdb) p iss.str()
$2 = "4"

Inside above customized::extract(iss, e) function there is a string to unsigned int conversion using a basic_istream

static void extract(std::basic_istream<Ch, Traits>& s, E& e) {
    s >> e;
    if(!s.eof()) { s >> std::ws; }
}

Inside this >> operator there is a _M_extract function and inside that __check_facet function throws the exception (by cheking NULL of this->_M_num_get )

basic_istream<_CharT, _Traits>::
_M_extract(_ValueT& __v) {
  __try {
    const __num_get_type& __ng = __check_facet(this->_M_num_get);
    ...

inline const _Facet&
__check_facet(const _Facet* __f) {
  if (!__f)
    __throw_bad_cast();
  return *__f;
}

stack trace above scenario

#0  std::istream::_M_extract<unsigned int>(unsigned int&) (__f=0x0) at gcc-7.3.0/objdir/x86_64-centos-linux/libstdc++-v3/include/bits/basic_ios.h:49
#1  std::istream::operator>>(unsigned int&) (this=0x7fffffff9980, __n=@0x7fffffff997c: 0)
#2  boost_1_68_0::property_tree::customize_stream::extract(std::istream&, unsigned int&) (s=..., e=@0x7fffffff997c: 0)
#3  boost_1_68_0::property_tree::stream_translator<char, std::char_traits<char>, std::allocator<char>, unsigned int>::get_value(std::string const&) (this=0x7fffffff9b58, v="4")

I could see the same behavior in the another place that we are using std::stringstream . Variable ss shows empty even with << operator adding strings

std::stringstream ss;
ss << std::setw(8) << std::setfill('0') << std::hex << firmId;

I had a concern about that the ABI flag causing this, but I was able to remove it and the issue is still there. I searched about this kind of istream issues but couldn't find anything useful.

Body:
Your input is corrupt. Likely it's using an encoding or code-points that you didn't expect, but don't stand out for a human reader.

Live On Coliru

#include <boost/property_tree/ini_parser.hpp>
#include <iostream>

int main() {
    std::istringstream iss(R"([SYSTEM]
num_of_vps = 1)");
    boost::property_tree::ptree pt;
    read_ini(iss, pt);

    uint hwCount = pt.get<uint>("SYSTEM.num_of_vps");

    std::cout << "hwCount: " << hwCount << "\n";
}

Prints

hwCount: 1

However, if you change the input to be e.g.

    std::istringstream iss(R"([SYSTEM]
num_of_vps = 1)");

(Note that the space after = is now < > 160, \240, U+00A0 NO-BREAK SPACE, ^KNS, &nbsp;) it prints:

Live On Coliru

Prints

terminate called after throwing an instance of 'boost::wrapexcept<boost::property_tree::ptree_bad_data>'
  what():  conversion of data to type "j" failed


来源: stackexchange

问:
Can we give a Sequence Id for rows in Spark?
I am new to spark and I have around 10000 rows in a datafile to read

```<code>SparkSession sessionSpark = SparkSession
            .builder()
            .config(sparkConf)
            .getOrCreate();

Dataset<Row> dataset = sessionSpark.read.parquet("s3://databucket/files/")

</code>```

I have a usecase to add a row number to every row in the dataset , the row number should start from 1 to 10000 (since the file has 10000 records ) , is it possible to assign a row number and we know spark shuffles the data but let's say even after rerunning the same file twice from the application , the row number generated should be the same , is it possible to do ?

答:
monotonically_increasing_id() would add incremental id for your rows

```<code>import org.apache.spark.sql.functions._
Dataset<Row> dataset = sessionSpark.read.parquet("s3://databucket/files/").withColumn("rowNum", monotonically_increasing_id())
</code>```

From official Spark Docs

A column expression that generates monotonically increasing 64-bit
  integers.

The generated ID is guaranteed to be monotonically increasing and
  unique, but not consecutive. The current implementation puts the
  partition ID in the upper 31 bits, and the record number within each
  partition in the lower 33 bits. The assumption is that the data frame
  has less than 1 billion partitions, and each partition has less than 8
  billion records.

As an example, consider a DataFrame with two partitions, each with 3
  records. This expression would return the following IDs:

{{{ 0, 1, 2, 8589934592 (1L << 33), 8589934593, 8589934594. }}}

ContentLicense: CC BY-SA 4.0

Body:
I am new to spark and I have around 10000 rows in a datafile to read

SparkSession sessionSpark = SparkSession
            .builder()
            .config(sparkConf)
            .getOrCreate();

Dataset<Row> dataset = sessionSpark.read.parquet("s3://databucket/files/")

I have a usecase to add a row number to every row in the dataset , the row number should start from 1 to 10000 (since the file has 10000 records ) , is it possible to assign a row number and we know spark shuffles the data but let's say even after rerunning the same file twice from the application , the row number generated should be the same , is it possible to do ?

Body:
monotonically_increasing_id() would add incremental id for your rows

import org.apache.spark.sql.functions._
Dataset<Row> dataset = sessionSpark.read.parquet("s3://databucket/files/").withColumn("rowNum", monotonically_increasing_id())

From official Spark Docs

A column expression that generates monotonically increasing 64-bit
  integers.

The generated ID is guaranteed to be monotonically increasing and
  unique, but not consecutive. The current implementation puts the
  partition ID in the upper 31 bits, and the record number within each
  partition in the lower 33 bits. The assumption is that the data frame
  has less than 1 billion partitions, and each partition has less than 8
  billion records.

As an example, consider a DataFrame with two partitions, each with 3
  records. This expression would return the following IDs:

{{{ 0, 1, 2, 8589934592 (1L << 33), 8589934593, 8589934594. }}}


问:
How much disk space does a GCP Function have?
I am looking into different FaaS providers and am interested how much disk space I have per function. A function in AWS Lambda has 512 MB of disk space available (see here) and Azure functions have up to 1000 GB of disk space, depending on the pricing model (see here).

How much does a GCP Function have?

When searching the documentation, I could only find that functions do have disk storage, but not how much (see here).

答:
A google Cloud function can have between 128 MiB and 2 GiB of memmory.

You can find here the quotas for  Cloud Functions


问:
-webkit-transform CSS property not working in IronPdf
I want to convert a html page in a ASP .NET project with IronPdf

This is the HTML that I give to IronPdf:

```<code><!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <style type="text/css">
        .meter {
            width: 100%;
            height: 100%;
        }

        .circle {
            fill: none;
            -webkit-transform-origin: 50% 50%;
            -webkit-transform: rotateZ(-90deg) rotateX(180deg);
        }

        .outline, .mask {
            stroke: #F1F1F1;
            stroke-width: 30;
        }

        .range {
            stroke-width: 30;
        }
    </style>

</head>
<body>
    <div class="container">
        <h5 id="headline">Test Render</h5>
        <svg class="meter">
            <circle class="outline-curves circle outline" cx="50%" cy="50%" r="100"></circle>
            <circle class="low circle range" cx="50%" cy="50%" stroke="#FDE47F" r="100"></circle>
            <circle class="mask circle" cx="50%" cy="50%" r="100"></circle>
            <circle class="outline-ends circle outline" cx="50%" cy="50%" r="100"></circle>
            <text class="text" x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">70%</text>
        </svg>
    </div>
</body>
</html>
<footer>
    <script lang="text/javascript">
        /* Set radius for all circles */
        var r = 100;
        var circles = document.querySelectorAll('.circle');
        var total_circles = circles.length;
        for (var i = 0; i < total_circles; i++) {
            circles[i].setAttribute('r', r);
        }

        /* Set meter's wrapper dimension */
        var meter_dimension = (r * 2) + 100;
        var meters = document.querySelectorAll(".meter");
        for (var i = 0; i < meters.length; i++) {
            meters[i].style.width = meter_dimension + "px";
            meters[i].style.height = meter_dimension + "px";
        }

        /* Add strokes to circles  */
        var cf = 2 * Math.PI * r;
        var semi_cf = cf;
        var outlineCurves = document.querySelectorAll(".outline-curves")
        var lows = document.querySelectorAll(".low")
        var outlineEnds = document.querySelectorAll(".outline-ends");
        var masks = document.querySelectorAll(".mask");

        for (var i = 0; i < outlineCurves.length; i++) {
            outlineCurves[i].setAttribute("stroke-dasharray", semi_cf + "," + cf);
        }
        for (var i = 0; i < lows.length; i++) {
            lows[i].setAttribute("stroke-dasharray", semi_cf + "," + cf);
        }
        for (var i = 0; i < outlineEnds.length; i++) {
            outlineEnds[i].setAttribute("stroke-dasharray", 2 + "," + (semi_cf - 2));
        }

        function setGaugeValue(value) {
            var percent = value;
            var meter_value = semi_cf - ((percent * semi_cf) / 100);
            for (var i = 0; i < masks.length; i++) {
                masks[i].setAttribute("stroke-dasharray", meter_value + "," + cf);
            }
        }

        setGaugeValue(70);
    </script>
</footer>
</code>```

And here are the settings used for IronPdf in C#:

```<code>var _renderer = new HtmlToPdf();
_renderer.PrintOptions.SetCustomPaperSizeInInches(8.5, 11);
_renderer.PrintOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait;
_renderer.PrintOptions.Title = "X";
_renderer.PrintOptions.EnableJavaScript = true;
_renderer.PrintOptions.RenderDelay = 5000; //ms
_renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
_renderer.PrintOptions.DPI = 300;
_renderer.PrintOptions.GrayScale = false;
_renderer.PrintOptions.FitToPaperWidth = true;
_renderer.PrintOptions.InputEncoding = Encoding.UTF8;
_renderer.PrintOptions.Zoom = 90;
_renderer.PrintOptions.ViewPortWidth = 1280;
_renderer.PrintOptions.CreatePdfFormsFromHtml = true;
_renderer.PrintOptions.MarginTop = 10; //millimeters
_renderer.PrintOptions.MarginLeft = 10; //millimeters
_renderer.PrintOptions.MarginRight = 10; //millimeters
_renderer.PrintOptions.MarginBottom = 10; //millimeters
_renderer.PrintOptions.FirstPageNumber = 1;
</code>```

According to their documentation this should work: https://ironpdf.com/docs/questions/rotating-text/

When I try the HTML in the browser it works as expected but when IronPdf converts it into a PDF everything works except the -webkit-transform CSS properties.

I don't know if I overlooked something to make it work but I'm at the end of my wisdom.

答:
I figured out what my problem was:

-webkit-transform is only working in IronPdf when used on a svg-Element and is NOT working on a circle-Element.

Body:
I want to convert a html page in a ASP .NET project with IronPdf

This is the HTML that I give to IronPdf:

<!doctype html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Test Render

        <svg class="meter">
            <circle class="outline-curves circle outline" cx="50%" cy="50%" r="100"></circle>
            <circle class="low circle range" cx="50%" cy="50%" stroke="#FDE47F" r="100"></circle>
            <circle class="mask circle" cx="50%" cy="50%" r="100"></circle>
            <circle class="outline-ends circle outline" cx="50%" cy="50%" r="100"></circle>
            <text class="text" x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">70%</text>
        </svg>

And here are the settings used for IronPdf in C#:

var _renderer = new HtmlToPdf();
_renderer.PrintOptions.SetCustomPaperSizeInInches(8.5, 11);
_renderer.PrintOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait;
_renderer.PrintOptions.Title = "X";
_renderer.PrintOptions.EnableJavaScript = true;
_renderer.PrintOptions.RenderDelay = 5000; //ms
_renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
_renderer.PrintOptions.DPI = 300;
_renderer.PrintOptions.GrayScale = false;
_renderer.PrintOptions.FitToPaperWidth = true;
_renderer.PrintOptions.InputEncoding = Encoding.UTF8;
_renderer.PrintOptions.Zoom = 90;
_renderer.PrintOptions.ViewPortWidth = 1280;
_renderer.PrintOptions.CreatePdfFormsFromHtml = true;
_renderer.PrintOptions.MarginTop = 10; //millimeters
_renderer.PrintOptions.MarginLeft = 10; //millimeters
_renderer.PrintOptions.MarginRight = 10; //millimeters
_renderer.PrintOptions.MarginBottom = 10; //millimeters
_renderer.PrintOptions.FirstPageNumber = 1;

According to their documentation this should work: https://ironpdf.com/docs/questions/rotating-text/

When I try the HTML in the browser it works as expected but when IronPdf converts it into a PDF everything works except the -webkit-transform CSS properties.

I don't know if I overlooked something to make it work but I'm at the end of my wisdom.


问:
plot bar graph with column names on x axis
Dataframe how to plot a bar graph using python with column names on x axis and the total of the first column on y axis. I have a dataframe similar to this

```<code>     Name  1990 1991 1992 1993 1994
  0   A      10    2   15   20   18
  1   B      13   14   18   11   17
  2   C      12   17    8   10   13
  3   D       9   15   16    6    9
  4   E      19   18   13   17   19
  5   Total  63   66   70   64   76
</code>```

I want to plot a bar graph with x-axis = 1990,1991,1992,1993,1994 and y-axis = Total values. Any help with python code would be much appreciated.

could anyone help me with the dynamic scatter plot using plotly express taking years 1990, 1991,1992,1993,1994 on x-axis and corresponding yearly data on y-axis. The Name column values to be taken as animation. as the play button is clicked, the data corresponding to the year and name value should move from 1990 to 1994

答:
Hope this helps!

```<code>#  sample data
df = pd.DataFrame({
    '1990': [5, 6, 7, 9, 2],
    '1992': [15, 2, 7, 5, 11],
    '1994': [2, -6, 21, 6, 2]},
    index= ['a', 'b', 'c', 'd', 'e']

)

# Transposing the dataframe before plotting
df.T.plot()
</code>```

Read more about Pandas Dataframe Plot fns, its really powerful!

```<code>df.T.plot(kind='bar')
</code>```

Body:
Dataframe how to plot a bar graph using python with column names on x axis and the total of the first column on y axis. I have a dataframe similar to this

     Name  1990 1991 1992 1993 1994
  0   A      10    2   15   20   18
  1   B      13   14   18   11   17
  2   C      12   17    8   10   13
  3   D       9   15   16    6    9
  4   E      19   18   13   17   19
  5   Total  63   66   70   64   76

I want to plot a bar graph with x-axis = 1990,1991,1992,1993,1994 and y-axis = Total values. Any help with python code would be much appreciated.

could anyone help me with the dynamic scatter plot using plotly express taking years 1990, 1991,1992,1993,1994 on x-axis and corresponding yearly data on y-axis. The Name column values to be taken as animation. as the play button is clicked, the data corresponding to the year and name value should move from 1990 to 1994

Body:
Hope this helps!

#  sample data
df = pd.DataFrame({
    '1990': [5, 6, 7, 9, 2],
    '1992': [15, 2, 7, 5, 11],
    '1994': [2, -6, 21, 6, 2]},
    index= ['a', 'b', 'c', 'd', 'e']

)

# Transposing the dataframe before plotting
df.T.plot()

Read more about Pandas Dataframe Plot fns, its really powerful!

df.T.plot(kind='bar')


问:
Dataframe Column to list conserving order in Pyspark
I have a Spark dataframe containing 2 columns, "id" and "timetamp".
How can i convert the "id" column to a list conserving the original order by timestamp?
When i try collect, the order is not conserved.

Thanks

答:
you can't use collect_list, since it is nondeterministic collecting of elements over a group, see doc -

```<code>/**
   * Aggregate function: returns a list of objects with duplicates.
   *
   * @note The function is non-deterministic because the order of collected results depends
   * on order of rows which may be non-deterministic after a shuffle.
   *
   * @group agg_funcs
   * @since 1.6.0
   */
  def collect_list(e: Column): Column = withAggregateFunction { CollectList(e.expr) }
</code>```

In distributed computing, collecting the elements over certain order is kind of impossible since the data is disributed across nodes. To achieve that you need collect the data to single partition on an executor and then perform aggregation. This may cause Resource crunch on the executor. If you know that your data is less in number you can do this using UDAF by coalescing the data to 1.

If you have repartitioning column which is not skewed then you can perform this action in performant and reliable way

Here is a good example to sort values based on timestamp by cloudera

Body:
you can't use collect_list, since it is nondeterministic collecting of elements over a group, see doc -

/**
   * Aggregate function: returns a list of objects with duplicates.
   *
   * @note The function is non-deterministic because the order of collected results depends
   * on order of rows which may be non-deterministic after a shuffle.
   *
   * @group agg_funcs
   * @since 1.6.0
   */
  def collect_list(e: Column): Column = withAggregateFunction { CollectList(e.expr) }

In distributed computing, collecting the elements over certain order is kind of impossible since the data is disributed across nodes. To achieve that you need collect the data to single partition on an executor and then perform aggregation. This may cause Resource crunch on the executor. If you know that your data is less in number you can do this using UDAF by coalescing the data to 1.

If you have repartitioning column which is not skewed then you can perform this action in performant and reliable way

Here is a good example to sort values based on timestamp by cloudera


问:
Supply a default value for an incomplete SQL join
Sorry I don't know if there's proper name for 'incomplete join' but consider this sort of query, designed to return details of every sale:

```<code>SELECT a.id, a.productId, b.productDescription FROM Sales a, AdditionalProductData b WHERE a.productId = b.productId;
</code>```

In a situation where AdditionalProductData doesn't guarantee to to have a row for every productId, but I want to return a result for every row in Sales, how can I modify my query to return either null or some default value e.g. "unknown" in such cases? I want to ensure sales of unregistered products are not omitted.

(It is a slightly contrived example, and indicates a problem in the DB, but those are outside scope of the question)

答:
Use OUTER JOIN :

```<code>SELECT a.productId, b.productName
FROM Products b LEFT JOIN
     Sales a
     ON a.productId = b.id;
</code>```

but I want to return a result for every row in Sales

Do the table swapping :

```<code>SELECT a.productId, COALESCE(b.productName, 'unknown') AS productName
FROM  Sales a LEFT JOIN
      Products b
      ON a.productId = b.id;
</code>```

Body:
Sorry I don't know if there's proper name for 'incomplete join' but consider this sort of query, designed to return details of every sale:

SELECT a.id, a.productId, b.productDescription FROM Sales a, AdditionalProductData b WHERE a.productId = b.productId;

In a situation where AdditionalProductData doesn't guarantee to to have a row for every productId, but I want to return a result for every row in Sales, how can I modify my query to return either null or some default value e.g. "unknown" in such cases? I want to ensure sales of unregistered products are not omitted.

(It is a slightly contrived example, and indicates a problem in the DB, but those are outside scope of the question)

Body:
Use OUTER JOIN :

SELECT a.productId, b.productName
FROM Products b LEFT JOIN
     Sales a
     ON a.productId = b.id;

but I want to return a result for every row in Sales

Do the table swapping :

SELECT a.productId, COALESCE(b.productName, 'unknown') AS productName
FROM  Sales a LEFT JOIN
      Products b
      ON a.productId = b.id;


问:
Ionic: Set default checked of ion-radio by variable
Current Versions: Ionic 6.7.0

Hello,
this is my first question on stackoverflow, so please be forgiving if some information are missing.

I try to include a radio-group that should be equal to a variable of my .ts-file. I pass an 'id' between two pages, so the user doesn't always have to re-select it.

Thats what I tried, but I can't get a default selected radio-button working.

home.page.html:

```<code>                        <ion-radio-group (ionChange)="carChangeEvent($event)"  [(ngModel)]="car_id">

                        <ion-item>
                            <ion-label>Button 1</ion-label>
                            <ion-radio slot="start" value="1"></ion-radio>
                        </ion-item>

                        <ion-item>
                            <ion-label>Button 2</ion-label>
                            <ion-radio slot="start" value="2"></ion-radio>
                        </ion-item>

                        <ion-item>
                            <ion-label>Button 3</ion-label>
                            <ion-radio slot="start" value="3"></ion-radio>
                        </ion-item>

                    </ion-radio-group>
</code>```

home.page.ts:

```<code>export class HomePage {

    public car_id: string = "1";
    ...

    constructor(...) {...}

    carChangeEvent (event) {
        switch(this.car_id) {
            case "1": {
                ...do stuff by car_id...
            break;
            }
            case "2": {
                ...do stuff by car_id...
            break;
            }
            case "3": {
                ...do stuff by car_id...
            break;
            }
            default: {
                this.msg2 = "switch default";
                console.log('ERROR: Invalid car identifier: ' + event.target.value);
            break;
            }
        }
    }
</code>```

Any solutions or hints?

Edit 1:
I ran it on my device as well and comparing to the ionic serve instance the default radio selection is shown correctly. However, when i changed the value on another page and return to the home.page, no radio-button is selected (but the value is correct).
When I set another value by e.g. an <ion-input [(ngModel)]="car_id">, a radio-button gets selected correctly according to the input-value.

答:
I finaly got solved it.
I defined a wrong data-type in the queryParams : 'NavigationExtras', so the switch/case was not able to enter the correct case. => Everything is fine and working correctly.

Body:
Current Versions: Ionic 6.7.0

Hello,
this is my first question on stackoverflow, so please be forgiving if some information are missing.

I try to include a radio-group that should be equal to a variable of my .ts-file. I pass an 'id' between two pages, so the user doesn't always have to re-select it.

Thats what I tried, but I can't get a default selected radio-button working.

home.page.html:

                        <ion-radio-group (ionChange)="carChangeEvent($event)"  [(ngModel)]="car_id">

                        <ion-item>
                            <ion-label>Button 1</ion-label>
                            <ion-radio slot="start" value="1"></ion-radio>
                        </ion-item>

                        <ion-item>
                            <ion-label>Button 2</ion-label>
                            <ion-radio slot="start" value="2"></ion-radio>
                        </ion-item>

                        <ion-item>
                            <ion-label>Button 3</ion-label>
                            <ion-radio slot="start" value="3"></ion-radio>
                        </ion-item>

                    </ion-radio-group>

home.page.ts:

export class HomePage {

    public car_id: string = "1";
    ...

    constructor(...) {...}

    carChangeEvent (event) {
        switch(this.car_id) {
            case "1": {
                ...do stuff by car_id...
            break;
            }
            case "2": {
                ...do stuff by car_id...
            break;
            }
            case "3": {
                ...do stuff by car_id...
            break;
            }
            default: {
                this.msg2 = "switch default";
                console.log('ERROR: Invalid car identifier: ' + event.target.value);
            break;
            }
        }
    }

Any solutions or hints?

Edit 1:
I ran it on my device as well and comparing to the ionic serve instance the default radio selection is shown correctly. However, when i changed the value on another page and return to the home.page, no radio-button is selected (but the value is correct).
When I set another value by e.g. an <ion-input [(ngModel)]="car_id">, a radio-button gets selected correctly according to the input-value.


问:
how to unwrap swift optionals within a struct
I'm learning swift and found an example that contains an optional property within a struct. When I try to set a value to the optional I find that it is nil.

```<code>struct Price{
    var USD: Double = 0.0
    var CAD: Double = 0.0
}
struct Item{
    var name: String = "not defined"
    var price: Price?
}

var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price?.USD = 19.2

print("purchase name is \(purchase.name), purchase price is \(purchase.price?.USD)")
</code>```

yields

```<code>purchase name is lampshade, purchase price is nil
</code>```

if I try (purchase.price.USD) I get an error "Value of optional type 'Price?' must be unwrapped to refer to member 'USD' of wrapped base type 'Price'

How can I unwrap price in order to set a value of USD?

答:
You cannot directly set a property of an Optional if you haven't assigned a value to the Optional itself, since due to the optional chaining, the setter of usd won't be called.

Instead, you need to assign a Price to purchase.price.

```<code>var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price = Price(USD: 19.2)
</code>```

Or if you want to assign an "empty" price, then optional chaining on that works, since now price is not nil.

```<code>var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price = Price()
purchase.price?.USD = 19.2
</code>```

Also, you should try to make properties immutable immutable (let) by default and only make properties mutable (var) if they really need to change after initialisation. You should also only add default values to properties where it makes sense for them to have a default value. For instance, name shouldn't have one, but rather, should be immutable with its value being set in the init.

```<code>struct Item{
    let name: String
    var price: Price?
}

var purchase = Item(name: "lampshade")
purchase.price = Price(USD: 19.2)
</code>```

Body:
I'm learning swift and found an example that contains an optional property within a struct. When I try to set a value to the optional I find that it is nil.

struct Price{
    var USD: Double = 0.0
    var CAD: Double = 0.0
}
struct Item{
    var name: String = "not defined"
    var price: Price?
}

var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price?.USD = 19.2

print("purchase name is \(purchase.name), purchase price is \(purchase.price?.USD)")

yields

purchase name is lampshade, purchase price is nil

if I try (purchase.price.USD) I get an error "Value of optional type 'Price?' must be unwrapped to refer to member 'USD' of wrapped base type 'Price'

How can I unwrap price in order to set a value of USD?

Body:
You cannot directly set a property of an Optional if you haven't assigned a value to the Optional itself, since due to the optional chaining, the setter of usd won't be called.

Instead, you need to assign a Price to purchase.price.

var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price = Price(USD: 19.2)

Or if you want to assign an "empty" price, then optional chaining on that works, since now price is not nil.

var purchase:Item = Item()
purchase.name = "lampshade"
purchase.price = Price()
purchase.price?.USD = 19.2

Also, you should try to make properties immutable immutable (let) by default and only make properties mutable (var) if they really need to change after initialisation. You should also only add default values to properties where it makes sense for them to have a default value. For instance, name shouldn't have one, but rather, should be immutable with its value being set in the init.

struct Item{
    let name: String
    var price: Price?
}

var purchase = Item(name: "lampshade")
purchase.price = Price(USD: 19.2)


问:
Function is not visible inside Function Apps in the Azure portal
I have created a FunctionApp in Azure Portal (Canada central region) and deployed my function from Visual Studio 2019. It published without any error. However, I am not able to see my function inside my FunctionApp in the Azure portal. My Runtime version is ~1 and my code .NET framework is 4.7.2.
When I change my Runtime version to ~2 or ~3, I am able to see my function inside FunctionApp. I have noticed this issue lately. I have deployed my FunctionApp last month and it was working as expected. I have noticed the above-mentioned issue from last week.
As part of the investigation, I have deployed my code in the Central US region it is working as expected, but when I deploy the same code in Canada central region, I am not able to see my function under my FunctionApp.
Does anyone face this issue in any other Azure region? Is it specific to Canada central region?
Thank you!</p>

答:
Please check again whether the deployment can be successful. Now there is no problem with me in Canada Central.

You can't see the function problem on the portal should be related to the recent update to the function portal, and the problem should have be fixed now.


问:
Rails: accept first search result
I'm using MetaSearch in a Rails 3 project although I imagine the search method doesn't really matter that much.

My controller looks like this:

```<code>  def index
    @search = Household.search(params[:search])
    @households = @search.all
  end
</code>```

If there is only a single search result, I want to go directly to the "show" action for that item, otherwise go to the "index" action. (Right now everything goes to the "index" action, which adds another step for the user).

Any ideas how to accomplish this?

答:
Try something like:</p>

```<code>def index
  @search = Household.search(params[:search])
  @households = @search.all
  if @households.size == 1
    redirect_to @households.first
  end
end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rails: accept first search result

Body:
I'm using MetaSearch in a Rails 3 project although I imagine the search method doesn't really matter that much.

My controller looks like this:

  def index
    @search = Household.search(params[:search])
    @households = @search.all
  end

If there is only a single search result, I want to go directly to the "show" action for that item, otherwise go to the "index" action. (Right now everything goes to the "index" action, which adds another step for the user).

Any ideas how to accomplish this?

Body:
Try something like:

def index
  @search = Household.search(params[:search])
  @households = @search.all
  if @households.size == 1
    redirect_to @households.first
  end
end


问:
How to unit test a Spring Boot MongoRepository?
In my Spring Boot web application I use MongoDB to store data. In the application I access the database using interfaces that extend MongoRepository.

How do I set up a unit test for such a repository class? What I would like is to

start an embedded/in memory instance of MongoDB

insert testdata from JSON or XML

use an autowired repository to perform queries on the testdata

I have tried using Embedded MongoDB, but I can't figure out how to insert testdata from a file.
I've also tried using NoSQLUnit, but the SpringApplicationConfiguration conflicts with the unit test configuration, resulting in different databases for reading and writing.

答:
First, make sure that you have added the following Spring Boot parent to your project:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
</code>```

Since we added Spring Boot parent, we can add required dependencies without specifying their versions:

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</code>```

spring-boot-starter-data-mongodb will enable Spring support for
  MongoDB

```<code><dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <scope>test</scope>
</dependency>
</code>```

de.flapdoodle.embed.mongo provides embedded MongoDB for integration
  tests

After adding de.flapdoodle.embed.mongo dependency Spring Boot will automatically try to download and start the embedded MongoDB when running tests. The following snippet shows how you can configure the embedded MongoDB instance manually

```<code>class EmbeddedMongoDbIntegrationTest {
    private MongodExecutable mongodExecutable;
    private MongoTemplate mongoTemplate;

    @After
    void clean() {
        mongodExecutable.stop();
    }

    @Before
    void setup() throws Exception {
        String ip = "localhost";
        int port = 27017;

        IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION)
            .net(new Net(ip, port, Network.localhostIsIPv6()))
            .build();

        MongodStarter starter = MongodStarter.getDefaultInstance();
        mongodExecutable = starter.prepare(mongodConfig);
        mongodExecutable.start();
        mongoTemplate = new MongoTemplate(new MongoClient(ip, port), "test");
    }

    @Test
    void test() throws Exception {
        // given
        DBObject objectToSave = BasicDBObjectBuilder.start()
            .add("key", "value")
            .get();

        // when
        mongoTemplate.save(objectToSave, "collection");

        // then
        assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key")
            .containsOnly("value");
    }
}
</code>```

Note, that we can quickly create MongoTemplate bean configured to use
  our manually configured embedded database and register it inside the
  Spring container, so your mongo repository will start leveraging this
  mongoTemplate as well.

Body:
First, make sure that you have added the following Spring Boot parent to your project:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

Since we added Spring Boot parent, we can add required dependencies without specifying their versions:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

spring-boot-starter-data-mongodb will enable Spring support for
  MongoDB

<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <scope>test</scope>
</dependency>

de.flapdoodle.embed.mongo provides embedded MongoDB for integration
  tests

After adding de.flapdoodle.embed.mongo dependency Spring Boot will automatically try to download and start the embedded MongoDB when running tests. The following snippet shows how you can configure the embedded MongoDB instance manually

class EmbeddedMongoDbIntegrationTest {
    private MongodExecutable mongodExecutable;
    private MongoTemplate mongoTemplate;

    @After
    void clean() {
        mongodExecutable.stop();
    }

    @Before
    void setup() throws Exception {
        String ip = "localhost";
        int port = 27017;

        IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION)
            .net(new Net(ip, port, Network.localhostIsIPv6()))
            .build();

        MongodStarter starter = MongodStarter.getDefaultInstance();
        mongodExecutable = starter.prepare(mongodConfig);
        mongodExecutable.start();
        mongoTemplate = new MongoTemplate(new MongoClient(ip, port), "test");
    }

    @Test
    void test() throws Exception {
        // given
        DBObject objectToSave = BasicDBObjectBuilder.start()
            .add("key", "value")
            .get();

        // when
        mongoTemplate.save(objectToSave, "collection");

        // then
        assertThat(mongoTemplate.findAll(DBObject.class, "collection")).extracting("key")
            .containsOnly("value");
    }
}

Note, that we can quickly create MongoTemplate bean configured to use
  our manually configured embedded database and register it inside the
  Spring container, so your mongo repository will start leveraging this
  mongoTemplate as well.


答:
Never use commas in the FROM clause.  Always use proper, explicit, standard, readable JOIN syntax.

You want a left join:

```<code>SELECT p.id, p.productName
FROM Products p LEFT JOIN
     Sales s
     ON s.productId = p.id;
</code>```

I am guessing you really want at least one row per product.  It doesn't make sense that you would have sales for non-existent products -- at least in most databases.

The above doesn't make sense -- only selecting from one table.  You probably want something like this:

```<code>SELECT p.id, p.productName, SUM(s.amount)
FROM Products p LEFT JOIN
     Sales s
     ON s.productId = p.id
GROUP BY p.id, p.productName;
</code>```

EDIT:

If you really do want one row per sales, then you still want a LEFT JOIN just in the other order:

```<code>SELECT s.*, p.productName
FROM Sales s LEFT JOIN
     Products p L
     ON s.productId = p.id;
</code>```

Title: Supply a default value for an incomplete SQL join

Body:
Never use commas in the FROM clause.  Always use proper, explicit, standard, readable JOIN syntax.

You want a left join:

SELECT p.id, p.productName
FROM Products p LEFT JOIN
     Sales s
     ON s.productId = p.id;

I am guessing you really want at least one row per product.  It doesn't make sense that you would have sales for non-existent products -- at least in most databases.

The above doesn't make sense -- only selecting from one table.  You probably want something like this:

SELECT p.id, p.productName, SUM(s.amount)
FROM Products p LEFT JOIN
     Sales s
     ON s.productId = p.id
GROUP BY p.id, p.productName;

EDIT:

If you really do want one row per sales, then you still want a LEFT JOIN just in the other order:

SELECT s.*, p.productName
FROM Sales s LEFT JOIN
     Products p L
     ON s.productId = p.id;


问:
PHP is not storing $_SESSION array values
I'm new in php and right now I'm having a problem when storing data in the $_SESSION array. I have an index page that retrieves information from an XML file and displays each product from the XML file in the page each one  with a button to add to a cart. When the button is pressed, I send an XMLHttpRequest with the id of the product I want to add to the $_SESSION array.

This is the main page:

```<code>function check_avi(id){
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var available = this.responseText;
      if (available == "True") {
      alert("Add to the cart successfully.");
    } else {
      alert("Sorry, the car is not available now. Please try other cars.");
    }
  }
};
xhttp.open("GET", "add_delete_session.php?action=add&id="+id, true);
xhttp.send();
</code>```

In the php I open the xml, retrieve the info and store it into an array, I then copy the information to the $_SESSION[#number of product]

What is happening is that after I add a product, it deletes in the session array the previous products, so each time I'm only having one product in the array and I want to store all of them to show them later in a shopping cart. The php should return a variable to the main page indicating the availability of the product but I'll do that later.

$arra is the array in where I'm storing the values obtained from the XML file corresponding to the product of the Id sent from the main page, like the price or name. $rf is the variable which count the amount of products stored and serve the same function as $_SESSION['g']

This is my PHP:

```<code><?php
session_start();
$id = $_GET[id];
$action = $_GET[action];
if (empty($_SESSION['g'])) {
  $_SESSION['g'] = 0;
}
switch($action){
  case "add" :
    $xmlDoc = new DOMDocument();
    $xmlDoc = simplexml_load_file("cars.xml");
    for ($e = 0; $e < 10; $e++) {
      $cont = 0;
      unset($arra);
      foreach ($xmlDoc->carrito[$e]->children() as $child) {
        $arra[$cont] = $child;
        $cont = $cont + 1;
      }
      if ($arra[0] == $id) {
        for ($f = 0; $f < 10; $f++) {
          $rf = $_SESSION['g'];
          $_SESSION[$rf][$f] = $arra[$f];
        }
        $_SESSION['g'] = $_SESSION['g'] + 1;
      }
    }
    break;
  case "delete":
    break;
}
</code>```

If anyone could help me I'll be so grateful.
Thanks

答:
I think your in your code

1:

```<code>if (empty($_SESSION['g'])) {
  $_SESSION['g'] = 0;
}
</code>```

Actually here you haven't even defined the session at all and you are checking for its value if empty or not that's gonna stop execution of your code there itself, first you need to define the session variable and the check the value for it.

2:

```<code>$rf = $_SESSION['g'];
$_SESSION[$rf][$f] = $arra[$f];
</code>```

Because it means that

```<code>$_SESSION[$_SESSION['g']][$f] =  $arra[$f];
</code>```

Which is a wrong approach.
Better way first you make all the simplifications and then assign it to the $_SESSION[] and echo it.

Body:
I'm new in php and right now I'm having a problem when storing data in the $_SESSION array. I have an index page that retrieves information from an XML file and displays each product from the XML file in the page each one  with a button to add to a cart. When the button is pressed, I send an XMLHttpRequest with the id of the product I want to add to the $_SESSION array.

This is the main page:

function check_avi(id){
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var available = this.responseText;
      if (available == "True") {
      alert("Add to the cart successfully.");
    } else {
      alert("Sorry, the car is not available now. Please try other cars.");
    }
  }
};
xhttp.open("GET", "add_delete_session.php?action=add&id="+id, true);
xhttp.send();

In the php I open the xml, retrieve the info and store it into an array, I then copy the information to the $_SESSION[#number of product]

What is happening is that after I add a product, it deletes in the session array the previous products, so each time I'm only having one product in the array and I want to store all of them to show them later in a shopping cart. The php should return a variable to the main page indicating the availability of the product but I'll do that later.

$arra is the array in where I'm storing the values obtained from the XML file corresponding to the product of the Id sent from the main page, like the price or name. $rf is the variable which count the amount of products stored and serve the same function as $_SESSION['g']

This is my PHP:

<?php
session_start();
$id = $_GET[id];
$action = $_GET[action];
if (empty($_SESSION['g'])) {
  $_SESSION['g'] = 0;
}
switch($action){
  case "add" :
    $xmlDoc = new DOMDocument();
    $xmlDoc = simplexml_load_file("cars.xml");
    for ($e = 0; $e < 10; $e++) {
      $cont = 0;
      unset($arra);
      foreach ($xmlDoc->carrito[$e]->children() as $child) {
        $arra[$cont] = $child;
        $cont = $cont + 1;
      }
      if ($arra[0] == $id) {
        for ($f = 0; $f < 10; $f++) {
          $rf = $_SESSION['g'];
          $_SESSION[$rf][$f] = $arra[$f];
        }
        $_SESSION['g'] = $_SESSION['g'] + 1;
      }
    }
    break;
  case "delete":
    break;
}

If anyone could help me I'll be so grateful.
Thanks

Body:
I think your in your code

1:

if (empty($_SESSION['g'])) {
  $_SESSION['g'] = 0;
}

Actually here you haven't even defined the session at all and you are checking for its value if empty or not that's gonna stop execution of your code there itself, first you need to define the session variable and the check the value for it.

2:

$rf = $_SESSION['g'];
$_SESSION[$rf][$f] = $arra[$f];

Because it means that

$_SESSION[$_SESSION['g']][$f] =  $arra[$f];

Which is a wrong approach.
Better way first you make all the simplifications and then assign it to the $_SESSION[] and echo it.


问:
how to set value by id in react-select
I use react-select.I have a number of react-select that change the values inside the state by handleChange.And finally they are stored somewhere(To simplify, I wrote a react-select).
So far no problem.

```<code>export const regionOptions = [
  { id: "1", value: "region 1", label: "region 1" },
  { id: "2", value: "region 2", label: "region 2" },
  { id: "3", value: "region 3", label: "region 3" },
  { id: "4", value: "region 4", label: "region 4" },
  { id: "5", value: "region 5", label: "region 5" },
  { id: "6", value: "region 6", label: "region 6" },
  { id: "7", value: "region 7", label: "region 7" },
  { id: "8", value: "region 8", label: "region 8" }
];
</code>```

To edit the form, I want to set the react-select, but by ID.for example if State.region = 2 react-select Result = region2.
tip:handleChange should not be changed.
Here you can see my codeSandbox

答:
You can try this example:</p>

```<code>import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

import Select from "react-select";

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedOption: ''
    };
  }

  options = [
    { id: "1", value: "Spring", label: "Spring" },
    { id: "2", value: "Summer", label: "Summer" },
    { id: "3", value: "Autumn", label: "Autumn" },
    { id: "4", value: "Winter", label: "Winter" }
  ];

  handleChange = selectedOption => {
    this.setState({ selectedOption });
  };

  render() {
    return (
      <div>
        <Select
          value={this.state.selectedOption}
          onChange={this.handleChange}
          options={this.options}
        />
        <button
          onClick={() => {
            let summer = this.options.find(o => o.id === "2");
            this.setState({ selectedOption: summer });
          }}
        >
          Set Summer
        </button>
      </div>
    );
  }
}

ReactDOM.render(<MyComponent />, document.getElementById("app"));
</code>```

Title: how to set value by id in react-select

Body:
I use react-select.I have a number of react-select that change the values inside the state by handleChange.And finally they are stored somewhere(To simplify, I wrote a react-select).
So far no problem.

export const regionOptions = [
  { id: "1", value: "region 1", label: "region 1" },
  { id: "2", value: "region 2", label: "region 2" },
  { id: "3", value: "region 3", label: "region 3" },
  { id: "4", value: "region 4", label: "region 4" },
  { id: "5", value: "region 5", label: "region 5" },
  { id: "6", value: "region 6", label: "region 6" },
  { id: "7", value: "region 7", label: "region 7" },
  { id: "8", value: "region 8", label: "region 8" }
];

To edit the form, I want to set the react-select, but by ID.for example if State.region = 2 react-select Result = region2.
tip:handleChange should not be changed.
Here you can see my codeSandbox

Body:
You can try this example:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

import Select from "react-select";

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedOption: ''
    };
  }

  options = [
    { id: "1", value: "Spring", label: "Spring" },
    { id: "2", value: "Summer", label: "Summer" },
    { id: "3", value: "Autumn", label: "Autumn" },
    { id: "4", value: "Winter", label: "Winter" }
  ];

  handleChange = selectedOption => {
    this.setState({ selectedOption });
  };

  render() {
    return (
      <div>
        <Select
          value={this.state.selectedOption}
          onChange={this.handleChange}
          options={this.options}
        />
        <button
          onClick={() => {
            let summer = this.options.find(o => o.id === "2");
            this.setState({ selectedOption: summer });
          }}
        >
          Set Summer
        </button>
      </div>
    );
  }
}

ReactDOM.render(<MyComponent />, document.getElementById("app"));


问:
compress the size of electron application
I have developed angular-electron app.Its a simple app but its size is 159Mb.I have used electron builder for building the electron app and included auto-update package.when I unpacked asar file,it had node modules .when I specified not to include node modules in package.json ,the size of the app reduced to 89mb but the application was not running  .
this is my package.json

```<code>{
  "name": "example",
  "version": "0.1.2",
  "main": "main.js",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "dist": "electron-builder",
    "electron": "ng build --base-href ./ && electron .",
    "build:electron": "electron-builder build --mac --win --publish never",
    "deploy": " electron-builder build  --publish always"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~7.0.0",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "~7.0.0",
    "@angular/compiler": "~7.0.0",
    "@angular/core": "~7.0.0",
    "@angular/forms": "~7.0.0",
    "@angular/http": "~7.0.0",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "~7.0.0",
    "@angular/platform-browser-dynamic": "~7.0.0",
    "@angular/router": "~7.0.0",
    "core-js": "^2.5.4",
    "electron-updater": "^4.2.0",
    "ngx-electron": "^2.2.0",
    "rxjs": "~6.3.3",
    "v8-compile-cache": "^2.1.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.10.0",
    "@angular/cli": "~7.0.7",
    "@angular/compiler-cli": "~7.0.0",
    "@angular/language-service": "~7.0.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "electron": "^7.1.2",
    "electron-builder": "^21.2.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "rimraf": "^3.0.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.1.6"
  },
  "build": {
    "appId": "com.electron.example",
    "compression": "normal",
    "extends": null,
    "files": [
      "*.js",
      "build",
      "dist",
      "renderer",
      "!node_modules"
    ],
    "mac": {
      "target": "zip"
    },
    "linux": {
      "target": [
        "AppImage",
        "zip"
      ]
    },
    "win": {
      "target": [
        "NSIS",
        "zip"
      ]
    },
    "publish": {
      "provider": "github",
      "repo": "Example",
      "owner": "y***y",
      "token": "1234567"
    }
  },
  "repository": {
    "type": "git",
    "url": "**********"
  }
}
</code>```

is there any other way to reduce the file size of electron app

答:
You can change compression level from "normal" to "maximum" in package.json:

```<code>"build": {
    "appId": "com.electron.example",
    "compression": "maximum",
    // other build settings
}
</code>```

This should usually save you much in term of app size depending on your previous compression settings and also on how much static files and added features, codes and/or dependencies you have in your build.

UPDATE

Anyway, If your app is relatively close to ~80Mb you won't save a lot, because that's generally the size of electron's build (containing node, chromium and API..).

Check electron-builder docs for more info.

Body:
I have developed angular-electron app.Its a simple app but its size is 159Mb.I have used electron builder for building the electron app and included auto-update package.when I unpacked asar file,it had node modules .when I specified not to include node modules in package.json ,the size of the app reduced to 89mb but the application was not running  .
this is my package.json

{
  "name": "example",
  "version": "0.1.2",
  "main": "main.js",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "dist": "electron-builder",
    "electron": "ng build --base-href ./ && electron .",
    "build:electron": "electron-builder build --mac --win --publish never",
    "deploy": " electron-builder build  --publish always"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~7.0.0",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "~7.0.0",
    "@angular/compiler": "~7.0.0",
    "@angular/core": "~7.0.0",
    "@angular/forms": "~7.0.0",
    "@angular/http": "~7.0.0",
    "@angular/material": "^7.3.7",
    "@angular/platform-browser": "~7.0.0",
    "@angular/platform-browser-dynamic": "~7.0.0",
    "@angular/router": "~7.0.0",
    "core-js": "^2.5.4",
    "electron-updater": "^4.2.0",
    "ngx-electron": "^2.2.0",
    "rxjs": "~6.3.3",
    "v8-compile-cache": "^2.1.0",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.10.0",
    "@angular/cli": "~7.0.7",
    "@angular/compiler-cli": "~7.0.0",
    "@angular/language-service": "~7.0.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "electron": "^7.1.2",
    "electron-builder": "^21.2.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "rimraf": "^3.0.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.1.6"
  },
  "build": {
    "appId": "com.electron.example",
    "compression": "normal",
    "extends": null,
    "files": [
      "*.js",
      "build",
      "dist",
      "renderer",
      "!node_modules"
    ],
    "mac": {
      "target": "zip"
    },
    "linux": {
      "target": [
        "AppImage",
        "zip"
      ]
    },
    "win": {
      "target": [
        "NSIS",
        "zip"
      ]
    },
    "publish": {
      "provider": "github",
      "repo": "Example",
      "owner": "y***y",
      "token": "1234567"
    }
  },
  "repository": {
    "type": "git",
    "url": "**********"
  }
}

is there any other way to reduce the file size of electron app

Body:
You can change compression level from "normal" to "maximum" in package.json:

"build": {
    "appId": "com.electron.example",
    "compression": "maximum",
    // other build settings
}

This should usually save you much in term of app size depending on your previous compression settings and also on how much static files and added features, codes and/or dependencies you have in your build.

UPDATE

Anyway, If your app is relatively close to ~80Mb you won't save a lot, because that's generally the size of electron's build (containing node, chromium and API..).

Check electron-builder docs for more info.


问:
JavaScript Short-Circuit Still Throws Undefined Error
I'm working with some older code in AngularJs.  There's a variable someVar1 that could possibly exist in the JS ether and if it does, I wanted to attach it to my scope like so:

```<code>$scope.someVar2 = someVar1 || 0;
</code>```

But occasionally, when someVar1 doesn't exist in the ether, I get this error:

Error: someVar1 is not defined

It points directly to the line and column of someVar1 in the JS file.

Why is this happening?  I was under the impression that someVar1 || 0 would check if someVar1 was undefined, which is falsy, and set the $scope.someVar2 to 0.

答:
To have someVar1 being potentially undefined, this variable must be declared first.

In your case, it is possible that the code in charge of defining someVar1 is called after this script (or maybe never).

I'd suggest checking this in the first place.

As a hack, you could check if the variable is defined yourself by using typeof.

typeof will not throw a ReferenceError is the variable is not defined but instead will reply undefined if the variable is not defined or have undefined value.

For example, your code can look like this:

$scope.someVar2 = typeof(someVar1) !== "undefined" ? someVar1 : 0;
```

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined

Body:
I'm working with some older code in AngularJs.  There's a variable someVar1 that could possibly exist in the JS ether and if it does, I wanted to attach it to my scope like so:

$scope.someVar2 = someVar1 || 0;

But occasionally, when someVar1 doesn't exist in the ether, I get this error:

Error: someVar1 is not defined

It points directly to the line and column of someVar1 in the JS file.

Why is this happening?  I was under the impression that someVar1 || 0 would check if someVar1 was undefined, which is falsy, and set the $scope.someVar2 to 0.

Body:
To have someVar1 being potentially undefined, this variable must be declared first.

In your case, it is possible that the code in charge of defining someVar1 is called after this script (or maybe never).

I'd suggest checking this in the first place.

As a hack, you could check if the variable is defined yourself by using typeof.

typeof will not throw a ReferenceError is the variable is not defined but instead will reply undefined if the variable is not defined or have undefined value.

For example, your code can look like this:

$scope.someVar2 = typeof(someVar1) !== "undefined" ? someVar1 : 0;

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_defined


问:
git report files changed on which I did not work
git status reports a large set of file to be “new”, “modified” and “deleted” in a directory tree I never worked in. In Subversion  I would do a svn revert --recursive iPhone (I don't work on the iPhone version of the App) and be done with. But with Git things are not easy. With Git everything it is always complicated.

So I am in bit of a panic because the iPhone team would tear me apart if I mess up there code. And it would be a mayor mess as more then 50 files are reported changed.

Can anybody help me?

答:
The equivalent Git command is:

```<code>git reset --hard HEAD
</code>```

Be aware that this will throw away any local changes you have made in the whole tree (since the last commit). Be careful with this, it's a good idea to take a backup of your entire repository until you check that this really does what you want.

Body:
The equivalent Git command is:

git reset --hard HEAD

Be aware that this will throw away any local changes you have made in the whole tree (since the last commit). Be careful with this, it's a good idea to take a backup of your entire repository until you check that this really does what you want.


问:
Replace 'A' to 1, 'B' to 2, in R dataframe column
We have a column of a dataframe with letters A to Z

```<code>df$Col1 <- c("B", "C", "Q", ... , "A")
</code>```

I want to change those letters to numbers 1-26.

Naturally I could just do the following 26 times, but it isn't efficient nor pretty.

```<code>df$Col1  <- gsub("A","1",df$Col1)
</code>```

What would be the best way to approach this problem?

答:
Another way to do this in base R is to create a lookup table.</p>

```<code>LookUp = 1:26
names(LookUp) = LETTERS
Replacement = LookUp[Data]
</code>```

Body:
We have a column of a dataframe with letters A to Z

df$Col1 <- c("B", "C", "Q", ... , "A")

I want to change those letters to numbers 1-26.

Naturally I could just do the following 26 times, but it isn't efficient nor pretty.

df$Col1  <- gsub("A","1",df$Col1)

What would be the best way to approach this problem?

Body:
Another way to do this in base R is to create a lookup table.

LookUp = 1:26
names(LookUp) = LETTERS
Replacement = LookUp[Data]


问:
Try...catch vs .catch
So I have this user service functions in service.ts which includes database stuffs.

```<code>export const service = {
  async getAll(): Promise<User[]> {
    try {
      const result = await query
      return result
    } catch (e) {
      report.error(e)
      throw new Error(e)
    }
  },

  ...
}
</code>```

And query.ts file for some reasons, eg: caching, business logic, etc.

```<code>export const query = {
  async index(): Promise<User[]> {
    try {
      const result = await service.getAll()
      return result
    } catch (e) {
      report.error(e)
      throw new Error(e)
    }
  },

  ...
}
</code>```

And another upper layer for routers and resolvers, because I want to see all routes in one file.

```<code>export const resolver = {
  Query: {
    users: (): Promise<User[]> => query.index(),
  },

  ...
}
</code>```

Do I need to wrap try...catch in all functions? Or can't I just add .catch at the very top layer like this:

```<code>export const resolver = {
  Query: {
    users: (): Promise<User[]> => query.index().catch(e => e),
  },

  ...
}
</code>```

答:
Do I need to wrap try...catch in all functions?

No, you don't, not unless you want to log it at every level for some reason. Just handle it at the top level.

In an async function, promise rejections are exceptions (as you know, since you're using try/catch with them), and exceptions propagate through the async call tree until/unless they're caught. Under the covers, async functions return promises and reject those promises when a synchronous exception occurs or when a promise the async function is awaiting rejects.

Here's a simple example:

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function outer() {
    // ...
    await delay(10);

    console.log("before calling inner");
    await inner();
    console.log("after calling inner (we never get here)");
}

async function inner() {
    // ...
    await delay(10);

    console.log("inside inner");

    // Something goes wrong
    null.foo();
}

outer()
.catch(e => {
    console.log("Caught error: " + e.message, e.stack);
});```
</div>
</div>
</p>

<hr>

<p>Just as a side note: If you <em>do</em> catch an error because you want to do X before the error propagates and you're going to re-throw the error after you do X, best practice is to re-throw the error you caught, rather than creating a new one. So:</p>

```} catch (e) {
    // ...do X...
    throw e; // <== Not `throw new Error(e);`
}
```

But only do that if you really need to do X when an error occurs. Most of the time, just leave the try/catch off entirely.

Title: Try...catch vs .catch

Body:
So I have this user service functions in service.ts which includes database stuffs.

export const service = {
  async getAll(): Promise<User[]> {
    try {
      const result = await query
      return result
    } catch (e) {
      report.error(e)
      throw new Error(e)
    }
  },

  ...
}

And query.ts file for some reasons, eg: caching, business logic, etc.

export const query = {
  async index(): Promise<User[]> {
    try {
      const result = await service.getAll()
      return result
    } catch (e) {
      report.error(e)
      throw new Error(e)
    }
  },

  ...
}

And another upper layer for routers and resolvers, because I want to see all routes in one file.

export const resolver = {
  Query: {
    users: (): Promise<User[]> => query.index(),
  },

  ...
}

Do I need to wrap try...catch in all functions? Or can't I just add .catch at the very top layer like this:

export const resolver = {
  Query: {
    users: (): Promise<User[]> => query.index().catch(e => e),
  },

  ...
}

Body:
Do I need to wrap try...catch in all functions?

No, you don't, not unless you want to log it at every level for some reason. Just handle it at the top level.

In an async function, promise rejections are exceptions (as you know, since you're using try/catch with them), and exceptions propagate through the async call tree until/unless they're caught. Under the covers, async functions return promises and reject those promises when a synchronous exception occurs or when a promise the async function is awaiting rejects.

Here's a simple example:

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function outer() {
    // ...
    await delay(10);

    console.log("before calling inner");
    await inner();
    console.log("after calling inner (we never get here)");
}

async function inner() {
    // ...
    await delay(10);

    console.log("inside inner");

    // Something goes wrong
    null.foo();
}

outer()
.catch(e => {
    console.log("Caught error: " + e.message, e.stack);
});

Just as a side note: If you do catch an error because you want to do X before the error propagates and you're going to re-throw the error after you do X, best practice is to re-throw the error you caught, rather than creating a new one. So:

} catch (e) {
    // ...do X...
    throw e; // <== Not `throw new Error(e);`
}

But only do that if you really need to do X when an error occurs. Most of the time, just leave the try/catch off entirely.


问:
Thymeleaf th:each two iterate two listings
How can i iterate two listings at the same time using the thymeleaf th:each.

```<code>    <select id="rooms" th:field="*{room}">
        <option th:each="room : ${roomsFromHotel}"
                th:value="${{room}}"
                th:text="${room.id}">
            room name
        </option>
    </select>
</code>```

This is working, but i would like to do something like this

```<code>    <select id="rooms" th:field="*{room}">
    <option th:each="room : ${roomsFromHotel}, roomType : ${roomTypesList}"
            th:value="${{room}}"
            th:text="${roomType.name}">
            room name
        </option>
    </select>
</code>```

答: To expand on @Aeseir answers second option, I figured out it would be good idea to create inner class inside controller method with room and roomType. That way you don't pile up project structure, and have single use object, which is desirable in this case.</p>

Body:
How can i iterate two listings at the same time using the thymeleaf th:each.

    <select id="rooms" th:field="*{room}">
        <option th:each="room : ${roomsFromHotel}"
                th:value="${{room}}"
                th:text="${room.id}">
            room name
        </option>
    </select>

This is working, but i would like to do something like this

    <select id="rooms" th:field="*{room}">
    <option th:each="room : ${roomsFromHotel}, roomType : ${roomTypesList}"
            th:value="${{room}}"
            th:text="${roomType.name}">
            room name
        </option>
    </select>


问:
How Do I Remove The Border Of An Input
enter image description here

I have been trying to create a very simple login page. Around these inputs, as you can see, there are black borders. My question is, how do I remove that border?

答:
That is the new Google Chrome update. I encountered it the other day. Just add outline: none; to the element:

#testInput {
  outline: none;
  border-radius: 10px;
  border: 1px solid red;
  height: 25px;
  width: 225px;
  padding: 5px 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="testInput" type="text" placeholder="If you click here, no border is shown!" /></code>```

You could also try disabling this flag: chrome://flags/#form-controls-refresh. That will change the colour of the outline to a light-blue, which "was" default before Google Changed the option. But, if you are trying to make a website for the public, the first option would be better, as not everyone has disabled that flag. Hope this helps!

Edit: This does not work on <select> and <option> elements for some reason.

Title: How Do I Remove The Border Of An Input

Body:
That is the new Google Chrome update. I encountered it the other day. Just add outline: none; to the element:

#testInput {
  outline: none;
  border-radius: 10px;
  border: 1px solid red;
  height: 25px;
  width: 225px;
  padding: 5px 10px;
}

<input id="testInput" type="text" placeholder="If you click here, no border is shown!" />

You could also try disabling this flag: chrome://flags/#form-controls-refresh. That will change the colour of the outline to a light-blue, which "was" default before Google Changed the option. But, if you are trying to make a website for the public, the first option would be better, as not everyone has disabled that flag. Hope this helps!

Edit: This does not work on <select> and <option> elements for some reason.


问:
Swift & FirebaseIO query filtering not finding child
My app uses a barcode scanner (1D-3D) to get a code/tag, then validate it against my FirebaseIO and return as valid/invalid if found/not found.
The scanning works and console can print the tag nr everytime, although I cant figure out how to find that nr back in the Firebase?

```<code>self.tapHandler = { point in            print(point)                    self.barcodesHandler = { barcodes in                for barcode in barcodes {                    print(barcode.stringValue ?? "")                    let tags = barcode.stringValue                                        let query = dbref.queryOrdered(byChild: "Tag").queryEqual(toValue: tags)                    query.observe(.value, with: { (snapshot) in                for childSnapshot in snapshot.children {                    print("tag is ")                    print(childSnapshot)                }            })
</code>```

and my firebase structure (where Tag is the lookup field)
'''

```<code>{
  "members" : {
    "4b4ac23c9f184ce8b31fde011cd3a696" : {
      "Tag" : 82644,
      "Title" : "Mr",
      "Uid" : 80,
      "Username" : "orange"
    },
</code>```

答:
solved it.
Rookie error, data was saved as string and and lookup was for int. </p>

Body:
My app uses a barcode scanner (1D-3D) to get a code/tag, then validate it against my FirebaseIO and return as valid/invalid if found/not found.
The scanning works and console can print the tag nr everytime, although I cant figure out how to find that nr back in the Firebase?

self.tapHandler = { point in            print(point)                    self.barcodesHandler = { barcodes in                for barcode in barcodes {                    print(barcode.stringValue ?? "")                    let tags = barcode.stringValue                                        let query = dbref.queryOrdered(byChild: "Tag").queryEqual(toValue: tags)                    query.observe(.value, with: { (snapshot) in                for childSnapshot in snapshot.children {                    print("tag is ")                    print(childSnapshot)                }            })

and my firebase structure (where Tag is the lookup field)
'''

{
  "members" : {
    "4b4ac23c9f184ce8b31fde011cd3a696" : {
      "Tag" : 82644,
      "Title" : "Mr",
      "Uid" : 80,
      "Username" : "orange"
    },


问:
Rotate a custom UITableViewCell
I have a custom UITableViewCell which contains several UIButtons. Each button's frame position is relative to the cell width. I set autoresizingMask=UIViewAutoresizingFlexibleWidth so it will adjust the cell width and the button positions properly when the application starts with the device either in landscape or portrait mode.

The issue is when the device is rotated from one mode to the other, the buttons do not adjust positions because the UITableViewCell is reusable. In other words, the cell is not initialized based on the new UITalbeView width because the cell's function initWithStyle is called before the device is rotated and is not called again after the device rotation. Any suggestions?

答:
Since UITableViewCell is also a UIView, you can override setFrame method. Everytime that your table view rotates, this method will be called for all cells.</p>

```<code>-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];

    //Do your rotation stuffs here :)
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Rotate a custom UITableViewCell

Body:
Since UITableViewCell is also a UIView, you can override setFrame method. Everytime that your table view rotates, this method will be called for all cells.

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];

    //Do your rotation stuffs here :)
}


问:
How to find complete list of warnings in eclipse IDE
I'd like to find the places in my project where 'The static method should be accessed in a
 static way' warning raises.

Is there any way of getting the complete list at once ? I did search for a rule set in PMD, but dint find any. So, need help !!!

答: Select Markers view, at header of bottom panel for seeing list of warnings or errors</p>


问:
python equivalent of perl's "opendir"
What I am essentially looking for is a way to return a handle to a directory in python, a bit like how perl can do something like this...

```<code>opendir CWD .
</code>```

see: http://perldoc.perl.org/5.8.9/functions/opendir.html

CWD can then be used as a handle for pointing to the directory like *CWD in file operations.

The closest I've come across in python is open() but that doesn't return file descriptors/pointers and doesn't work with directories.

答:
The scandir function opens a handle and allows you to walk through each file iteratively.   This is useful for the one of the same reasons as opendir:  it's far more efficient when there could be a large number of files:

https://docs.python.org/3/library/os.html#os.scandir

The other use of opendir is the ability to retain a reference to the inode, rather than the path.

The generator returned by scandir can be passed around, like CWD, and it will retain the "inode-like" functionality of CWD.  For example, you can obtain a generator for scandir and then rename the underlying folder, and the generator remains valid.

However it cannot be "reset back" to the beginning.  AFAICT this is the only thing perl can do that python cannot.

Title: python equivalent of perl's "opendir"

Body:
What I am essentially looking for is a way to return a handle to a directory in python, a bit like how perl can do something like this...

opendir CWD .

see: http://perldoc.perl.org/5.8.9/functions/opendir.html

CWD can then be used as a handle for pointing to the directory like *CWD in file operations.

The closest I've come across in python is open() but that doesn't return file descriptors/pointers and doesn't work with directories.


问:
Expo MapView Country color
I need help regarding Expo MapView.

I want to achieve this kind of representation on MapView. I tried with polygons but, it's really hard to find all the country boundaries, and not sure if that is only way I can make this.

答:
I managed to find the solution, and if someone have the same requirement I will explain here. I used MapView from the react-native-maps and GeoJson feature.
Also I copied json files from here: https://github.com/johan/world.geo.json

After you copy the content from the json file, place it somewhere in the project (I added inside assets/georgia.json

Go to the component and add this code:

import React, { Component } from 'react'

import { StyleSheet, Dimensions } from 'react-native'

import MapView, {Geojson} from 'react-native-maps';

import myPlace from '../../assets/georgia.json';

export default class DataCoverage extends Component {
  render() {
    return (
      <MapView
        style={styles.mapStyle}
      >
        <Geojson
          geojson={myPlace}
          strokeColor="#0568AE"
          fillColor="#009FDB"
          strokeWidth={2}
        />
      </MapView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  mapStyle: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
})

Map should render with highlighted country that you wanted.

If you want multiple countries you just copy the "features" object and paste inside global features array inside your json file (in my case: georgija.json).

If you have any question feel free to ask.

Title: Expo MapView Country color


问:
Can we give a Sequence Id for rows in Spark?
I am new to spark and I have around 10000 rows in a datafile to read

```<code>SparkSession sessionSpark = SparkSession
            .builder()
            .config(sparkConf)
            .getOrCreate();

Dataset<Row> dataset = sessionSpark.read.parquet("s3://databucket/files/")

</code>```

I have a usecase to add a row number to every row in the dataset , the row number should start from 1 to 10000 (since the file has 10000 records ) , is it possible to assign a row number and we know spark shuffles the data but let's say even after rerunning the same file twice from the application , the row number generated should be the same , is it possible to do ?

答:
EDIT: A solution that complies to the ID being consecutive and starting at 1

If you can order them by something, it should be possible. This example might be scala, but the main part is still the SQL part.

val df = sc.parallelize(Seq(("alfa", 10), ("beta", 20), ("gama", 5))).toDF("word", "count")
df.createOrReplaceTempView("wordcount")

// MAIN PART
val tmpTable = spark.sqlContext.sql("select row_number() over (order by count) as index,word,count from wordcount")

tmpTable.show()

+-----+----+-----+
|index|word|count|
+-----+----+-----+
|    1|gama|    5|
|    2|alfa|   10|
|    3|beta|   20|
+-----+----+-----+

```

EDIT: If you don't need plain numbers, go with a hash of row. It is better.

Body:
I am new to spark and I have around 10000 rows in a datafile to read

SparkSession sessionSpark = SparkSession
            .builder()
            .config(sparkConf)
            .getOrCreate();

Dataset<Row> dataset = sessionSpark.read.parquet("s3://databucket/files/")

I have a usecase to add a row number to every row in the dataset , the row number should start from 1 to 10000 (since the file has 10000 records ) , is it possible to assign a row number and we know spark shuffles the data but let's say even after rerunning the same file twice from the application , the row number generated should be the same , is it possible to do ?

Body:
EDIT: A solution that complies to the ID being consecutive and starting at 1

If you can order them by something, it should be possible. This example might be scala, but the main part is still the SQL part.

val df = sc.parallelize(Seq(("alfa", 10), ("beta", 20), ("gama", 5))).toDF("word", "count")
df.createOrReplaceTempView("wordcount")

// MAIN PART
val tmpTable = spark.sqlContext.sql("select row_number() over (order by count) as index,word,count from wordcount")

tmpTable.show()

+-----+----+-----+
|index|word|count|
+-----+----+-----+
|    1|gama|    5|
|    2|alfa|   10|
|    3|beta|   20|
+-----+----+-----+

EDIT: If you don't need plain numbers, go with a hash of row. It is better.