问:
compute determinant from LU decomposition in lapack
Lapack, most probably, doesn't have any routine for computing determinant. However we can compute it using either LU, QR or SVD decomposition. I prefer to use LU decomposition. Now lapack uses some dgetrf subroutine to factorize a matrix A into PLU format with some IPIV array. I don't have much idea how to deal with this information. To compute the determinant, I just multiply diagonal elements of U matrix. But what is L and U in PLU format and how to extract them. I am programming in C.</p>

答:
L is a unit diagonal matrix so its determinant is always unity. For P it is either 1 or -1 depending on the odd/even number of permutations but ipiv is a swap array not the permutation array so you can convert the following simple Python loop to C

```<code>det = 1

for i in range(len(ipiv)):
    det *= u(i,i)
    if ipiv[i] != i:
        det *= -1
</code>```

But note that multiplication can both overflow or underflow if the conditioning of the matrix is problematic in terms of conditioning. Instead just use SVD.

Body:
L is a unit diagonal matrix so its determinant is always unity. For P it is either 1 or -1 depending on the odd/even number of permutations but ipiv is a swap array not the permutation array so you can convert the following simple Python loop to C

det = 1

for i in range(len(ipiv)):
    det *= u(i,i)
    if ipiv[i] != i:
        det *= -1

But note that multiplication can both overflow or underflow if the conditioning of the matrix is problematic in terms of conditioning. Instead just use SVD.


来源: stackexchange

问:
How to use user input in prolog to search
hello i want to be able to get the user input then store it and use in in my code.</p>

```<code>    body(mercury, 36, small, none, none).
    body(venus, 67, small, atmosphere, none).
    body(earth, 93, small, atmosphere, none).
    body(moon, 93, small, none, none).
    body(mars, 141, small, atmosphere, none).
    body(jupiter, 489, large, atmosphere, rings).

    miles(Body,Miles):-write('Enter the Goal State:'),nl,
           read(X),nl,
           body(Body, Miles, _, _, _); Miles > X.
</code>```

答:
i switched to GNU prolog firstly which helped.</p>

```<code>     miles(Body,Miles):-write('Enter the Goal State:'),nl,
                      read(X),nl,
                      body(Body, Miles, _, _, _), Miles > X.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
hello i want to be able to get the user input then store it and use in in my code.

    body(mercury, 36, small, none, none).
    body(venus, 67, small, atmosphere, none).
    body(earth, 93, small, atmosphere, none).
    body(moon, 93, small, none, none).
    body(mars, 141, small, atmosphere, none).
    body(jupiter, 489, large, atmosphere, rings).

    miles(Body,Miles):-write('Enter the Goal State:'),nl,
           read(X),nl,
           body(Body, Miles, _, _, _); Miles > X.

Body:
i switched to GNU prolog firstly which helped.

     miles(Body,Miles):-write('Enter the Goal State:'),nl,
                      read(X),nl,
                      body(Body, Miles, _, _, _), Miles > X.


问:
List comprehension Python with multiple control flow
I am trying to convert this function:

```<code>templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')
characters = templist
print(characters)
</code>```

into list comprehension

```<code>modified_list = ['v' for each in characters for item in vowels
                     if item in vowels
                 else 'c' if (item in alphabet) & (item not in vowels)
                 else '?']`
</code>```

Kinda stuck here! Can't figure out what I am doing wrong.

答:
Sometimes it's best to make a function to be called in your list comprehension. Still gives you the speed improvements of a list comprehension while cleaning up the insides a bit.</p>

```<code>def char_code(character):
  if character in vowels:
    return 'v'
  elif character in alphabet:
    return 'c'
  else:
    return '?'

print([char_code(c) for c in characters])
</code>```

Body:
I am trying to convert this function:

templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')
characters = templist
print(characters)

into list comprehension

modified_list = ['v' for each in characters for item in vowels
                     if item in vowels
                 else 'c' if (item in alphabet) & (item not in vowels)
                 else '?']`

Kinda stuck here! Can't figure out what I am doing wrong.

Body:
Sometimes it's best to make a function to be called in your list comprehension. Still gives you the speed improvements of a list comprehension while cleaning up the insides a bit.

def char_code(character):
  if character in vowels:
    return 'v'
  elif character in alphabet:
    return 'c'
  else:
    return '?'

print([char_code(c) for c in characters])


问:
Valums multi file uploading
I am using Valums AJAX javascript, found at http://valums.com/ajax-upload/
I am using VB.net as my server side scripting language and I have a webservice that is called, but I do not know how to retrieve the query string sent by his code.  Can some help me?</p>

答:
looks like you have access to these methods:

```<code>onSubmit: function(id, fileName){},
onProgress: function(id, fileName, loaded, total){},
onComplete: function(id, fileName, responseJSON){},
onCancel: function(id, fileName){},
</code>```

I would imagine that the onComplete method is what you would most likely want if you wanted to show something once the entire process was done.  I would guess the responseJSON value is what you would most likely want to check.

ContentLicense: CC BY-SA 2.5

Title: Valums multi file uploading

Body:
looks like you have access to these methods:

onSubmit: function(id, fileName){},
onProgress: function(id, fileName, loaded, total){},
onComplete: function(id, fileName, responseJSON){},
onCancel: function(id, fileName){},

I would imagine that the onComplete method is what you would most likely want if you wanted to show something once the entire process was done.  I would guess the responseJSON value is what you would most likely want to check.


问:
Xamarin cross platform database
I'm developing a cross platform app  in Xamarin.iOS and Xamarin.Android. I want to write a dal or repository layer once, and then make a reference to it from Android and iOS yo layers. Is this possible? Thanks.</p>

答: This kind of thing is not possible for 1.x, as the API is not compatible with any PCL or .NET Standard profile (however, you can use shared projects to achieve something similar).  However, version 2.0 of the library is compiled as .NET Standard 1.4 and so you can create one assembly that can be referenced by any platform that also implements at least .NET Standard 1.4 (including Xamarin iOS and Android).</p>

Title: Xamarin cross platform database


问:
Reference to vector element in allocator aware class calls copy constructor
I have a class that contains a vector of vector. It is allocator aware. When trying to call the operator[] to store elements in a reference, Visual Studio 2015 fails to compile, AppleClang (latest) is fine with it.

I am unsure whether this is a bug or not, which compiler is right, or if there is some undefined behaviour somewhere in my code.

Here is a concise example, with everything as simple as possible.

```<code>#include <cstdlib>
#include <memory>
#include <new>
#include <vector>

/* Allocator */
template <class T>
struct my_allocator {
    typedef T value_type;
    my_allocator() = default;

    template <class U>
    constexpr my_allocator(const my_allocator<U>&) noexcept {
    }

    T* allocate(std::size_t n) {
        if (n > std::size_t(-1) / sizeof(T))
            throw std::bad_alloc();
        if (auto p = static_cast<T*>(std::malloc(n * sizeof(T))))
            return p;
        throw std::bad_alloc();
    }

    void deallocate(T* p, std::size_t) noexcept {
        std::free(p);
    }
};

template <class T, class U>
bool operator==(const my_allocator<T>&, const my_allocator<U>&) {
    return true;
}
template <class T, class U>
bool operator!=(const my_allocator<T>&, const my_allocator<U>&) {
    return false;
}

/* Example Element */
struct X {
    X() = default;
    X(X&&) = default;
    X& operator=(X&&) = default;

    X(const X&) = delete;
    X& operator=(const X&) = delete;

    int test = 42;
};

/* Example Container Class */
template <class T, class Allocator = std::allocator<T>>
struct vec_of_vec {
    using OuterAlloc = typename std::allocator_traits<
            Allocator>::template rebind_alloc<std::vector<T, Allocator>>;

    vec_of_vec(const Allocator& alloc = Allocator{})
            : data(10, std::vector<T, Allocator>{ alloc },
                      OuterAlloc{ alloc }) {

        for (int i = 0; i < 10; ++i) {
            data[i].resize(42);
        }
    }

    std::vector<T, Allocator>& operator[](size_t i) {
        return data[i];
    }

    std::vector<std::vector<T, Allocator>, OuterAlloc> data;
};

/* Trigger Error */
int main(int, char**) {
    my_allocator<X> alloc;
    vec_of_vec<X, my_allocator<X>> test(alloc);

    X& ref_test = test[0][0]; // <-- Error Here!
    printf("%d\n", ref_test.test);

    return 0;
}
</code>```

VS tries to use the copy constructor of X.

error C2280: 'X::X(const X &)': attempting to reference a deleted function

function main.cpp(42): note: see declaration of 'X::X'

Is there something I am missing with the use of allocators and allocator_traits?

答:
GCC error sheds light on what's going on, potentially same in VS2015 case.

```<code>In file included from memory:65,
                 from prog.cc:2:
bits/stl_uninitialized.h: In instantiation of '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, _Allocator&) [with _InputIterator = __gnu_cxx::__normal_iterator<const X*, std::vector<X, my_allocator<X> > >; _ForwardIterator = X*; _Allocator = my_allocator<X>]':
bits/stl_vector.h:454:31:   required from 'std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = X; _Alloc = my_allocator<X>]'
bits/alloc_traits.h:250:4:   required from 'static std::_Require<std::__and_<std::__not_<typename std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::type>, std::is_constructible<_Tp, _Args ...> > > std::allocator_traits<_Alloc>::_S_construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = std::vector<X, my_allocator<X> >; _Args = {const std::vector<X, my_allocator<X> >&}; _Alloc = my_allocator<std::vector<X, my_allocator<X> > >; std::_Require<std::__and_<std::__not_<typename std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::type>, std::is_constructible<_Tp, _Args ...> > > = void]'
bits/alloc_traits.h:344:16:   required from 'static decltype (std::allocator_traits<_Alloc>::_S_construct(__a, __p, (forward<_Args>)(std::allocator_traits::construct::__args)...)) std::allocator_traits<_Alloc>::construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = std::vector<X, my_allocator<X> >; _Args = {const std::vector<X, my_allocator<X> >&}; _Alloc = my_allocator<std::vector<X, my_allocator<X> > >; decltype (std::allocator_traits<_Alloc>::_S_construct(__a, __p, (forward<_Args>)(std::allocator_traits::construct::__args)...)) = void]'
bits/stl_uninitialized.h:351:25:   required from '_ForwardIterator std::__uninitialized_fill_n_a(_ForwardIterator, _Size, const _Tp&, _Allocator&) [with _ForwardIterator = std::vector<X, my_allocator<X> >*; _Size = long unsigned int; _Tp = std::vector<X, my_allocator<X> >; _Allocator = my_allocator<std::vector<X, my_allocator<X> > >]'
bits/stl_vector.h:1466:33:   required from 'void std::vector<_Tp, _Alloc>::_M_fill_initialize(std::vector<_Tp, _Alloc>::size_type, const value_type&) [with _Tp = std::vector<X, my_allocator<X> >; _Alloc = my_allocator<std::vector<X, my_allocator<X> > >; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::value_type = std::vector<X, my_allocator<X> >]'
bits/stl_vector.h:421:9:   required from 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const value_type&, const allocator_type&) [with _Tp = std::vector<X, my_allocator<X> >; _Alloc = my_allocator<std::vector<X, my_allocator<X> > >; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::value_type = std::vector<X, my_allocator<X> >; std::vector<_Tp, _Alloc>::allocator_type = my_allocator<std::vector<X, my_allocator<X> > >]'
prog.cc:59:42:   required from 'vec_of_vec<T, Allocator>::vec_of_vec(const Allocator&) [with T = X; Allocator = my_allocator<X>]'
prog.cc:76:46:   required from here
bits/stl_uninitialized.h:275:25: error: no matching function for call to '__gnu_cxx::__alloc_traits<my_allocator<X>, X>::construct(my_allocator<X>&, X*, const X&)'
      __traits::construct(__alloc, std::__addressof(*__cur), *__first);```
```

<p>Wandbox</p>

<p>if we go from bottom to top we see:</p>

<ul>
<li><code>vec_of_vec</code> constructor</li>
<li><code>fill</code>ing <code>vector<vector></code> by 10 copies of empty inner vector</li>
<li>construction of copies</li>
</ul>

<p>Despite of the fact that inner vector is empty, its copy constructor requires that the type it contains is copy-constructible.</p>

<p>P.S.</p>

<p>I don't know how clang overcomes this. Potentially it recognises that <code>vector<vector></code> if filled with default value (if constructor with passed allocator instance still qualifies as default) and so instead of copying uses default construction</p>

<p>EDIT:</p>

<p>To fix the error replace</p>

```vec_of_vec(const Allocator& alloc = Allocator{})
        : data(10, std::vector<T, Allocator>{ alloc },
                  OuterAlloc{ alloc }) {

    for (int i = 0; i < 10; ++i) {
        data[i].resize(42);
    }
}
```

<p>by</p>

```vec_of_vec(const Allocator& alloc = Allocator{})
{
    data.resize(10); // here we don't `fill` it by copies but default-construct 10 instances
    for (int i = 0; i < 10; ++i) {
        data[i].resize(42);
    }
}
```

<p>or version for stateful allocator:</p>

```vec_of_vec(const Allocator& alloc = Allocator{}):
    data(OuterAlloc(alloc))
{
    for (int i = 0; i < 10; ++i) {
        data.emplace_back(alloc);
        data.back().resize(42);
    }
}
```

Body:
I have a class that contains a vector of vector. It is allocator aware. When trying to call the operator[] to store elements in a reference, Visual Studio 2015 fails to compile, AppleClang (latest) is fine with it.

I am unsure whether this is a bug or not, which compiler is right, or if there is some undefined behaviour somewhere in my code.

Here is a concise example, with everything as simple as possible.

#include <cstdlib>
#include <memory>
#include <new>
#include <vector>

/* Allocator */
template <class T>
struct my_allocator {
    typedef T value_type;
    my_allocator() = default;

    template <class U>
    constexpr my_allocator(const my_allocator&) noexcept {
    }

    T* allocate(std::size_t n) {
        if (n > std::size_t(-1) / sizeof(T))
            throw std::bad_alloc();
        if (auto p = static_cast<T*>(std::malloc(n * sizeof(T))))
            return p;
        throw std::bad_alloc();
    }

    void deallocate(T* p, std::size_t) noexcept {
        std::free(p);
    }
};

template <class T, class U>
bool operator==(const my_allocator<T>&, const my_allocator&) {
    return true;
}
template <class T, class U>
bool operator!=(const my_allocator<T>&, const my_allocator&) {
    return false;
}

/* Example Element */
struct X {
    X() = default;
    X(X&&) = default;
    X& operator=(X&&) = default;

    X(const X&) = delete;
    X& operator=(const X&) = delete;

    int test = 42;
};

/* Example Container Class */
template <class T, class Allocator = std::allocator<T>>
struct vec_of_vec {
    using OuterAlloc = typename std::allocator_traits<
            Allocator>::template rebind_alloc<std::vector<T, Allocator>>;

    vec_of_vec(const Allocator& alloc = Allocator{})
            : data(10, std::vector<T, Allocator>{ alloc },
                      OuterAlloc{ alloc }) {

        for (int i = 0; i < 10; ++i) {
            data[i].resize(42);
        }
    }

    std::vector<T, Allocator>& operator[](size_t i) {
        return data[i];
    }

    std::vector<std::vector<T, Allocator>, OuterAlloc> data;
};

/* Trigger Error */
int main(int, char**) {
    my_allocator<X> alloc;
    vec_of_vec<X, my_allocator<X>> test(alloc);

    X& ref_test = test[0][0]; // <-- Error Here!
    printf("%d\n", ref_test.test);

    return 0;
}

VS tries to use the copy constructor of X.

error C2280: 'X::X(const X &)': attempting to reference a deleted function

function main.cpp(42): note: see declaration of 'X::X'

Is there something I am missing with the use of allocators and allocator_traits?

Body:
GCC error sheds light on what's going on, potentially same in VS2015 case.

In file included from memory:65,
                 from prog.cc:2:
bits/stl_uninitialized.h: In instantiation of '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, _Allocator&) [with _InputIterator = __gnu_cxx::__normal_iterator<const X*, std::vector<X, my_allocator<X> > >; _ForwardIterator = X*; _Allocator = my_allocator<X>]':
bits/stl_vector.h:454:31:   required from 'std::vector<_Tp, _Alloc>::vector(const std::vector<_Tp, _Alloc>&) [with _Tp = X; _Alloc = my_allocator<X>]'
bits/alloc_traits.h:250:4:   required from 'static std::_Require<std::__and_<std::__not_<typename std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::type>, std::is_constructible<_Tp, _Args ...> > > std::allocator_traits<_Alloc>::_S_construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = std::vector<X, my_allocator<X> >; _Args = {const std::vector<X, my_allocator<X> >&}; _Alloc = my_allocator<std::vector<X, my_allocator<X> > >; std::_Require<std::__and_<std::__not_<typename std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::type>, std::is_constructible<_Tp, _Args ...> > > = void]'
bits/alloc_traits.h:344:16:   required from 'static decltype (std::allocator_traits<_Alloc>::_S_construct(__a, __p, (forward<_Args>)(std::allocator_traits::construct::__args)...)) std::allocator_traits<_Alloc>::construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = std::vector<X, my_allocator<X> >; _Args = {const std::vector<X, my_allocator<X> >&}; _Alloc = my_allocator<std::vector<X, my_allocator<X> > >; decltype (std::allocator_traits<_Alloc>::_S_construct(__a, __p, (forward<_Args>)(std::allocator_traits::construct::__args)...)) = void]'
bits/stl_uninitialized.h:351:25:   required from '_ForwardIterator std::__uninitialized_fill_n_a(_ForwardIterator, _Size, const _Tp&, _Allocator&) [with _ForwardIterator = std::vector<X, my_allocator<X> >*; _Size = long unsigned int; _Tp = std::vector<X, my_allocator<X> >; _Allocator = my_allocator<std::vector<X, my_allocator<X> > >]'
bits/stl_vector.h:1466:33:   required from 'void std::vector<_Tp, _Alloc>::_M_fill_initialize(std::vector<_Tp, _Alloc>::size_type, const value_type&) [with _Tp = std::vector<X, my_allocator<X> >; _Alloc = my_allocator<std::vector<X, my_allocator<X> > >; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::value_type = std::vector<X, my_allocator<X> >]'
bits/stl_vector.h:421:9:   required from 'std::vector<_Tp, _Alloc>::vector(std::vector<_Tp, _Alloc>::size_type, const value_type&, const allocator_type&) [with _Tp = std::vector<X, my_allocator<X> >; _Alloc = my_allocator<std::vector<X, my_allocator<X> > >; std::vector<_Tp, _Alloc>::size_type = long unsigned int; std::vector<_Tp, _Alloc>::value_type = std::vector<X, my_allocator<X> >; std::vector<_Tp, _Alloc>::allocator_type = my_allocator<std::vector<X, my_allocator<X> > >]'
prog.cc:59:42:   required from 'vec_of_vec<T, Allocator>::vec_of_vec(const Allocator&) [with T = X; Allocator = my_allocator<X>]'
prog.cc:76:46:   required from here
bits/stl_uninitialized.h:275:25: error: no matching function for call to '__gnu_cxx::__alloc_traits<my_allocator<X>, X>::construct(my_allocator<X>&, X*, const X&)'
      __traits::construct(__alloc, std::__addressof(*__cur), *__first);```

Wandbox

if we go from bottom to top we see:

vec_of_vec constructor

filling vector<vector> by 10 copies of empty inner vector

construction of copies

Despite of the fact that inner vector is empty, its copy constructor requires that the type it contains is copy-constructible.

P.S.

I don't know how clang overcomes this. Potentially it recognises that vector<vector> if filled with default value (if constructor with passed allocator instance still qualifies as default) and so instead of copying uses default construction

EDIT:

To fix the error replace

vec_of_vec(const Allocator& alloc = Allocator{})
        : data(10, std::vector<T, Allocator>{ alloc },
                  OuterAlloc{ alloc }) {

    for (int i = 0; i < 10; ++i) {
        data[i].resize(42);
    }
}

by

vec_of_vec(const Allocator& alloc = Allocator{})
{
    data.resize(10); // here we don't `fill` it by copies but default-construct 10 instances
    for (int i = 0; i < 10; ++i) {
        data[i].resize(42);
    }
}

or version for stateful allocator:

vec_of_vec(const Allocator& alloc = Allocator{}):
    data(OuterAlloc(alloc))
{
    for (int i = 0; i < 10; ++i) {
        data.emplace_back(alloc);
        data.back().resize(42);
    }
}


问:
Ambiguous Lexer rules in Antlr
I have an antlr grammar with multiple lexer rules that match the same word. It can't be resolved during lexing, but with the grammar, it becomes unambiguous.

Example:

```<code>conversion: NUMBER UNIT CONVERT UNIT;
NUMBER: [0-9]+;
UNIT: 'in' | 'meters' | ......;
CONVERT: 'in';
</code>```

Input: 1 in in meters

The word "in" matches the lexer rules UNIT and CONVERT.

How can this be solved while keeping the grammar file readable?

答:
Based on the info in your question, it's hard to say what the best solution would be - I don't know what your lexer rules are, for example - nor can I tell why you have lexer rules that are ambiguous at all.

In my experience with antlr, lexer rules don't generally carry any semantic meaning; they are just text that matches some kind of regular expression.  So, instead of having VARIABLE, METHOD_NAME, etc, I'd just have IDENTIFIER, and then figure it out at a higher level.

In other words, it seems (from the little I can glean from your question) that you might benefit either from replacing UNIT and CONVERT with grammar rules, or just having a single rule:

```<code>conversion: NUMBER TEXT TEXT TEXT
</code>```

and validating the text values in your ANTLR listener/tree-walker/etc.

EDIT

Thanks for updating your question with lexer rules.  It's clear now why it's failing - as BernardK points out, antlr will always choose the first matching lexer rule.  This means it's impossible for the second of two ambiguous lexer rules to match, and makes your proposed design infeasible.

My opinion is that lexer rules are not the correct layer to do things like unit validation; they excel at structure, not content.  Evaluating the parse tree will be much more practical than trying to contort an antlr grammar.

Finally, you might also do something with embedded actions on parse rules, like validating the value of an ID token against a known set of units.  It could work, but would destroy the reusability of your grammar.

Title: Ambiguous Lexer rules in Antlr

Body:
I have an antlr grammar with multiple lexer rules that match the same word. It can't be resolved during lexing, but with the grammar, it becomes unambiguous.

Example:

conversion: NUMBER UNIT CONVERT UNIT;
NUMBER: [0-9]+;
UNIT: 'in' | 'meters' | ......;
CONVERT: 'in';

Input: 1 in in meters

The word "in" matches the lexer rules UNIT and CONVERT.

How can this be solved while keeping the grammar file readable?

Body:
Based on the info in your question, it's hard to say what the best solution would be - I don't know what your lexer rules are, for example - nor can I tell why you have lexer rules that are ambiguous at all.

In my experience with antlr, lexer rules don't generally carry any semantic meaning; they are just text that matches some kind of regular expression.  So, instead of having VARIABLE, METHOD_NAME, etc, I'd just have IDENTIFIER, and then figure it out at a higher level.

In other words, it seems (from the little I can glean from your question) that you might benefit either from replacing UNIT and CONVERT with grammar rules, or just having a single rule:

conversion: NUMBER TEXT TEXT TEXT

and validating the text values in your ANTLR listener/tree-walker/etc.

EDIT

Thanks for updating your question with lexer rules.  It's clear now why it's failing - as BernardK points out, antlr will always choose the first matching lexer rule.  This means it's impossible for the second of two ambiguous lexer rules to match, and makes your proposed design infeasible.

My opinion is that lexer rules are not the correct layer to do things like unit validation; they excel at structure, not content.  Evaluating the parse tree will be much more practical than trying to contort an antlr grammar.

Finally, you might also do something with embedded actions on parse rules, like validating the value of an ID token against a known set of units.  It could work, but would destroy the reusability of your grammar.


问:
C++: creating an event repeatedly called by timer
I wanted to redo a Conway's Game of Life thing I did in Java, but this time use ncurses and C++. Obviously I need a timed event so I can run out the simulation at a rate which it can be viewed. Turns out it is a hell of a lot harder to make a timed event in C++ than it is in Java. I am not as experienced in C++ than I am in Java. I have already looked around online, and what I found led me to the code I have below. Upon executing it produces no result in the terminal. What exactly am I doing wrong?

main.cpp:

```<code>#include <iostream>
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

using namespace std;

class callBackTimer //no idea how this works, got it from Stack Overflow thread
{

public:
    callBackTimer()
    :_execute(false)
    {}

    void start(int interval, std::function<void(void)> func)
    {
        _execute = true;
        std::thread([=]()
                    {
                        while (_execute)
                        {
                            func();
                            std::this_thread::sleep_for(
                            std::chrono::milliseconds(interval));
                        }
                    }).detach();
    }

    void stop()
    {
        _execute = false;
    }

private:
    bool _execute;

};

void timerExec()
{
    cout << "SNAFU" << endl;
}

int main(int argc, const char * argv[])
{
    callBackTimer timer; //declare the timer
    std::function<void(void)> exec = timerExec; //declare a pointer to timerExec
    timer.start(25, std::bind(exec)); //start the timer

    return 0;
}
</code>```

答:
You need to wait for the thread to finish what it is doing, which is usually accomplished by calling join(). So maybe something like this:

```<code>#include <iostream>
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

using namespace std;

class callBackTimer //no idea how this works, got it from Stack Overflow thread
{

public:
    callBackTimer()
        :_execute(false)
    {}

    void setup(int interval, std::function<void(void)> func)
    {
        _execute = true;
        thread = std::thread([=]()
        {
//          while (_execute)
            for (int steps = 0; steps < 100; ++steps)
            {
                func();
                std::this_thread::sleep_for(std::chrono::milliseconds(interval));
            }
        });
    }

    void stop()
    {
        _execute = false;
    }

    void run()
    {
        thread.join();
    }

private:
    bool _execute;
    std::thread thread;

};

void timerExec()
{
    cout << "SNAFU" << endl;
}

int main(int argc, const char * argv[])
{
    callBackTimer timer; //declare the timer
    std::function<void(void)> exec = timerExec; //declare a pointer to timerExec
    timer.setup(25, std::bind(exec)); //start the timer
    timer.run();

    return 0;
}
</code>```

Calling detach() is OK, but you have to make main() wait for the thread manually. You also need a condition to break out of the while loop, otherwise it will go on forever. Hope that helps!

Body:
I wanted to redo a Conway's Game of Life thing I did in Java, but this time use ncurses and C++. Obviously I need a timed event so I can run out the simulation at a rate which it can be viewed. Turns out it is a hell of a lot harder to make a timed event in C++ than it is in Java. I am not as experienced in C++ than I am in Java. I have already looked around online, and what I found led me to the code I have below. Upon executing it produces no result in the terminal. What exactly am I doing wrong?

main.cpp:

#include <iostream>
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

using namespace std;

class callBackTimer //no idea how this works, got it from Stack Overflow thread
{

public:
    callBackTimer()
    :_execute(false)
    {}

    void start(int interval, std::function<void(void)> func)
    {
        _execute = true;
        std::thread([=]()
                    {
                        while (_execute)
                        {
                            func();
                            std::this_thread::sleep_for(
                            std::chrono::milliseconds(interval));
                        }
                    }).detach();
    }

    void stop()
    {
        _execute = false;
    }

private:
    bool _execute;

};

void timerExec()
{
    cout << "SNAFU" << endl;
}

int main(int argc, const char * argv[])
{
    callBackTimer timer; //declare the timer
    std::function<void(void)> exec = timerExec; //declare a pointer to timerExec
    timer.start(25, std::bind(exec)); //start the timer

    return 0;
}

Body:
You need to wait for the thread to finish what it is doing, which is usually accomplished by calling join(). So maybe something like this:

#include <iostream>
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>

using namespace std;

class callBackTimer //no idea how this works, got it from Stack Overflow thread
{

public:
    callBackTimer()
        :_execute(false)
    {}

    void setup(int interval, std::function<void(void)> func)
    {
        _execute = true;
        thread = std::thread([=]()
        {
//          while (_execute)
            for (int steps = 0; steps < 100; ++steps)
            {
                func();
                std::this_thread::sleep_for(std::chrono::milliseconds(interval));
            }
        });
    }

    void stop()
    {
        _execute = false;
    }

    void run()
    {
        thread.join();
    }

private:
    bool _execute;
    std::thread thread;

};

void timerExec()
{
    cout << "SNAFU" << endl;
}

int main(int argc, const char * argv[])
{
    callBackTimer timer; //declare the timer
    std::function<void(void)> exec = timerExec; //declare a pointer to timerExec
    timer.setup(25, std::bind(exec)); //start the timer
    timer.run();

    return 0;
}

Calling detach() is OK, but you have to make main() wait for the thread manually. You also need a condition to break out of the while loop, otherwise it will go on forever. Hope that helps!


问:
Inserting row into QSqlTableModel
When a row is going to be edited, an index is passed into the editing dialogue.

The edit works fine.

When I want to add a row, I don't pass an index to the dialogue constructor, so it knows that it's supposed to add a new row.

Here's the code of function reacting to dialogue's buttons

```<code>void DialogAddCl::on_buttonBox_clicked(QAbstractButton *button)
{
    // prepare
    m->database().transaction();
    QString debugstr;
    auto chi4 = ui->buttonBox->buttonRole(button);
    int rowCount = m->rowCount();
    switch (chi4) {
    case QDialogButtonBox::AcceptRole:
        if (!ind->isValid())
            // insert
            if (!m->insertRow(rowCount, *ind))
            {
                QMessageBox::critical (this, "Error inserting into model", m->lastError().text(), QMessageBox::Cancel);
                break;
            }
            else
            {
                m->setData(m->index(rowCount, 0), rowCount+1);
            }
        else
        {
            // update
            rowCount = ind->row();
        }
        m->setData(m->index(rowCount, 1), ui->name->text());
        m->setData(m->index(rowCount, 2), ui->addr->text());
        // 12 other setData() calls

        if (m->submitAll())
        {
            m->database().commit();
        }
        else
        {
            // rollback if error
            m->database().rollback();
            debugstr = QString(m->database().lastError().text());
            QMessageBox::critical (this, "Database returned an error",
                                   m->database().lastError().text(), QMessageBox::Cancel);
        }
    case QDialogButtonBox::RejectRole:
        this->close();
        break;
    case QDialogButtonBox::ResetRole:
        fillFields();
        break;
    default:
        break;
    }

}
</code>```

Here's a piece of dialogaddcl.h:

```<code>private:
    Ui::DialogAddCl *ui;
    QSqlTableModel* m;
    QModelIndex* ind;
</code>```

So, m->submitAll() works fine if I edit an existing record, and fails if I try to submit freshly inserted row. I have checked with debugging, setData() calls work fine even when adding, so it's not DB expecting NOT NULL fields and giving an error.

By the way, maybe somebody can point out a method to catch the actual error text? I tried with debugstr, but it always only contains empty string. So does the error message that I print

答:
To insert a row to QSqlTableModel you should not use setData() directly, if you must not use insertRecord(), where you indicate the row and the QSqlRecord. The QSqlRecord can be obtained through the record() method of the model.

```<code>InsertDialog dial;
if(dial.exec()== InsertDialog::Accepted){
    db.transaction();
    QString f = dial.firstname();
    QString l = dial.lastname();

    QSqlRecord record = model.record();
    /* since the id field has the autoincrement attribute,
     * it is not necessary to indicate its value,
     * that is because this field of the request is removed.
    */
    record.remove(record.indexOf("id"))
    record.setValue("firstname", f);
    record.setValue("lastname", l);
    /*-1 is set to indicate that it will be added to the last row*/
    if(model.insertRecord(-1, record)){
        qDebug()<<"successful insertion";
        model->submitAll();
    }
    else{
        db.rollback();
    }
}
</code>```

In the following link you will find an example.

Title: Inserting row into QSqlTableModel

Body:
When a row is going to be edited, an index is passed into the editing dialogue.

The edit works fine.

When I want to add a row, I don't pass an index to the dialogue constructor, so it knows that it's supposed to add a new row.

Here's the code of function reacting to dialogue's buttons

void DialogAddCl::on_buttonBox_clicked(QAbstractButton *button)
{
    // prepare
    m->database().transaction();
    QString debugstr;
    auto chi4 = ui->buttonBox->buttonRole(button);
    int rowCount = m->rowCount();
    switch (chi4) {
    case QDialogButtonBox::AcceptRole:
        if (!ind->isValid())
            // insert
            if (!m->insertRow(rowCount, *ind))
            {
                QMessageBox::critical (this, "Error inserting into model", m->lastError().text(), QMessageBox::Cancel);
                break;
            }
            else
            {
                m->setData(m->index(rowCount, 0), rowCount+1);
            }
        else
        {
            // update
            rowCount = ind->row();
        }
        m->setData(m->index(rowCount, 1), ui->name->text());
        m->setData(m->index(rowCount, 2), ui->addr->text());
        // 12 other setData() calls

        if (m->submitAll())
        {
            m->database().commit();
        }
        else
        {
            // rollback if error
            m->database().rollback();
            debugstr = QString(m->database().lastError().text());
            QMessageBox::critical (this, "Database returned an error",
                                   m->database().lastError().text(), QMessageBox::Cancel);
        }
    case QDialogButtonBox::RejectRole:
        this->close();
        break;
    case QDialogButtonBox::ResetRole:
        fillFields();
        break;
    default:
        break;
    }

}

Here's a piece of dialogaddcl.h:

private:
    Ui::DialogAddCl *ui;
    QSqlTableModel* m;
    QModelIndex* ind;

So, m->submitAll() works fine if I edit an existing record, and fails if I try to submit freshly inserted row. I have checked with debugging, setData() calls work fine even when adding, so it's not DB expecting NOT NULL fields and giving an error.

By the way, maybe somebody can point out a method to catch the actual error text? I tried with debugstr, but it always only contains empty string. So does the error message that I print

Body:
To insert a row to QSqlTableModel you should not use setData() directly, if you must not use insertRecord(), where you indicate the row and the QSqlRecord. The QSqlRecord can be obtained through the record() method of the model.

InsertDialog dial;
if(dial.exec()== InsertDialog::Accepted){
    db.transaction();
    QString f = dial.firstname();
    QString l = dial.lastname();

    QSqlRecord record = model.record();
    /* since the id field has the autoincrement attribute,
     * it is not necessary to indicate its value,
     * that is because this field of the request is removed.
    */
    record.remove(record.indexOf("id"))
    record.setValue("firstname", f);
    record.setValue("lastname", l);
    /*-1 is set to indicate that it will be added to the last row*/
    if(model.insertRecord(-1, record)){
        qDebug()<<"successful insertion";
        model->submitAll();
    }
    else{
        db.rollback();
    }
}

In the following link you will find an example.

ContentLicense: CC BY-SA 4.0


问:
How to ensure that generated id does not exist in database
I would like to generate unique id for entity and store the entity in Cassandra database (only if entity with generated id does not exist already).

After id generation I check in db if there is any entity with the same id. If not, then the entity is saved. Sample code from MyService class:

```<code>synchronized (MyService.class) {
    do {
        id = generateId();
    } while (myDao.find(id) != null);
    sampleObject.setId(id);
    myDao.create(sampleObject);
}
</code>```

In MyDao to save entity I'm using:

```<code>cassandraOperations.insert(sampleObject);
</code>```

What is the best practice to ensure that already generated id does not exist in database? I feel that this synchronize block is not the most efficient solution.
Or maybe there is any other way in which I can ensure that entity is inserted only if there is no entity with the same id in database?

答:
UUID is safe solution but sometimes id is not very unique.
For example SSN.
To tackle it Cassandra has support for lightweight transactions.
https://docs.datastax.com/en/cql/3.3/cql/cql_using/useInsertLWT.html

On Application side no synchronized is required.
Cassandra resultset will return applied flag true if record is written.

Function to write:

```<code>ResultSet insertIfNotExists(String Id) {
    String cql = QueryBuilder.insertInto("table_name")
            .value("id", Id)
            .ifNotExists()

    return cassandraOperations.query(cql);
}
</code>```

Usage:

```<code>ResultSet rs = insertIfNotExists("abc123")
if (rs.wasApplied()) {
   log.info("success")
}
</code>```

Body:
I would like to generate unique id for entity and store the entity in Cassandra database (only if entity with generated id does not exist already).

After id generation I check in db if there is any entity with the same id. If not, then the entity is saved. Sample code from MyService class:

synchronized (MyService.class) {
    do {
        id = generateId();
    } while (myDao.find(id) != null);
    sampleObject.setId(id);
    myDao.create(sampleObject);
}

In MyDao to save entity I'm using:

cassandraOperations.insert(sampleObject);

What is the best practice to ensure that already generated id does not exist in database? I feel that this synchronize block is not the most efficient solution.
Or maybe there is any other way in which I can ensure that entity is inserted only if there is no entity with the same id in database?

Body:
UUID is safe solution but sometimes id is not very unique.
For example SSN.
To tackle it Cassandra has support for lightweight transactions.
https://docs.datastax.com/en/cql/3.3/cql/cql_using/useInsertLWT.html

On Application side no synchronized is required.
Cassandra resultset will return applied flag true if record is written.

Function to write:

ResultSet insertIfNotExists(String Id) {
    String cql = QueryBuilder.insertInto("table_name")
            .value("id", Id)
            .ifNotExists()

    return cassandraOperations.query(cql);
}

Usage:

ResultSet rs = insertIfNotExists("abc123")
if (rs.wasApplied()) {
   log.info("success")
}


问:
How to check arrays with numpy python
I have two arrays and i want to check how many integers are the same in the different arrays. The problem i'm having is that it only shows me how many are the same when they are in the same position. Both arrays have 15 numbers in them.
Example:

```<code>import numpy as np
a = np.array([1, 4, 5, 7, 9, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26])
b = np.array([8, 28, 12, 3, 24, 16, 23, 19, 14, 2, 11, 29, 27, 6, 13])
print(np.count_nonzero(a==b))
</code>```

This prints 0 even though there's clearly integers that are the same. How can i make this print how many integers have the same value?

答:
You can perform broadcasted comparison between b and a, and then just tally up the matches:

```<code>(b == a[:, None]).sum()
3
</code>```

This checks out since you have [14, 19, 23] as the common elements.

Title: How to check arrays with numpy python

Body:
I have two arrays and i want to check how many integers are the same in the different arrays. The problem i'm having is that it only shows me how many are the same when they are in the same position. Both arrays have 15 numbers in them.
Example:

import numpy as np
a = np.array([1, 4, 5, 7, 9, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26])
b = np.array([8, 28, 12, 3, 24, 16, 23, 19, 14, 2, 11, 29, 27, 6, 13])
print(np.count_nonzero(a==b))

This prints 0 even though there's clearly integers that are the same. How can i make this print how many integers have the same value?

Body:
You can perform broadcasted comparison between b and a, and then just tally up the matches:

(b == a[:, None]).sum()
3

This checks out since you have [14, 19, 23] as the common elements.


问:
mysql many-to-one and group by giving unusual results
im having difficulty with the following fairly simple setup:

```<code>CREATE TABLE IF NOT EXISTS invoices (
id int(11) NOT NULL auto_increment,
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_items (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
description text NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_payments (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);
</code>```

some data:

```<code>INSERT INTO invoices (id) VALUES (1);

INSERT INTO invoices_items (id, invoice_id, description, amount) VALUES
(1, 1, 'Item 1', '750.00'),
(2, 1, 'Item 2', '750.00'),
(3, 1, 'Item 3', '50.00'),
(4, 1, 'Item 4', '150.00');

INSERT INTO invoices_payments (id, invoice_id, amount) VALUES
(1, 1, '50.00'),
(2, 1, '1650.00');
</code>```

and the sql yielding unusual results:

```<code>select  invoices.id,
        ifnull(sum(invoices_payments.amount),0) as payments_total,
        ifnull(count(invoices_items.id),0) as item_count
from    invoices
            left join invoices_items on invoices_items.invoice_id=invoices.id
            left join invoices_payments on invoices_payments.invoice_id=invoices.id
group by invoices.id
</code>```

results in the (erroneous) output

```<code>id  payments_total  item_count
1   6800.00     8
</code>```

now, as evidenced by there being infact only four 'invoice_item' rows, i dont understand why mysql is not grouping properly.

EDIT

i know i can do something like this:

```<code>select x.*, ifnull(sum(invoices_payments.amount),0) as payments_total from (
    select  invoices.id,
            ifnull(count(invoices_items.id),0) as item_count
    from    invoices
                left join invoices_items on invoices_items.invoice_id=invoices.id
    group by invoices.id
) as x left join invoices_payments on invoices_payments.invoice_id=x.id
group by x.id
</code>```

but i want to know if im doing something wrong in the first query - i cant immediately see why the first query is giving incorrect results! :(

答:
Your join logic is incorrect. In your join, you specify invoices_items.invoice_id = invoices.id. You also specify invoices_payments.invoice_id = invoices.id. Because of transitivity, you end up with:

```<code>invoices_items.invoice_id    = invoices.id
invoices_payments.invoice_id = invoices.id
invoice_items.invoice_id     = invoices_payments.invoice_id
</code>```

The sum of the 2 invoice payments is $1700. For every invoice payment, there are 4 invoice_items that satisfy the above relations. $1700 * 4 = $6800.

For every invoice item, there will be two invoice payments that satisfy the above relations. 4 invoice items * 2 = 8 count.

Body:
im having difficulty with the following fairly simple setup:

CREATE TABLE IF NOT EXISTS invoices (
id int(11) NOT NULL auto_increment,
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_items (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
description text NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_payments (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

some data:

INSERT INTO invoices (id) VALUES (1);

INSERT INTO invoices_items (id, invoice_id, description, amount) VALUES
(1, 1, 'Item 1', '750.00'),
(2, 1, 'Item 2', '750.00'),
(3, 1, 'Item 3', '50.00'),
(4, 1, 'Item 4', '150.00');

INSERT INTO invoices_payments (id, invoice_id, amount) VALUES
(1, 1, '50.00'),
(2, 1, '1650.00');

and the sql yielding unusual results:

select  invoices.id,
        ifnull(sum(invoices_payments.amount),0) as payments_total,
        ifnull(count(invoices_items.id),0) as item_count
from    invoices
            left join invoices_items on invoices_items.invoice_id=invoices.id
            left join invoices_payments on invoices_payments.invoice_id=invoices.id
group by invoices.id

results in the (erroneous) output

id  payments_total  item_count
1   6800.00     8

now, as evidenced by there being infact only four 'invoice_item' rows, i dont understand why mysql is not grouping properly.

EDIT

i know i can do something like this:

select x.*, ifnull(sum(invoices_payments.amount),0) as payments_total from (
    select  invoices.id,
            ifnull(count(invoices_items.id),0) as item_count
    from    invoices
                left join invoices_items on invoices_items.invoice_id=invoices.id
    group by invoices.id
) as x left join invoices_payments on invoices_payments.invoice_id=x.id
group by x.id

but i want to know if im doing something wrong in the first query - i cant immediately see why the first query is giving incorrect results! :(

Body:
Your join logic is incorrect. In your join, you specify invoices_items.invoice_id = invoices.id. You also specify invoices_payments.invoice_id = invoices.id. Because of transitivity, you end up with:

invoices_items.invoice_id    = invoices.id
invoices_payments.invoice_id = invoices.id
invoice_items.invoice_id     = invoices_payments.invoice_id

The sum of the 2 invoice payments is $1700. For every invoice payment, there are 4 invoice_items that satisfy the above relations. $1700 * 4 = $6800.

For every invoice item, there will be two invoice payments that satisfy the above relations. 4 invoice items * 2 = 8 count.


问:
Linking multiple existing model instances to FactoryGirl object
As a simplified view, I have the following models:

```<code>class LineItem
  belongs_to :service, polymorphic: true
  belongs_to :line_item_template, optional: true
end

class LineItemTemplate
  belongs_to :service, polymorphic: true
  has_many :line_items
end

class ServiceOne
  has_many :line_items, as: :service
  has_many :line_item_templates, as: :service
  after_create :create_line_item_templates

  def create_line_item_templates
    # ...
  end
end

class ServiceTwo
  has_many :line_items, as: :service
  has_many :line_item_templates, as: :service
  after_create :create_line_item_templates

  def create_line_item_templates
    # ...
  end
end
</code>```

So after either an instance of ServiceOne or ServiceTwo is created, the appropriate line_item_templates are created and linked to the service.

It's important to note that the line_item_templates association from LineItem is optional.

I'd like to create a factory that creates a LineItem which links to a newly created ServiceOne but also the LineItemTemplate that was created in the ServiceOne#after_create callback.

The pseudocode of what I'm trying to implement but haven't been able to get working is as follows:

```<code>FactoryGirl.define do
  factory :line_item
    service {|t| t.association :service_one}
    line_item_template_id self.services.first.line_item_templates.first.id
  end
end
</code>```

How can I achieve that in a working factory?

答:
I'm sure there's a better way to do this, but the solution I came up with was as follows.

Using the after(:build) callback was essential for my various tests as it means regardless of using FactoryGirl.build or FactoryGirl.create it will

```<code>FactoryGirl.define do
  factory :line_item do
    sequence(:description) {|n| "Line Item #{n}"}
    service {|t| t.association :service_one}
  end

  factory :service_one_line_item, parent: :line_item do
    after(:build) do |li|
      li.line_item_template_id = li.service.line_item_templates.first.id
    end
  end

  factory :service_two_line_item, parent: :line_item do
    after(:build) do |li|
      li.service = FactoryGirl.create(:service_two)
      li.line_item_template_id = li.service.line_item_templates.first.id
    end
  end
end
</code>```

Body:
As a simplified view, I have the following models:

class LineItem
  belongs_to :service, polymorphic: true
  belongs_to :line_item_template, optional: true
end

class LineItemTemplate
  belongs_to :service, polymorphic: true
  has_many :line_items
end

class ServiceOne
  has_many :line_items, as: :service
  has_many :line_item_templates, as: :service
  after_create :create_line_item_templates

  def create_line_item_templates
    # ...
  end
end

class ServiceTwo
  has_many :line_items, as: :service
  has_many :line_item_templates, as: :service
  after_create :create_line_item_templates

  def create_line_item_templates
    # ...
  end
end

So after either an instance of ServiceOne or ServiceTwo is created, the appropriate line_item_templates are created and linked to the service.

It's important to note that the line_item_templates association from LineItem is optional.

I'd like to create a factory that creates a LineItem which links to a newly created ServiceOne but also the LineItemTemplate that was created in the ServiceOne#after_create callback.

The pseudocode of what I'm trying to implement but haven't been able to get working is as follows:

FactoryGirl.define do
  factory :line_item
    service {|t| t.association :service_one}
    line_item_template_id self.services.first.line_item_templates.first.id
  end
end

How can I achieve that in a working factory?

Body:
I'm sure there's a better way to do this, but the solution I came up with was as follows.

Using the after(:build) callback was essential for my various tests as it means regardless of using FactoryGirl.build or FactoryGirl.create it will

FactoryGirl.define do
  factory :line_item do
    sequence(:description) {|n| "Line Item #{n}"}
    service {|t| t.association :service_one}
  end

  factory :service_one_line_item, parent: :line_item do
    after(:build) do |li|
      li.line_item_template_id = li.service.line_item_templates.first.id
    end
  end

  factory :service_two_line_item, parent: :line_item do
    after(:build) do |li|
      li.service = FactoryGirl.create(:service_two)
      li.line_item_template_id = li.service.line_item_templates.first.id
    end
  end
end


问:
Cookie Syncing: user id mapping between different cookie domains
I am quite new to ad targeting field, and have a question while reading blogs about cookie syncing.

Let's assume User123 has never been to Amazon.com and Facebook.com in her entire life, and the scenario is User123 bought a PS4 on Amazon and then visited Facebook.com and saw a couple ads of Xbox, Nintendo Switch, etc(she visited Amazon first and then Facebook).

When visiting Amazon, Amazon generated a Cookie Amazon123 for User123 and then called Facebook to generate Facebook123 to map to Amazon123.

Now after leaving Amazon for Facebook, how does FB know that the one who's visiting is actually Facebook123 instead of considering her as a new user and generates Facebook234? Is it because both Cookies collect other user information (like machine id?) so they can use it to do a matching?

Or if the whole assumption is wrong, what is the correct work flow?

答:
Your hypothetical situation is a little unique from a standard mapping process because both Amazon and FB have logins which would be used for consumer mapping rather than cookie IDs. But for the sake of this conversation and to keep things simple we can use your hypothetical situation.

When your hypothetical consumer visits Amazon on a browser (not an app) Amazon lays a 3rd party cookie ID into the consumer's browser and calls it Amazon 123. When the same consumer visits Facebook the same process happens and Facebook drops a cookie ID called FB 123 into the consumer's browser. Until the consumer deletes their cookies (most browsers automatically do on a monthly cadence) then every time the consumer visits FB, FB is able to request the cached ID number and figure out that they are speaking to consumer FB123. Once that consumer deletes their cookies FB would not be able to identify that consumers as FB123 unless the consumer logged in.

At this point Amazon and FB don't know that these two cookies are the same consumer unless they ran a cookie match which they would never do because both platforms are walled gardens.


问:
ERROR in Entry module not found
This is the error:

SyntaxError: Unexpected token } in JSON at position 322. But JSON file
  is correct.

JSON file:

```<code>    {
      "name": "gl",
      "version": "1.0.0",
      "description": "GL online CV",
      "main": "index.html",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Alex Guzhyk",
      "license": "ISC",
      "dependencies": {
        "express": "^4.16.2",
        "react": "^16.1.1",
        "react-dom": "^16.1.1",
      },
      "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "webpack": "^3.8.1",
        }
    }
</code>```

答:
In JSON, you can not have a trailing comma.

Incorrect usage

```<code>"person": {
  "age": 31,
  "gender": "male",
}
</code>```

Unlike javascript, JSON is a strict data format which is not javascript! It has only been derived from it.

Therefore in JSON, you are not allowed to add a trailing comma.

Correct usage

```<code>"person": {
  "age": 31,
  "gender": "male"
}
</code>```

Title: ERROR in Entry module not found

Body:
This is the error:

SyntaxError: Unexpected token } in JSON at position 322. But JSON file
  is correct.

JSON file:

    {
      "name": "gl",
      "version": "1.0.0",
      "description": "GL online CV",
      "main": "index.html",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "Alex Guzhyk",
      "license": "ISC",
      "dependencies": {
        "express": "^4.16.2",
        "react": "^16.1.1",
        "react-dom": "^16.1.1",
      },
      "devDependencies": {
        "babel-core": "^6.26.0",
        "babel-loader": "^7.1.2",
        "babel-preset-env": "^1.6.1",
        "babel-preset-es2015": "^6.24.1",
        "babel-preset-react": "^6.24.1",
        "webpack": "^3.8.1",
        }
    }

Body:
In JSON, you can not have a trailing comma.

Incorrect usage

"person": {
  "age": 31,
  "gender": "male",
}

Unlike javascript, JSON is a strict data format which is not javascript! It has only been derived from it.

Therefore in JSON, you are not allowed to add a trailing comma.

Correct usage

"person": {
  "age": 31,
  "gender": "male"
}


问:
wxpython add splitter window to notebook page
I have adapted this for my own use:

```<code>import wx
import wx.grid as gridlib

########################################################################
class LeftPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class RightPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title="Splitter Tutorial")

        splitter = wx.SplitterWindow(self)
        leftP = LeftPanel(splitter)
        rightP = RightPanel(splitter)

        # split the window
        splitter.SplitVertically(leftP, rightP)
        splitter.SetMinimumPaneSize(20)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()
</code>```

Now I want to add it as a page in a simple wxNotebook. Normally the notebook page would be set up something like:

```<code>p = wx.Panel(self)
nb = wx.Notebook(p)
page1 = module_name.module_Class(nb)
nb.AddPage(page1, "Tab label")
</code>```

The splitter has two (three in my case) panel Classes but obviously I can't just call one of them. Can someone please explain how I can wrap it all up?
Thanks.

答:
You just need to put the splitter widget on a panel in its own class. Then you can add your panel with the splitter in it to a notebook widget. Here's an example:</p>

```<code>import wx
import wx.grid as gridlib

########################################################################
class LeftPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class RightPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)

########################################################################
class SplitterPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        splitter = wx.SplitterWindow(self)
        leftP = LeftPanel(splitter)
        rightP = RightPanel(splitter)
        # split the window
        splitter.SplitVertically(leftP, rightP)
        splitter.SetMinimumPaneSize(20)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title="Notebook Splitter Tutorial")

        panel = wx.Panel(self)

        notebook = wx.Notebook(panel)
        splitter = SplitterPanel(notebook)
        notebook.AddPage(splitter, 'Splitter')

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
        panel.SetSizer(sizer)

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()
</code>```

Body:
I have adapted this for my own use:

import wx
import wx.grid as gridlib

########################################################################
class LeftPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class RightPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title="Splitter Tutorial")

        splitter = wx.SplitterWindow(self)
        leftP = LeftPanel(splitter)
        rightP = RightPanel(splitter)

        # split the window
        splitter.SplitVertically(leftP, rightP)
        splitter.SetMinimumPaneSize(20)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

Now I want to add it as a page in a simple wxNotebook. Normally the notebook page would be set up something like:

p = wx.Panel(self)
nb = wx.Notebook(p)
page1 = module_name.module_Class(nb)
nb.AddPage(page1, "Tab label")

The splitter has two (three in my case) panel Classes but obviously I can't just call one of them. Can someone please explain how I can wrap it all up?
Thanks.

Body:
You just need to put the splitter widget on a panel in its own class. Then you can add your panel with the splitter in it to a notebook widget. Here's an example:

import wx
import wx.grid as gridlib

########################################################################
class LeftPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class RightPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)

########################################################################
class SplitterPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        splitter = wx.SplitterWindow(self)
        leftP = LeftPanel(splitter)
        rightP = RightPanel(splitter)
        # split the window
        splitter.SplitVertically(leftP, rightP)
        splitter.SetMinimumPaneSize(20)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(splitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, title="Notebook Splitter Tutorial")

        panel = wx.Panel(self)

        notebook = wx.Notebook(panel)
        splitter = SplitterPanel(notebook)
        notebook.AddPage(splitter, 'Splitter')

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
        panel.SetSizer(sizer)

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()


Title: How to check arrays with numpy python

Body:
You want to use np.intersect1d, if I am understanding you correctly:

In [12]: import numpy as np

In [13]: a = np.array([1, 4, 5, 7, 9, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26])
    ...: b = np.array([8, 28, 12, 3, 24, 16, 23, 19, 14, 2, 11, 29, 27, 6, 13])
    ...:

In [14]: np.intersect1d(a, b)
Out[14]: array([14, 19, 23])


问:
CSS font-spacing issue with Calibri and the letters "ti"
I'm starting a website build for a small business that uses Calibri as the primary font for their branding and I have come across an issue with using this font in certain web browsers.

In Google Chrome and Opera, the letters "ti" appear to be joined.  When I apply some letter-spacing, they will not separate.  This doesn't happen in Mozilla Firefox or Microsoft Edge.

Is there an issue with the font, or is it the browser?
Is there anything I can do to fix it?

I've created a snippet for testing (or you can test at https://codepen.io/whitenoise83/pen/KyXWWL)

#site-title {
  font-family: Calibri, Candara, Segoe, "Segoe UI", Optima,  Arial, sans-serif !important;
  color: #e00b00;
  font-size: 6em;
  font-weight: bold;
  /*letter-spacing: 0.25em;*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="site-title">Audiomation</span> </code>```

答:
Never seen that but after some search :
Maybe a font ligature option to choose ?

https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-ligatures

Hope its help ;)

Body:
I'm starting a website build for a small business that uses Calibri as the primary font for their branding and I have come across an issue with using this font in certain web browsers.

In Google Chrome and Opera, the letters "ti" appear to be joined.  When I apply some letter-spacing, they will not separate.  This doesn't happen in Mozilla Firefox or Microsoft Edge.

Is there an issue with the font, or is it the browser?
Is there anything I can do to fix it?

I've created a snippet for testing (or you can test at https://codepen.io/whitenoise83/pen/KyXWWL)

#site-title {
  font-family: Calibri, Candara, Segoe, "Segoe UI", Optima,  Arial, sans-serif !important;
  color: #e00b00;
  font-size: 6em;
  font-weight: bold;
  /*letter-spacing: 0.25em;*/
}

Audiomation


问:
Format data in workbook into data frame in R/PYTHON
I have unformatted data in Exel that i need to covert into data frame in R

Raw Data:

which needs to be converted to data frame format in R:

The Titles like Event name and Time etc., are represented as columns. Is there any way we can do it in R.

答:
If it is saved as an excel workbook, try clicking File > Save As > CSV. Then running the following code to read the file into R as a data frame.

data <- read.csv("C:/Users/YOURNAME/Desktop/data.csv")

If this does not load in your data into the manner you'd like (unfortunately, it may not), the solution you are looking for might be much more complicated and would result in changes to the Excel file itself.


问:
Changing HTML to PlainText
I'm trying to edit HTML to be plaintext in java, but I am running into an issue. I am trying to get the number on the padding-left element in the code and transform it into tabs but it doesn't work.
ie.

Hello
 becomes Hello with a tab in front of it.

Here is my code so far (every 40px becomes one tab)

```<code> private static String setNonHTML(String txt)
{
    System.out.println(txt.substring(txt.indexOf("<p style=\"padding-left:") + 23, txt.indexOf("px\"><b>")));
    //return "";
    return txt
    .replaceAll("<br>","\n")
    .replaceAll(txt.substring(txt.indexOf("<p style=\"padding-left:"), txt.indexOf("px\"><b>") + 7)
        ,"\n" + repeat("\t",Integer.parseInt(txt.substring(txt.indexOf("<p style=\"padding-left:") + 23, txt.indexOf("px\"><b>")))/40))
    .replaceAll(txt.substring(txt.indexOf("<p style=\"padding-left:"), txt.indexOf("px\">") + 4)
        ,"\n" + repeat("\t",Integer.parseInt(txt.substring(txt.indexOf("<p style=\"padding-left:") + 23, txt.indexOf("px\">")))/40))
    .replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", "\n");
}
</code>```

答:
I cleaned up some of your code to show you what is happening

```<code>    private static String setNonHTML(String txt)
    {
        System.out.println(txt.substring(txt.indexOf("<p style=\"padding-left:") + 23, txt.indexOf("px\"><b>")));
        //return "";

        //grab the padding text indexes
        int beforePaddingIndex = txt.indexOf("<p style=\"padding-left:");
        int afterPaddingIndex = txt.indexOf("px\"><b>");

        //replace all breaks with new lines
        txt = txt.replaceAll("<br>", "\n");

        //replaces all instances of 40px\"> with \n\t
        txt = txt.replaceAll(txt.substring(beforePaddingIndex, afterPaddingIndex + 7), "\n" + repeat("\t", Integer.parseInt(txt.substring(beforePaddingIndex + 23, afterPaddingIndex)) / 40));

        //the indexes of these items have changed because the last operation replaced them. The following items will not have indexes due to the replace operation.
        beforePaddingIndex = txt.indexOf("<p style=\"padding-left:");
        afterPaddingIndex = txt.indexOf("px\"><b>");
        afterPaddingBeforeBoldIndex = txt.indexOf("px\">");

        //replace a substring of the same tag a second time? should find nothing
        txt = txt.replaceAll(txt.substring(beforePaddingIndex, afterPaddingIndex), "\n" + repeat("\t", Integer.parseInt(txt.substring(beforePaddingIndex + 23, afterPaddingBeforeBoldIndex)) / 40));

        txt = txt.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", "\n");

        return txt;
    }
</code>```

as you can see, after the first replace all, there is a second replace all that takes place on virtually the same indexes. You grab the index of values inline after the first replace all so I set them again to replicate that behavior. Splitting out code into descriptive variables and sections is a good practice and is monumentally helpful when trying to debug complicated sections. I don't know what the output of your program is giving you, so I have no way to know if this actually solves your issue, but it does look like a bug and I believe this might give you a good start.

As for what you should do to fix this, you may want to look into some off the shelf solution like http://htmlcleaner.sourceforge.net/javause.php

That allows you to traverse and modify html programmatically and read off attributes like padding left and the extract content between tags.

Title: Changing HTML to PlainText

Body:
I'm trying to edit HTML to be plaintext in java, but I am running into an issue. I am trying to get the number on the padding-left element in the code and transform it into tabs but it doesn't work.
ie.

Hello
 becomes Hello with a tab in front of it.

Here is my code so far (every 40px becomes one tab)

 private static String setNonHTML(String txt)
{
    System.out.println(txt.substring(txt.indexOf("
")));
    //return "";
    return txt
    .replaceAll("
","\n")
    .replaceAll(txt.substring(txt.indexOf("
") + 7)
        ,"\n" + repeat("\t",Integer.parseInt(txt.substring(txt.indexOf("
")))/40))
    .replaceAll(txt.substring(txt.indexOf("
") + 4)
        ,"\n" + repeat("\t",Integer.parseInt(txt.substring(txt.indexOf("
")))/40))
    .replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", "\n");
}

Body:
I cleaned up some of your code to show you what is happening

    private static String setNonHTML(String txt)
    {
        System.out.println(txt.substring(txt.indexOf("<p style=\"padding-left:") + 23, txt.indexOf("px\"><b>")));
        //return "";

        //grab the padding text indexes
        int beforePaddingIndex = txt.indexOf("<p style=\"padding-left:");
        int afterPaddingIndex = txt.indexOf("px\"><b>");

        //replace all breaks with new lines
        txt = txt.replaceAll("<br>", "\n");

        //replaces all instances of 40px\"> with \n\t
        txt = txt.replaceAll(txt.substring(beforePaddingIndex, afterPaddingIndex + 7), "\n" + repeat("\t", Integer.parseInt(txt.substring(beforePaddingIndex + 23, afterPaddingIndex)) / 40));

        //the indexes of these items have changed because the last operation replaced them. The following items will not have indexes due to the replace operation.
        beforePaddingIndex = txt.indexOf("<p style=\"padding-left:");
        afterPaddingIndex = txt.indexOf("px\"><b>");
        afterPaddingBeforeBoldIndex = txt.indexOf("px\">");

        //replace a substring of the same tag a second time? should find nothing
        txt = txt.replaceAll(txt.substring(beforePaddingIndex, afterPaddingIndex), "\n" + repeat("\t", Integer.parseInt(txt.substring(beforePaddingIndex + 23, afterPaddingBeforeBoldIndex)) / 40));

        txt = txt.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", "\n");

        return txt;
    }

as you can see, after the first replace all, there is a second replace all that takes place on virtually the same indexes. You grab the index of values inline after the first replace all so I set them again to replicate that behavior. Splitting out code into descriptive variables and sections is a good practice and is monumentally helpful when trying to debug complicated sections. I don't know what the output of your program is giving you, so I have no way to know if this actually solves your issue, but it does look like a bug and I believe this might give you a good start.

As for what you should do to fix this, you may want to look into some off the shelf solution like http://htmlcleaner.sourceforge.net/javause.php

That allows you to traverse and modify html programmatically and read off attributes like padding left and the extract content between tags.


问:
IdentityUserLogin<string>' requires a primary key to be defined error while adding migration
I am using 2 different Dbcontexts. i want to use 2 different databases users and mycontext. While doing that i am getting a error The entity type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin' requires a primary key to be defined. I think there is something wrong with IdentityUser please suggest me where can i change my code so that i can add migration.

My Dbcontext class:

```<code> class MyContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<PostTag>()
            .HasKey(t => new { t.PostId, t.TagId });

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Post)
            .WithMany(p => p.PostTags)
            .HasForeignKey(pt => pt.PostId);

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Tag)
            .WithMany(t => t.PostTags)
            .HasForeignKey(pt => pt.TagId);
    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public AppUser User {get; set;}
    public string Content { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}
</code>```

and AppUser class:

```<code>public class AppUser : IdentityUser
{
  //some other propeties
}
</code>```

when I try to Add migration the following error occurs.

```<code>The entity type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>' requires a primary key to be defined.
</code>```

give me solution to resolve the issue..

答:
To reduce the link to a nutshell, try this:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    ...
</code>```

See Above link for more.

Body:
I am using 2 different Dbcontexts. i want to use 2 different databases users and mycontext. While doing that i am getting a error The entity type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin' requires a primary key to be defined. I think there is something wrong with IdentityUser please suggest me where can i change my code so that i can add migration.

My Dbcontext class:

 class MyContext : DbContext
{
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<PostTag>()
            .HasKey(t => new { t.PostId, t.TagId });

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Post)
            .WithMany(p => p.PostTags)
            .HasForeignKey(pt => pt.PostId);

        modelBuilder.Entity<PostTag>()
            .HasOne(pt => pt.Tag)
            .WithMany(t => t.PostTags)
            .HasForeignKey(pt => pt.TagId);
    }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public AppUser User {get; set;}
    public string Content { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class Tag
{
    public string TagId { get; set; }

    public List<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public string TagId { get; set; }
    public Tag Tag { get; set; }
}

and AppUser class:

public class AppUser : IdentityUser
{
  //some other propeties
}

when I try to Add migration the following error occurs.

The entity type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>' requires a primary key to be defined.

give me solution to resolve the issue..

Body:
To reduce the link to a nutshell, try this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    ...

See Above link for more.


问:
How do I remove the objects I want from an array and add them to another array using .forEach?
This is a coding challenge I'm working on and can't seem to grasp what I need to do. Not sure if I am even going in the right direction.

Here is the instructions: Here we have an array called people. Some of them are our friends and some are not.
1. Create an empty array called friends.
2. Using .forEach, loop over people and add those that are our friend to the empty friends array.

Here is the provided code:

```<code>var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted",friend: false},
  {name: "Sperry",friend: true},
  {name: "Bill",friend: false}
];
</code>```

My code so far:

```<code>var friends = [];
people.forEach(function(people){
  if (people === true) {
    return name;
  } else {
    //
  }
});
</code>```

答:
I would do this using #Array.prototype.filter. It's the easiest. You can also use #Array.prototype.map to transform "persons" to "names". Click the button to run the code below and see for yourself.

var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted",friend: false},
  {name: "Sperry",friend: true},
  {name: "Bill",friend: false}
];

var friends = people
  // only keep the people that are friends
  .filter(person => person.friend)
  // transform a person to a name
  .map(person => person.name);
console.log(friends)```

Body:
This is a coding challenge I'm working on and can't seem to grasp what I need to do. Not sure if I am even going in the right direction.

Here is the instructions: Here we have an array called people. Some of them are our friends and some are not.
1. Create an empty array called friends.
2. Using .forEach, loop over people and add those that are our friend to the empty friends array.

Here is the provided code:

var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted",friend: false},
  {name: "Sperry",friend: true},
  {name: "Bill",friend: false}
];

My code so far:

var friends = [];
people.forEach(function(people){
  if (people === true) {
    return name;
  } else {
    //
  }
});


问:
List comprehension Python with multiple control flow
I am trying to convert this function:

```<code>templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')
characters = templist
print(characters)
</code>```

into list comprehension

```<code>modified_list = ['v' for each in characters for item in vowels
                     if item in vowels
                 else 'c' if (item in alphabet) & (item not in vowels)
                 else '?']`
</code>```

Kinda stuck here! Can't figure out what I am doing wrong.

答:
You had several errors in your comprehension syntax.  Most of all, you inserted your for clause into the middle of your conditional expression; it has to go at the end of the expression.

```<code>modified_list = ['v' if each in vowels else
                ('c' if each in alphabet else '?')
                     for each in characters]
</code>```

I also removed the useless for clauses, and the redundant test for a consonant: when you're in the else clause of your expression, you already know it's not a vowel -- no need to re-test.

FULL TEST

vowels = "aeiou"
alphabet = "qwertyuiopasdfghjklzxcvbnm"
characters = "Now is the time"

```<code>templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')

print("     original", ''.join(templist))

modified_list = ['v' if each in vowels else \
                ('c' if (each in alphabet) else '?') \
                     for each in characters]

print("comprehension", ''.join(modified_list))
</code>```

Output:

```<code>     original ?vc?vc?ccv?cvcv
comprehension ?vc?vc?ccv?cvcv
</code>```

Body:
I am trying to convert this function:

templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')
characters = templist
print(characters)

into list comprehension

modified_list = ['v' for each in characters for item in vowels
                     if item in vowels
                 else 'c' if (item in alphabet) & (item not in vowels)
                 else '?']`

Kinda stuck here! Can't figure out what I am doing wrong.

Body:
You had several errors in your comprehension syntax.  Most of all, you inserted your for clause into the middle of your conditional expression; it has to go at the end of the expression.

modified_list = ['v' if each in vowels else
                ('c' if each in alphabet else '?')
                     for each in characters]

I also removed the useless for clauses, and the redundant test for a consonant: when you're in the else clause of your expression, you already know it's not a vowel -- no need to re-test.

FULL TEST

vowels = "aeiou"
alphabet = "qwertyuiopasdfghjklzxcvbnm"
characters = "Now is the time"

templist = []
for each in characters:
    if each in vowels:
        templist.append('v')
    elif (each in alphabet) & (each not in vowels):
        templist.append('c')
    else:
        templist.append('?')

print("     original", ''.join(templist))

modified_list = ['v' if each in vowels else \
                ('c' if (each in alphabet) else '?') \
                     for each in characters]

print("comprehension", ''.join(modified_list))

Output:

     original ?vc?vc?ccv?cvcv
comprehension ?vc?vc?ccv?cvcv


问:
What's the difference between jQuery .val() and .attr('value')?
I think the title is clear enough</p>

答:
To add to actis's answer...

Also .attr('value') returns the value that was before editing input
  field. And .val() returns the current value.

When working with a text entry field, the setter methods of .attr() and .val() work differently.

```<code>.val('newval')
</code>```

will set the value the user sees on the page and update the value returned by subsequent .val() method calls.  It will not set the value= attribute of the element.

OTOH

```<code>.attr('value','newval')
</code>```

will set the value= attribute on the element.   If the user hasn't typed and .val(newval) hasn't been called, then doing this will also visually update the control and update the value returned by .val().

You can investigate further with the following jsfiddle:

https://jsfiddle.net/jasonnet/vamLww2k/

Good luck.

Body: I think the title is clear enough

Body:
To add to actis's answer...

Also .attr('value') returns the value that was before editing input
  field. And .val() returns the current value.

When working with a text entry field, the setter methods of .attr() and .val() work differently.

.val('newval')

will set the value the user sees on the page and update the value returned by subsequent .val() method calls.  It will not set the value= attribute of the element.

OTOH

.attr('value','newval')

will set the value= attribute on the element.   If the user hasn't typed and .val(newval) hasn't been called, then doing this will also visually update the control and update the value returned by .val().

You can investigate further with the following jsfiddle:

https://jsfiddle.net/jasonnet/vamLww2k/

Good luck.


问:
Split Pandas DataFrame on Blank rows
I have a large dataframe that I need to split on empty rows.

here's a simplified example of the DataFrame:

```<code>    A   B   C
0   1   0   International
1   1   1   International
2   NaN 2   International
3   1   3   International
4   1   4   International
5   8   0   North American
6   8   1   North American
7   8   2   North American
8   8   3   North American
9   NaN NaN NaN
10  1   0   Internal
11  1   1   Internal
12  6   0   East
13  6   1   East
14  6   2   East
...
</code>```

As you can see, row 9 is blank. What I need to do is take rows 0 through 8 and put them in a different dataframe, as well as rows 10 to the next blank so that I have several dataframes in the end. Notice, when looking for blank rows I need the whole row to be blank.

Here is the code I'm using to find blanks:

```<code>def find_breaks(df):
    df_breaks = df[(df.loc[:,['A','B','C']].isnull()).any(axis=1)]
    print(df_breaks.index)
</code>```

This code works when I test it on the simplified DF but, of course, my real DataFrame has many more columns than ['A','B','C']

How can I find the next blank row (or as I am doing above, all the blank rows at once) without having to specify my column names?

Thanks

答:
IIUC, use pd.isnull + np.split:

```<code>df_list = np.split(df, df[df.isnull().all(1)].index)

for df in df_list:
    print(df, '\n')

     A    B               C
0  1.0  0.0   International
1  1.0  1.0   International
2  NaN  2.0   International
3  1.0  3.0   International
4  1.0  4.0   International
5  8.0  0.0  North American
6  8.0  1.0  North American
7  8.0  2.0  North American
8  8.0  3.0  North American

      A    B         C
9   NaN  NaN       NaN
10  1.0  0.0  Internal
11  1.0  1.0  Internal
12  6.0  0.0      East
13  6.0  1.0      East
14  6.0  2.0      East
</code>```

First, obtain the indices where the entire row is null, and then use that to split your dataframe into chunks. np.split handles dataframes quite well.

Title: Split Pandas DataFrame on Blank rows

Body:
I have a large dataframe that I need to split on empty rows.

here's a simplified example of the DataFrame:

    A   B   C
0   1   0   International
1   1   1   International
2   NaN 2   International
3   1   3   International
4   1   4   International
5   8   0   North American
6   8   1   North American
7   8   2   North American
8   8   3   North American
9   NaN NaN NaN
10  1   0   Internal
11  1   1   Internal
12  6   0   East
13  6   1   East
14  6   2   East
...

As you can see, row 9 is blank. What I need to do is take rows 0 through 8 and put them in a different dataframe, as well as rows 10 to the next blank so that I have several dataframes in the end. Notice, when looking for blank rows I need the whole row to be blank.

Here is the code I'm using to find blanks:

def find_breaks(df):
    df_breaks = df[(df.loc[:,['A','B','C']].isnull()).any(axis=1)]
    print(df_breaks.index)

This code works when I test it on the simplified DF but, of course, my real DataFrame has many more columns than ['A','B','C']

How can I find the next blank row (or as I am doing above, all the blank rows at once) without having to specify my column names?

Thanks

Body:
IIUC, use pd.isnull + np.split:

df_list = np.split(df, df[df.isnull().all(1)].index)

for df in df_list:
    print(df, '\n')

     A    B               C
0  1.0  0.0   International
1  1.0  1.0   International
2  NaN  2.0   International
3  1.0  3.0   International
4  1.0  4.0   International
5  8.0  0.0  North American
6  8.0  1.0  North American
7  8.0  2.0  North American
8  8.0  3.0  North American

      A    B         C
9   NaN  NaN       NaN
10  1.0  0.0  Internal
11  1.0  1.0  Internal
12  6.0  0.0      East
13  6.0  1.0      East
14  6.0  2.0      East

First, obtain the indices where the entire row is null, and then use that to split your dataframe into chunks. np.split handles dataframes quite well.


问:
Redirecting users to a 404 page by using pretty urls
I'm working on a mvc project just for fun.
Pretty urls already work, but i can't find a good way with my code to send visitors to a 404 page, in case the page doesn't exist which people are looking for.</p>

```<code>class Route
{
       private $_uri = array();
       private $_method = array();

    /*
     * Builds a collection of internal URL's to look for
     * @param type $uri
     */
    public function add($uri, $method = null)
    {
        $this->_uri[] = '/' . trim($uri, '/');

        if($method != null){
            $this->_method[] = $method;
        }
    }

    public function submit()
    {

        $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';

        foreach($this->_uri as $key => $value){
            if(preg_match("#^$value$#",$uriGetParam)){
                if(is_string($this->_method[$key])){
                    $useMethod = $this->_method[$key];
                    new $useMethod();
                }
                else{
                    call_user_func($this->_method[$key]);
                }
            }
        }
    }

}
</code>```

答:
I didn't analyze your code thoroughly (I couldn't, not sure what is the example route / method you're adding with ->add), but the solution seems simple to me:

```<code>public function submit()
{

    $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
    $routeFound = false;
    foreach($this->_uri as $key => $value){
        if(preg_match("#^$value$#",$uriGetParam)){
            if(is_string($this->_method[$key])){
                $routeFound = true;
                $useMethod = $this->_method[$key];
                new $useMethod();
            }
            else{
                $routeFound = true;
                call_user_func($this->_method[$key]);
            }
        }
    }
    if(!$routeFound){
        http_response_code(404);
        echo 'ooooh, not found';
        //or:
        include('404.php');
        die();
    }
}
</code>```

p.s. http_response_code is a built-in function:

https://secure.php.net/manual/en/function.http-response-code.php

edit: you could put the code starting with 'http_response_code(404);' to a separate function and just call it.

Body:
I'm working on a mvc project just for fun.
Pretty urls already work, but i can't find a good way with my code to send visitors to a 404 page, in case the page doesn't exist which people are looking for.

class Route
{
       private $_uri = array();
       private $_method = array();

    /*
     * Builds a collection of internal URL's to look for
     * @param type $uri
     */
    public function add($uri, $method = null)
    {
        $this->_uri[] = '/' . trim($uri, '/');

        if($method != null){
            $this->_method[] = $method;
        }
    }

    public function submit()
    {

        $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';

        foreach($this->_uri as $key => $value){
            if(preg_match("#^$value$#",$uriGetParam)){
                if(is_string($this->_method[$key])){
                    $useMethod = $this->_method[$key];
                    new $useMethod();
                }
                else{
                    call_user_func($this->_method[$key]);
                }
            }
        }
    }

}

Body:
I didn't analyze your code thoroughly (I couldn't, not sure what is the example route / method you're adding with ->add), but the solution seems simple to me:

public function submit()
{

    $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
    $routeFound = false;
    foreach($this->_uri as $key => $value){
        if(preg_match("#^$value$#",$uriGetParam)){
            if(is_string($this->_method[$key])){
                $routeFound = true;
                $useMethod = $this->_method[$key];
                new $useMethod();
            }
            else{
                $routeFound = true;
                call_user_func($this->_method[$key]);
            }
        }
    }
    if(!$routeFound){
        http_response_code(404);
        echo 'ooooh, not found';
        //or:
        include('404.php');
        die();
    }
}

p.s. http_response_code is a built-in function:

https://secure.php.net/manual/en/function.http-response-code.php

edit: you could put the code starting with 'http_response_code(404);' to a separate function and just call it.


问:
Loading feature module from another Angular4 project
This is regarding Angular4 project setup.

Is it possible to load the feature module from another Angular4 project?

The approach I am trying was to keep the project repositories separate and load feature modules conditionally into the main project. So that the development will be isolated and independent.
Any insights into this or is there any other better approach?

答:
I have tried an approach creating the applications using nx.
ref: https://nrwl.io/nx/guide-getting-started </p>

<p>The library provides a set of code that you can import and use to simplify common patterns and functionality in the Angular applications. </p>

Body:
I have tried an approach creating the applications using nx.
ref: https://nrwl.io/nx/guide-getting-started

The library provides a set of code that you can import and use to simplify common patterns and functionality in the Angular applications.


问:
Dynamic variable in PHP [GET]
I'm trying to use the php get. everthing is working find exept the include page.
it's adding 1 at the end of include content
any ide how do i ride that?

example:

```<code>I love norway
I love norway1
</code>```

Code:

```<code><?php
if($_GET['boy'] == 'zabi') $zabkas =  'it is Zabi';
if($_GET['girl'] == 'veronka') $verona = 'It is veronka';
if($_GET['place'] == 'norway') $norge = include('norway.php');
?>

<?php echo $zabkas ?>
<?php echo $verona ?>
<?php echo $norge ?>
</code>```

答:
We should use file_get_contents, instead of include.

```<code>$norge = file_get_contents("norway.php");
</code>```

Title: Dynamic variable in PHP [GET]

Body:
I'm trying to use the php get. everthing is working find exept the include page.
it's adding 1 at the end of include content
any ide how do i ride that?

example:

I love norway
I love norway1

Code:

<?php
if($_GET['boy'] == 'zabi') $zabkas =  'it is Zabi';
if($_GET['girl'] == 'veronka') $verona = 'It is veronka';
if($_GET['place'] == 'norway') $norge = include('norway.php');
?>

<?php echo $zabkas ?>
<?php echo $verona ?>
<?php echo $norge ?>

Body:
We should use file_get_contents, instead of include.

$norge = file_get_contents("norway.php");