问:
/usr/bin/clang command failing trying to pip install TA-lib on MacOS
I'm trying pip install TA-lib and getting this log:

> pip install TA-lib
Collecting TA-lib
  Downloading TA-Lib-0.4.10.tar.gz (829kB)
    100% |████████████████████████████████| 839kB 822kB/s
Building wheels for collected packages: TA-lib
  Running setup.py bdist_wheel for TA-lib ... error
  Complete output from command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;__file__='/private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/tmpSTzWMxpip-wheel- --python-tag cp27:
  /private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py:77: UserWarning: Cannot find ta-lib library, installation may fail.
    warnings.warn('Cannot find ta-lib library, installation may fail.')
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.macosx-10.6-intel-2.7
  creating build/lib.macosx-10.6-intel-2.7/talib
  copying talib/__init__.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/deprecated.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/test_abstract.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/test_data.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/test_func.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/test_stream.py -> build/lib.macosx-10.6-intel-2.7/talib
  running build_ext
  building 'talib.common' extension
  creating build/temp.macosx-10.6-intel-2.7
  creating build/temp.macosx-10.6-intel-2.7/talib
  /usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include -I/usr/include -I/usr/local/include -I/opt/include -I/opt/local/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c talib/common.c -o build/temp.macosx-10.6-intel-2.7/talib/common.o
  talib/common.c:242:10: fatal error: 'ta-lib/ta_defs.h' file not found
  #include "ta-lib/ta_defs.h"
           ^
  1 error generated.
  error: command '/usr/bin/clang' failed with exit status 1

  ----------------------------------------

>   Failed building wheel for TA-lib   Running setup.py clean for TA-lib
> Failed to build TA-lib Installing collected packages: TA-lib   Running
> setup.py install for TA-lib ... error
>     Complete output from command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
> -u -c "import setuptools, tokenize;__file__='/private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py';f=getattr(tokenize,
> 'open', open)(__file__);code=f.read().replace('\r\n',
> '\n');f.close();exec(compile(code, __file__, 'exec'))" install
> --record /var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-lbZkZA-record/install-record.txt
> --single-version-externally-managed --compile:
>     /private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py:77:
> UserWarning: Cannot find ta-lib library, installation may fail.
>       warnings.warn('Cannot find ta-lib library, installation may fail.')
>     running install
>     running build
>     running build_py
>     creating build
>     creating build/lib.macosx-10.6-intel-2.7
>     creating build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/__init__.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/deprecated.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/test_abstract.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/test_data.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/test_func.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/test_stream.py -> build/lib.macosx-10.6-intel-2.7/talib
>     running build_ext
>     building 'talib.common' extension
>     creating build/temp.macosx-10.6-intel-2.7
>     creating build/temp.macosx-10.6-intel-2.7/talib
>     /usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
> -I/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include
> -I/usr/include -I/usr/local/include -I/opt/include -I/opt/local/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c talib/common.c -o build/temp.macosx-10.6-intel-2.7/talib/common.o
>     talib/common.c:242:10: fatal error: 'ta-lib/ta_defs.h' file not found
>     #include "ta-lib/ta_defs.h"
>              ^
>     1 error generated.
>     error: command '/usr/bin/clang' failed with exit status 1
>
>     ---------------------------------------- Command "/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
> -u -c "import setuptools, tokenize;__file__='/private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py';f=getattr(tokenize,
> 'open', open)(__file__);code=f.read().replace('\r\n',
> '\n');f.close();exec(compile(code, __file__, 'exec'))" install
> --record /var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-lbZkZA-record/install-record.txt
> --single-version-externally-managed --compile" failed with error code 1 in
> /private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/
```

I'm quite at noob at installing stuff.
There is some guidance here:

https://pypi.python.org/pypi/TA-Lib

but its for python3, and I have no experience in this kind of troubleshooting

答:
Please try:

```<code>brew install ta-lib
pip install numpy
pip install TA-lib
</code>```

source of information:
https://github.com/mrjbq7/ta-lib

Body:
I'm trying pip install TA-lib and getting this log:

> pip install TA-lib
Collecting TA-lib
  Downloading TA-Lib-0.4.10.tar.gz (829kB)
    100% |████████████████████████████████| 839kB 822kB/s
Building wheels for collected packages: TA-lib
  Running setup.py bdist_wheel for TA-lib ... error
  Complete output from command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c "import setuptools, tokenize;__file__='/private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/tmpSTzWMxpip-wheel- --python-tag cp27:
  /private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py:77: UserWarning: Cannot find ta-lib library, installation may fail.
    warnings.warn('Cannot find ta-lib library, installation may fail.')
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.macosx-10.6-intel-2.7
  creating build/lib.macosx-10.6-intel-2.7/talib
  copying talib/__init__.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/deprecated.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/test_abstract.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/test_data.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/test_func.py -> build/lib.macosx-10.6-intel-2.7/talib
  copying talib/test_stream.py -> build/lib.macosx-10.6-intel-2.7/talib
  running build_ext
  building 'talib.common' extension
  creating build/temp.macosx-10.6-intel-2.7
  creating build/temp.macosx-10.6-intel-2.7/talib
  /usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include -I/usr/include -I/usr/local/include -I/opt/include -I/opt/local/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c talib/common.c -o build/temp.macosx-10.6-intel-2.7/talib/common.o
  talib/common.c:242:10: fatal error: 'ta-lib/ta_defs.h' file not found
  #include "ta-lib/ta_defs.h"
           ^
  1 error generated.
  error: command '/usr/bin/clang' failed with exit status 1

  ----------------------------------------

>   Failed building wheel for TA-lib   Running setup.py clean for TA-lib
> Failed to build TA-lib Installing collected packages: TA-lib   Running
> setup.py install for TA-lib ... error
>     Complete output from command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
> -u -c "import setuptools, tokenize;__file__='/private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py';f=getattr(tokenize,
> 'open', open)(__file__);code=f.read().replace('\r\n',
> '\n');f.close();exec(compile(code, __file__, 'exec'))" install
> --record /var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-lbZkZA-record/install-record.txt
> --single-version-externally-managed --compile:
>     /private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py:77:
> UserWarning: Cannot find ta-lib library, installation may fail.
>       warnings.warn('Cannot find ta-lib library, installation may fail.')
>     running install
>     running build
>     running build_py
>     creating build
>     creating build/lib.macosx-10.6-intel-2.7
>     creating build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/__init__.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/deprecated.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/test_abstract.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/test_data.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/test_func.py -> build/lib.macosx-10.6-intel-2.7/talib
>     copying talib/test_stream.py -> build/lib.macosx-10.6-intel-2.7/talib
>     running build_ext
>     building 'talib.common' extension
>     creating build/temp.macosx-10.6-intel-2.7
>     creating build/temp.macosx-10.6-intel-2.7/talib
>     /usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes
> -I/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/include
> -I/usr/include -I/usr/local/include -I/opt/include -I/opt/local/include -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c talib/common.c -o build/temp.macosx-10.6-intel-2.7/talib/common.o
>     talib/common.c:242:10: fatal error: 'ta-lib/ta_defs.h' file not found
>     #include "ta-lib/ta_defs.h"
>              ^
>     1 error generated.
>     error: command '/usr/bin/clang' failed with exit status 1
>
>     ---------------------------------------- Command "/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
> -u -c "import setuptools, tokenize;__file__='/private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/setup.py';f=getattr(tokenize,
> 'open', open)(__file__);code=f.read().replace('\r\n',
> '\n');f.close();exec(compile(code, __file__, 'exec'))" install
> --record /var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-lbZkZA-record/install-record.txt
> --single-version-externally-managed --compile" failed with error code 1 in
> /private/var/folders/gm/z065gk616xg6g0xgn4c7_bvc0000gn/T/pip-build-z2UL44/TA-lib/

I'm quite at noob at installing stuff.
There is some guidance here:

https://pypi.python.org/pypi/TA-Lib

but its for python3, and I have no experience in this kind of troubleshooting

Body:
Please try:

brew install ta-lib
pip install numpy
pip install TA-lib

source of information:
https://github.com/mrjbq7/ta-lib


来源: stackexchange

问:
Unable to get values from the input fields using jquery
I have my handlebars file as

            <form class="form-horizontal well">

                    Username

                        <input type="text" class="form-control" placeholder="Username">

                    Password

                        <input type="password" class="form-control" placeholder="Password">

                        <button type="submit" class="btn btn-default" id="login">Sign in</button>

                    <button type="submit" class="btn btn-primary" id="register">Not a Member? Sign Up</button>

            </form>

```
</div>
</div>
</p>

<p>and my app.js as </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){

    /*Submit login form*/

    $("#login").on('click', function(){
        var user = $("form input[type=text]").val();
        var pass = $("form input[type=password]").val();

        var data = {
            username : user,
            password : pass
        };

        $.ajax({
            type : "POST",
            url : '/api/login',
            data : data
        });
    });
})</code>```

I am unable to use the values inside of the data object but when i try to do a simple alert using the user and pass values it alerts correct values but when doing a ajax call nothing is getting passed neither the user nor the pass inside the data object

答:
I think this will fix your problem :

```<code> $.ajax({
            type : "POST",
            dataType: "json",
            url : '/api/login',
            data : JSON.stringify(data)
        });
</code>```

Added dataType:"json" and data:JSON.stringify(data)

ContentLicense: CC BY-SA 3.0

Body:
I have my handlebars file as

            <form class="form-horizontal well">

                    Username

                        <input type="text" class="form-control" placeholder="Username">

                    Password

                        <input type="password" class="form-control" placeholder="Password">

                        <button type="submit" class="btn btn-default" id="login">Sign in</button>

                    <button type="submit" class="btn btn-primary" id="register">Not a Member? Sign Up</button>

            </form>

and my app.js as

$(document).ready(function(){

    /*Submit login form*/

    $("#login").on('click', function(){
        var user = $("form input[type=text]").val();
        var pass = $("form input[type=password]").val();

        var data = {
            username : user,
            password : pass
        };

        $.ajax({
            type : "POST",
            url : '/api/login',
            data : data
        });
    });
})

I am unable to use the values inside of the data object but when i try to do a simple alert using the user and pass values it alerts correct values but when doing a ajax call nothing is getting passed neither the user nor the pass inside the data object

Body:
I think this will fix your problem :

 $.ajax({
            type : "POST",
            dataType: "json",
            url : '/api/login',
            data : JSON.stringify(data)
        });

Added dataType:"json" and data:JSON.stringify(data)


问:
How to check if MediaPlayer is stopped?
The answer here
    How to check if mediaplayer is playing or stopped?
does not work to me.
It seems that MediaPlayer does not have the getState method.
Is this method depreciated?

Thanks,

答:
If you have troubles with re-starting the MediaPlayer after stopping it, then try this:

```<code>if (mMediaPlayer != null) {
    mMediaPlayer.stop();
    try {
        mMediaPlayer.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "IOException during prepare after stop! mMediaPlayer value: " + mMediaPlayer);
    }
}
</code>```

You basically prepare it for the next start. It worked for me.

Title: How to check if MediaPlayer is stopped?

Body:
If you have troubles with re-starting the MediaPlayer after stopping it, then try this:

if (mMediaPlayer != null) {
    mMediaPlayer.stop();
    try {
        mMediaPlayer.prepare();
    } catch (IOException e) {
        Log.e(LOG_TAG, "IOException during prepare after stop! mMediaPlayer value: " + mMediaPlayer);
    }
}

You basically prepare it for the next start. It worked for me.


问:
hibernate criteria filtering on a set of enum values
Hi I'm using Hibernate 3.2 with a 1.6 JDK and Mysql 5.0 I'm trying to use the criteria api to put together a dynamic filter.  However when I add a Restriction on a Set of Enums that is a property of my Criteria object I get a org.hibernate.exception.GenericJDBCException.

my code is like this:

```<code>public class FollowUp {
    ...
    public Set<AdminCategory> getAdminCategories() {...}
    public void setAdminCategories(Set<AdminCategory> _arg) { ... }

}
</code>```

My hibernate mapping file has a set of Enum values as specified in the hibernate documentation:
http://docs.jboss.org/hibernate/stable/core/reference/en/html/collections.html#collections-ofvalues.  The file (FollowUp.hbm.xml
) is like this

```<code><hibernate-mapping>
    <typedef class="dao.util.HibernateAdminCategoryType" name="main-category" />
    <class name="FollowUp" table="follow_up">
    <!-- other properties here -->
    <set name="mainCategories" table="follow_up_main_categories" fetch="join" lazy="false">
             <key column="fup_id"/>
             <element column="identifier" type="main-category"/>
     </set>
     <!-- other stuff -->
     </class>
</hibernate-mapping>
</code>```

the criteria filter code is like this:

```<code>public void runFilter(FollowUpFilter _filter) {
    Criteria criteria = this.getSession().createCriteria(FollowUp.class);
    if (_filter.hasMainCategories()) {
        criteria.add(Restrictions.in("mainCategories", _filter.getMainCategories()));
    }
    criteria.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );

    criteria.setProjection(Projections.rowCount());
    Integer count = (Integer) criteria.uniqueResult();
    _filter.setTotalSize(count);
}
</code>```

When I run my tests (with sql output) I get the following error:

```<code>Statement parameter 1 not set.
org.hibernate.exception.GenericJDBCException: could not execute query
</code>```

the sql output is as follows:

```<code>select
    count(*) as y0_
from
    follow_up this_
where
    this_.id in (
        ?
    )
</code>```

Does anyone know the correct way to filter on a set of enum values in a Criteria (in Hibernate 3.2)?

Cheers
Simon

答:
I looked at a few different pages including the following:

Including this one which looks like an elegant solution for folks using hibernate 3.5 or JPA 2.0 (with annotations):

Hibernate Criteria API - adding a criterion: string should be in collection

This one eventually pointed me to a solution:
https://forum.hibernate.org/viewtopic.php?f=1&t=942839&start=0

In the end I did a manual subselect, I'm not happy with it but it works.  I can't believe that this is the preferred solution but I couldn't find any other.   It's about as ugly as a solution can be and still warrant the name :-(

```<code>public void runFilter(AdminNoteFilter _filter) {
   assert _filter != null;
   Criteria criteria = this.getSession().createCriteria(FollowUp.class);
   if (_filter.hasMainCategories()) {
      CriteriaQueryTranslator cqt = null;

      Criterion mainCategoriesCriterion = HibernateFilterUtil.getEnumIdentifierCriterion(_filter.getMainCategories(),
         "{alias}.id in " +
         "(select fup.id " +
         "from follow_up fup, follow_up_main_categories v " +
         "where fup.id = v.fup_id and v.identifier in (" + HibernateFilterUtil.SUBSTITUE_QUESTION_MARKS + "))");
      criteria.add(mainCategoriesCriterion);

   }

   List<FollowUp> adminNotes = (List<FollowUp>) criteria.list();
}

/**
 * constructs a criterion for filtering on a collection of enums using a subselect.
 * <br />https://stackoverflow.com/questions/2967199/hibernate-criteria-filtering-on-a-set-of-enum-values
 * <br />https://forum.hibernate.org/viewtopic.php?f=1&t=942839&start=0
 *
 * @param _enums     non null non empty
 * @param _subSelect non null must contain the {@link #SUBSTITUE_QUESTION_MARKS} string to be substituted
 * @return the Criterion that can be added to a Criteria
 */
private static Criterion getEnumIdentifierCriterion(Set<? extends MarshallableEnum> _enums, String _subSelect) {
   assert _enums != null;
   assert _enums.size() > 0;
   assert _subSelect != null;
   assert _subSelect.contains(SUBSTITUE_QUESTION_MARKS);

   Set<String> identifiersSet = MarshallableEnumUtil.getIdentifiersFromMarshallableEnums(_enums);
   String[] identifiers = identifiersSet.toArray(Constants.EMPTY_STRING_ARRAY);

   // taken from
   //https://forum.hibernate.org/viewtopic.php?f=1&t=942839&start=0
   final org.hibernate.type.Type[] types = new org.hibernate.type.Type[identifiers.length];
   Arrays.fill(types, org.hibernate.Hibernate.STRING);

   final StringBuilder questionMarks = new StringBuilder();
   for (int i = 0; i < identifiers.length; i++) {
      if (i > 0) {
         questionMarks.append(",");
      }
      questionMarks.append("?");
   }
   // substitute in the question marks to the sub select subselect
   String finalSubSelect = _subSelect.replace(SUBSTITUE_QUESTION_MARKS, questionMarks);

   return Restrictions.sqlRestriction(finalSubSelect, identifiers, types);
}

private static Set<String> getIdentifiersFromMarshallableEnums(Set<? extends MarshallableEnum> _enums) {
   Set<String> retSet = new HashSet<String>();
   for (MarshallableEnum tmpEnum : _enums) {
      retSet.add(tmpEnum.getIdentifier());
   }
   return retSet;
}
</code>```

Hope this helps, if you anyone finds a better solution for the version of hibernate (3.2) please post it to help the community

Cheers
Simon

ContentLicense: CC BY-SA 2.5

Body:
Hi I'm using Hibernate 3.2 with a 1.6 JDK and Mysql 5.0 I'm trying to use the criteria api to put together a dynamic filter.  However when I add a Restriction on a Set of Enums that is a property of my Criteria object I get a org.hibernate.exception.GenericJDBCException.

my code is like this:

public class FollowUp {
    ...
    public Set<AdminCategory> getAdminCategories() {...}
    public void setAdminCategories(Set<AdminCategory> _arg) { ... }

}

My hibernate mapping file has a set of Enum values as specified in the hibernate documentation:
http://docs.jboss.org/hibernate/stable/core/reference/en/html/collections.html#collections-ofvalues.  The file (FollowUp.hbm.xml
) is like this

<hibernate-mapping>
    <typedef class="dao.util.HibernateAdminCategoryType" name="main-category" />
    <class name="FollowUp" table="follow_up">

    <set name="mainCategories" table="follow_up_main_categories" fetch="join" lazy="false">
             <key column="fup_id"/>
             <element column="identifier" type="main-category"/>
     </set>

     </class>
</hibernate-mapping>

the criteria filter code is like this:

public void runFilter(FollowUpFilter _filter) {
    Criteria criteria = this.getSession().createCriteria(FollowUp.class);
    if (_filter.hasMainCategories()) {
        criteria.add(Restrictions.in("mainCategories", _filter.getMainCategories()));
    }
    criteria.setResultTransformer( Criteria.DISTINCT_ROOT_ENTITY );

    criteria.setProjection(Projections.rowCount());
    Integer count = (Integer) criteria.uniqueResult();
    _filter.setTotalSize(count);
}

When I run my tests (with sql output) I get the following error:

Statement parameter 1 not set.
org.hibernate.exception.GenericJDBCException: could not execute query

the sql output is as follows:

select
    count(*) as y0_
from
    follow_up this_
where
    this_.id in (
        ?
    )

Does anyone know the correct way to filter on a set of enum values in a Criteria (in Hibernate 3.2)?

Cheers
Simon

Body:
I looked at a few different pages including the following:

Including this one which looks like an elegant solution for folks using hibernate 3.5 or JPA 2.0 (with annotations):

Hibernate Criteria API - adding a criterion: string should be in collection

This one eventually pointed me to a solution:
https://forum.hibernate.org/viewtopic.php?f=1&t=942839&start=0

In the end I did a manual subselect, I'm not happy with it but it works.  I can't believe that this is the preferred solution but I couldn't find any other.   It's about as ugly as a solution can be and still warrant the name :-(

public void runFilter(AdminNoteFilter _filter) {
   assert _filter != null;
   Criteria criteria = this.getSession().createCriteria(FollowUp.class);
   if (_filter.hasMainCategories()) {
      CriteriaQueryTranslator cqt = null;

      Criterion mainCategoriesCriterion = HibernateFilterUtil.getEnumIdentifierCriterion(_filter.getMainCategories(),
         "{alias}.id in " +
         "(select fup.id " +
         "from follow_up fup, follow_up_main_categories v " +
         "where fup.id = v.fup_id and v.identifier in (" + HibernateFilterUtil.SUBSTITUE_QUESTION_MARKS + "))");
      criteria.add(mainCategoriesCriterion);

   }

   List<FollowUp> adminNotes = (List<FollowUp>) criteria.list();
}

/**
 * constructs a criterion for filtering on a collection of enums using a subselect.
 * <br />https://stackoverflow.com/questions/2967199/hibernate-criteria-filtering-on-a-set-of-enum-values
 * <br />https://forum.hibernate.org/viewtopic.php?f=1&t=942839&start=0
 *
 * @param _enums     non null non empty
 * @param _subSelect non null must contain the {@link #SUBSTITUE_QUESTION_MARKS} string to be substituted
 * @return the Criterion that can be added to a Criteria
 */
private static Criterion getEnumIdentifierCriterion(Set<? extends MarshallableEnum> _enums, String _subSelect) {
   assert _enums != null;
   assert _enums.size() > 0;
   assert _subSelect != null;
   assert _subSelect.contains(SUBSTITUE_QUESTION_MARKS);

   Set<String> identifiersSet = MarshallableEnumUtil.getIdentifiersFromMarshallableEnums(_enums);
   String[] identifiers = identifiersSet.toArray(Constants.EMPTY_STRING_ARRAY);

   // taken from
   //https://forum.hibernate.org/viewtopic.php?f=1&t=942839&start=0
   final org.hibernate.type.Type[] types = new org.hibernate.type.Type[identifiers.length];
   Arrays.fill(types, org.hibernate.Hibernate.STRING);

   final StringBuilder questionMarks = new StringBuilder();
   for (int i = 0; i < identifiers.length; i++) {
      if (i > 0) {
         questionMarks.append(",");
      }
      questionMarks.append("?");
   }
   // substitute in the question marks to the sub select subselect
   String finalSubSelect = _subSelect.replace(SUBSTITUE_QUESTION_MARKS, questionMarks);

   return Restrictions.sqlRestriction(finalSubSelect, identifiers, types);
}

private static Set<String> getIdentifiersFromMarshallableEnums(Set<? extends MarshallableEnum> _enums) {
   Set<String> retSet = new HashSet<String>();
   for (MarshallableEnum tmpEnum : _enums) {
      retSet.add(tmpEnum.getIdentifier());
   }
   return retSet;
}

Hope this helps, if you anyone finds a better solution for the version of hibernate (3.2) please post it to help the community

Cheers
Simon


问:
Sort date list dynamically with dates matching today's date always at top of list
Would really appreciate your help.
Have a list of dates for deliveries ahead of time. Would like when sheet is select deliveries expected for today is show at the top of the date list. So the list dynamically reorders every day putting expected deliveries matching today's date at the top. Nothing working for me. Thanks.

```<code>    Sub todaysList()

If ActiveSheet.FilterMode = False Then
Range("G2").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$M$4").AutoFilter Field:=7, Criteria1:= _
    xlFilterToday, Operator:=xlFilterDynamic
Else
    Selection.AutoFilter

End If

End Sub
</code>```

Amended Code: --- Good, but still does not sort dates so dates matching today's date are move to the top of the list of dates. Left the else statement in because it allows the button with the Macro attached to function as the filter and also as a switch to turn the filter on and off when clicked a second time.

```<code>Sub todaysList()
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("RECEIPTING")

If ws.AutoFilter Is Nothing Then
    Range("G2").Select
    Selection.AutoFilter
    ActiveSheet.Range("$A$1:$M$4").AutoFilter Field:=7, _
    Criteria1:=xlFilterToday, _
    Operator:=xlFilterDynamic
Else
    ws.UsedRange.AutoFilter

End If

End Sub
</code>```

答:
I CRACKED IT!!!. There are a few things you need to setup first.

Create a Column on the sheet containing your dates which you can leave visible or hide (your choice) - Call it what you like, mine is called  'Prioritiser'.

In this column you want to store the results the 'date in your date column - today's date' i.e. 'Date' function.
  If the date has passed the result will be a negative number.
  If the date is equal to today's date the result will be 0.
  If the date is ahead i.e. in the future the result will be a positive number.

The code explained:-

A: I perform a Row count.

B: I loop through each records date with a For Next
     loop starting at Row 2 (below the header).

C: For Dates records past
  and future I record a '0' in the 'Prioritiser' Column

D: For dates matching today's date I record a '1'

E: I then run a sort filter on the 'Prioritise' column putting all the 1s at the top of the list

F: I attach the code the worksheet's 'Active' state

Result:

Every time the sheet is selected dates matching the current day will be moved to the top.

I'm sure you guys can refine the code making it slicker and more
  efficient. Keep well and enjoy.

HERE IT IS:

```<code>Private Sub Worksheet_Activate()

Dim ws As Worksheet

Dim C1 As Long
Dim rowCount, I As Integer

Set ws = Sheets("RECEIPTING")
rowCount = ws.Range("A" & Rows.Count).End(xlUp).Row

For I = 2 To rowCount
    C1 = ws.Range("G" & I).Value - Date
        If C1 = 0 Then
            ws.Range("N" & I) = 1
        Else
            ws.Range("N" & I) = 0
        End If
Next I

If ws.AutoFilter Is Nothing Then
    Range("N2").Select
    Selection.AutoFilter
    ws.AutoFilter.Sort.SortFields.Add Key:=Range("N2"), _
    SortOn:=xlSortOnValues, _
    Order:=xlDescending, _
    DataOption:=xlSortNormal

    With ActiveWorkbook.Worksheets("RECEIPTING").AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    ws.UsedRange.AutoFilter

Else
    ws.UsedRange.AutoFilter

End If

End Sub
</code>```

Blockquote

Body:
Would really appreciate your help.
Have a list of dates for deliveries ahead of time. Would like when sheet is select deliveries expected for today is show at the top of the date list. So the list dynamically reorders every day putting expected deliveries matching today's date at the top. Nothing working for me. Thanks.

    Sub todaysList()

If ActiveSheet.FilterMode = False Then
Range("G2").Select
Selection.AutoFilter
ActiveSheet.Range("$A$1:$M$4").AutoFilter Field:=7, Criteria1:= _
    xlFilterToday, Operator:=xlFilterDynamic
Else
    Selection.AutoFilter

End If

End Sub

Amended Code: --- Good, but still does not sort dates so dates matching today's date are move to the top of the list of dates. Left the else statement in because it allows the button with the Macro attached to function as the filter and also as a switch to turn the filter on and off when clicked a second time.

Sub todaysList()
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("RECEIPTING")

If ws.AutoFilter Is Nothing Then
    Range("G2").Select
    Selection.AutoFilter
    ActiveSheet.Range("$A$1:$M$4").AutoFilter Field:=7, _
    Criteria1:=xlFilterToday, _
    Operator:=xlFilterDynamic
Else
    ws.UsedRange.AutoFilter

End If

End Sub

Body:
I CRACKED IT!!!. There are a few things you need to setup first.

Create a Column on the sheet containing your dates which you can leave visible or hide (your choice) - Call it what you like, mine is called  'Prioritiser'.

In this column you want to store the results the 'date in your date column - today's date' i.e. 'Date' function.
  If the date has passed the result will be a negative number.
  If the date is equal to today's date the result will be 0.
  If the date is ahead i.e. in the future the result will be a positive number.

The code explained:-

A: I perform a Row count.

B: I loop through each records date with a For Next
     loop starting at Row 2 (below the header).

C: For Dates records past
  and future I record a '0' in the 'Prioritiser' Column

D: For dates matching today's date I record a '1'

E: I then run a sort filter on the 'Prioritise' column putting all the 1s at the top of the list

F: I attach the code the worksheet's 'Active' state

Result:

Every time the sheet is selected dates matching the current day will be moved to the top.

I'm sure you guys can refine the code making it slicker and more
  efficient. Keep well and enjoy.

HERE IT IS:

Private Sub Worksheet_Activate()

Dim ws As Worksheet

Dim C1 As Long
Dim rowCount, I As Integer

Set ws = Sheets("RECEIPTING")
rowCount = ws.Range("A" & Rows.Count).End(xlUp).Row

For I = 2 To rowCount
    C1 = ws.Range("G" & I).Value - Date
        If C1 = 0 Then
            ws.Range("N" & I) = 1
        Else
            ws.Range("N" & I) = 0
        End If
Next I

If ws.AutoFilter Is Nothing Then
    Range("N2").Select
    Selection.AutoFilter
    ws.AutoFilter.Sort.SortFields.Add Key:=Range("N2"), _
    SortOn:=xlSortOnValues, _
    Order:=xlDescending, _
    DataOption:=xlSortNormal

    With ActiveWorkbook.Worksheets("RECEIPTING").AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    ws.UsedRange.AutoFilter

Else
    ws.UsedRange.AutoFilter

End If

End Sub

Blockquote


问:
Spring controller that will accept (XML/BASE64) and return XML with jackson support
I'm creating a spring based web application(Spring,jackson and hibernate) that will accept XML/BASE64 input as request message and after processing the response will be XML message. Application will have different controllers to accept BASE64/XML message.

Client ---(BASE64/XML)-->Server---->XML--->Client

I need to know how to implement two different controller and can read the XML from the client. Since it is a web application, which will get input message based on client request. Request XML messages contains optional tags which may/may not be present. I need to know is it good to create the application as a spring web service(Please guide me with proper sample links) or like a normal web application that will read data from the input stream.

My client programs which will open a url connection, open stream writes the data and will wait for the server to write response back to stream.

```<code>@Controller
@RequestMapping("/employee")
public class EmployeeController {

   //Function to take request and response as XML
    @RequestMapping(value = "/allEmployyes", method = RequestMethod.POST)
    public @ResponseBody EmployeesStatus readAllEmployeeDetails() {
    }

   //Function to take request as BASE64 and reply as XML
    @RequestMapping(value = "/empProfile", method = RequestMethod.POST)
    public @ResponseBody ProfileStatus updateEmployeeProfilePic() {
    }
 }
</code>```

Please help me to create a better solution for the requirement(Expecting practical solutions from experienced Spring professionals).

答:
I think to solve this can use the method like below
```</p>

<p>```</p>

<p>and change the controller to
```</p>

```<code>//Function to take request and response as XML
@RequestMapping(value = "/allEmployyes", method = RequestMethod.POST)
public void EmployeesStatus readAllEmployeeDetails(HttpServletResponse response) {
      ...
  ObjectMapper mapper = new XmlMapper();
  String xmlStr =  xmlMapper.writeValueAsString(someresult);
  try {
         response.getWriter().write(xmlStr);
      } catch (IOException e) {
         log.error("Io Exception!",e);
      }
}
</code>```

<p>```</p>

Body:
I'm creating a spring based web application(Spring,jackson and hibernate) that will accept XML/BASE64 input as request message and after processing the response will be XML message. Application will have different controllers to accept BASE64/XML message.

Client ---(BASE64/XML)-->Server---->XML--->Client

I need to know how to implement two different controller and can read the XML from the client. Since it is a web application, which will get input message based on client request. Request XML messages contains optional tags which may/may not be present. I need to know is it good to create the application as a spring web service(Please guide me with proper sample links) or like a normal web application that will read data from the input stream.

My client programs which will open a url connection, open stream writes the data and will wait for the server to write response back to stream.

@Controller
@RequestMapping("/employee")
public class EmployeeController {

   //Function to take request and response as XML
    @RequestMapping(value = "/allEmployyes", method = RequestMethod.POST)
    public @ResponseBody EmployeesStatus readAllEmployeeDetails() {
    }

   //Function to take request as BASE64 and reply as XML
    @RequestMapping(value = "/empProfile", method = RequestMethod.POST)
    public @ResponseBody ProfileStatus updateEmployeeProfilePic() {
    }
 }

Please help me to create a better solution for the requirement(Expecting practical solutions from experienced Spring professionals).

Body:
I think to solve this can use the method like below
```</p>

<p>```

and change the controller to
```</p>

<pre><code>//Function to take request and response as XML
@RequestMapping(value = "/allEmployyes", method = RequestMethod.POST)
public void EmployeesStatus readAllEmployeeDetails(HttpServletResponse response) {
      ...
  ObjectMapper mapper = new XmlMapper();
  String xmlStr =  xmlMapper.writeValueAsString(someresult);
  try {
         response.getWriter().write(xmlStr);
      } catch (IOException e) {
         log.error("Io Exception!",e);
      }
}
</code></pre>

<p>```


问:
Creating a binary tree through a loop
I want to create a binary tree by iterating through a loop. I know how to write a very basic binary tree.

```<code>class Tree(object):
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None

root = Tree()
root.data = 75
root.left = Tree()
root.left.data = 95
root.right = Tree()
root.right.data = 64

root.left.left = Tree()
root.left.left.data = 32
root.left.right = Tree()
root.left.right.data = 93
root.left.left = Tree()
root.right.left.data = 32
root.left.right = Tree()
root.right.right.data = 93

print(root.data)
</code>```

This is tedious handtyping it, and if I were to have a list of numbers:

```<code>list = [1,2,3,4,5,6,7]
</code>```

and put it through a loop to create a binary tree in this order so:

```<code>   1
 2   3
4 5 6 7
</code>```

How would I write that? and because I'm using this to calculate the sum of all the paths, how do you navigate/iterate through a binary tree:

答:
To build a full binary tree (not necessarily a binary search tree) from a list of node values, let's assume values in the list are ordered according to level-order traversal. So, a list from your question

```<code>values = [1,2,3,4,5,6,7]
</code>```

will represent a tree:

```<code>   1
 2   3
4 5 6 7
</code>```

Notice that the root value is at the position 0, its left child is at the position 1*2-1=1, the right child at 1*2=2, etc. In general for a node in the list at index i, its left child is at position (i+1)*2-1, and the right child at (i+1)*2.

Now, we simply need to build the tree recursively, node by node, at each step creating the left and the right subtree.

To make it simpler, let's assume the list of values is global.

```<code>class Node(object):
    def __init__(self, data=None, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

def buildTree(i):
    if i < len(values):
        return Node(values[i], left=buildTree((i+1)*2-1), right=buildTree((i+1)*2))

values = [1,2,3,4,5,6,7]
tree = buildTree(0)
</code>```

To print-out the tree, we can use the preorder tree traversal:

```<code>def preorder(node):
    if node is None:
        return
    yield node.data
    for v in preorder(node.left):
        yield v
    for v in preorder(node.right):
        yield v
</code>```

Like this:

```<code>>>> print list(preorder(tree))
[1, 2, 4, 5, 3, 6, 7]
</code>```

Title: Creating a binary tree through a loop

Body:
I want to create a binary tree by iterating through a loop. I know how to write a very basic binary tree.

class Tree(object):
    def __init__(self):
        self.left = None
        self.right = None
        self.data = None

root = Tree()
root.data = 75
root.left = Tree()
root.left.data = 95
root.right = Tree()
root.right.data = 64

root.left.left = Tree()
root.left.left.data = 32
root.left.right = Tree()
root.left.right.data = 93
root.left.left = Tree()
root.right.left.data = 32
root.left.right = Tree()
root.right.right.data = 93

print(root.data)

This is tedious handtyping it, and if I were to have a list of numbers:

list = [1,2,3,4,5,6,7]

and put it through a loop to create a binary tree in this order so:

   1
 2   3
4 5 6 7

How would I write that? and because I'm using this to calculate the sum of all the paths, how do you navigate/iterate through a binary tree:

Body:
To build a full binary tree (not necessarily a binary search tree) from a list of node values, let's assume values in the list are ordered according to level-order traversal. So, a list from your question

values = [1,2,3,4,5,6,7]

will represent a tree:

   1
 2   3
4 5 6 7

Notice that the root value is at the position 0, its left child is at the position 1*2-1=1, the right child at 1*2=2, etc. In general for a node in the list at index i, its left child is at position (i+1)*2-1, and the right child at (i+1)*2.

Now, we simply need to build the tree recursively, node by node, at each step creating the left and the right subtree.

To make it simpler, let's assume the list of values is global.

class Node(object):
    def __init__(self, data=None, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

def buildTree(i):
    if i < len(values):
        return Node(values[i], left=buildTree((i+1)*2-1), right=buildTree((i+1)*2))

values = [1,2,3,4,5,6,7]
tree = buildTree(0)

To print-out the tree, we can use the preorder tree traversal:

def preorder(node):
    if node is None:
        return
    yield node.data
    for v in preorder(node.left):
        yield v
    for v in preorder(node.right):
        yield v

Like this:

>>> print list(preorder(tree))
[1, 2, 4, 5, 3, 6, 7]


问:
"this" captured by lambda is incorrect. GCC compiler bug?
For the last few days, I have been debugging a weird issue involving lambdas in C++. I have reduced the problem down to the following symptoms:

The this pointer gets corrupted inside a lambda (note: this is always captured by copy, so the lambda should get its own this pointer, which points to the App object)

It only occurs if a std::cout print statement is present, and called before the lambda is created. The print statement can be seemingly completely unrelated (e.g. print "Hello!"). printf() also exhibits the same behaviour.

It only occurs when cross-compiling.

It compiles and runs fine with the standard compiler for x86 architecture (see example).

If I create the lambda on the heap (and save a pointer to it inside the App object), the bug does not occur.

The bug does not occur if optimizations are turned off (i.e. if I set the -O0 flag). It occurs when optimization is set to -O2.

The following is the simplest, compilable code example I could come up with that causes the problem.

```<code>#include <iostream>
#include <functional>

class App {

public:

    std::function<void*()> test_;

    void Run() {

        // Enable this line, ERROR is printed
        // Disable this line, app runs o.k.
        std::cout << "This print statement causes the bug below!" << std::endl;

        test_ = [this] () {
            return this;
        };

        void* returnedThis = test_();
        if(returnedThis != this) {
            std::cout << "ERROR: 'this' returned from lambda (" << returnedThis
                      << ") is NOT the same as 'this' (" << this << ") !?!?!?!?!"
                      << std::endl;
        } else {
            std::cout << "Program run successfully." << std::endl;
        }

    }
};

int main(void) {
    App app;
    app.Run();
}
</code>```

When running on the target device, I get the following output:

```<code>This print statement causes the bug below!
ERROR: 'this' returned from lambda (0xbec92dd4) is NOT the same as 'this'
(0xbec92c68) !?!?!?!?!
</code>```

If I try and dereference the corrupted this, I usually get a segmentation fault, which is how I discovered the bug in the first place.

Compiler Settings

```<code>arm-poky-linux-gnueabi-g++ -march=armv7-a -marm -mfpu=neon -std=c++14 \
-mfloat-abi=hard -mcpu=cortex-a9 \
--sysroot=/home/ghunter/sysroots/cortexa9hf-neon-poky-linux-gnueabi \
-O2 -pipe -g -feliminate-unused-debug-types
</code>```

Linker Settings

```<code>arm-poky-linux-gnueabi-ld \
--sysroot=/home/ghunter/sysroots/cortexa9hf-neon-poky-linux-gnueabi \
-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed
</code>```

Compiler Version

```<code>~$ arm-poky-linux-gnueabi-g++ --version

arm-poky-linux-gnueabi-g++ (GCC) 6.2.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code>```

Could this be a compiler bug?

答: Sounds like the following compiler bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77933  (which only effects code generated with O1 optimizations or higher).</p>

Body:
For the last few days, I have been debugging a weird issue involving lambdas in C++. I have reduced the problem down to the following symptoms:

The this pointer gets corrupted inside a lambda (note: this is always captured by copy, so the lambda should get its own this pointer, which points to the App object)

It only occurs if a std::cout print statement is present, and called before the lambda is created. The print statement can be seemingly completely unrelated (e.g. print "Hello!"). printf() also exhibits the same behaviour.

It only occurs when cross-compiling.

It compiles and runs fine with the standard compiler for x86 architecture (see example).

If I create the lambda on the heap (and save a pointer to it inside the App object), the bug does not occur.

The bug does not occur if optimizations are turned off (i.e. if I set the -O0 flag). It occurs when optimization is set to -O2.

The following is the simplest, compilable code example I could come up with that causes the problem.

#include <iostream>
#include <functional>

class App {

public:

    std::function<void*()> test_;

    void Run() {

        // Enable this line, ERROR is printed
        // Disable this line, app runs o.k.
        std::cout << "This print statement causes the bug below!" << std::endl;

        test_ = [this] () {
            return this;
        };

        void* returnedThis = test_();
        if(returnedThis != this) {
            std::cout << "ERROR: 'this' returned from lambda (" << returnedThis
                      << ") is NOT the same as 'this' (" << this << ") !?!?!?!?!"
                      << std::endl;
        } else {
            std::cout << "Program run successfully." << std::endl;
        }

    }
};

int main(void) {
    App app;
    app.Run();
}

When running on the target device, I get the following output:

This print statement causes the bug below!
ERROR: 'this' returned from lambda (0xbec92dd4) is NOT the same as 'this'
(0xbec92c68) !?!?!?!?!

If I try and dereference the corrupted this, I usually get a segmentation fault, which is how I discovered the bug in the first place.

Compiler Settings

arm-poky-linux-gnueabi-g++ -march=armv7-a -marm -mfpu=neon -std=c++14 \
-mfloat-abi=hard -mcpu=cortex-a9 \
--sysroot=/home/ghunter/sysroots/cortexa9hf-neon-poky-linux-gnueabi \
-O2 -pipe -g -feliminate-unused-debug-types

Linker Settings

arm-poky-linux-gnueabi-ld \
--sysroot=/home/ghunter/sysroots/cortexa9hf-neon-poky-linux-gnueabi \
-Wl,-O1 -Wl,--hash-style=gnu -Wl,--as-needed

Compiler Version

~$ arm-poky-linux-gnueabi-g++ --version

arm-poky-linux-gnueabi-g++ (GCC) 6.2.0
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Could this be a compiler bug?


问:
Inserting MySQL data from PHP API
I am creating an API in PHP and I am stuck at a point where I need same data of one table into another.

In table one, the order ID is created by auto increment. I want to copy its order ID into the 2nd table order ID:

So a customer can add multiple items in same order:

答:
I'm not sure if I understand your problem correctly. Are you asking how you can move data between two tables? Because if that's so, it's quite simple to do:

Let's suppose you want to move a record from table foo to table bar, you can use the query:

```<code>INSERT INTO `bar` (SELECT * FROM `foo` WHERE id = $some_id)
</code>```

Where $some_id is the ID of the record you want to move.

But again, your question wasn't very clear, so apologies if this isn't what you were trying to do.

Title: Inserting MySQL data from PHP API

Body:
I'm not sure if I understand your problem correctly. Are you asking how you can move data between two tables? Because if that's so, it's quite simple to do:

Let's suppose you want to move a record from table foo to table bar, you can use the query:

INSERT INTO `bar` (SELECT * FROM `foo` WHERE id = $some_id)

Where $some_id is the ID of the record you want to move.

But again, your question wasn't very clear, so apologies if this isn't what you were trying to do.


问:
Authorization in spring-security based on path variables
My use case is to authenticate & then authorize users based on @PathVariable parameters. I need to execute some custom code to authorize the principal. I'm not sure of the approach to take here -

I have implemented a custom AbstractAuthenticationProcessingFilter & AuthenticationProvider for authentication, which ends up granting roles to the principal. I can inspect the pathvariables in the servlet request (using HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE), and add additional authorities to the Authentication token. Then I can use the built-in hasRole, hasPermission expressions to implement access control.

I can extend WebSecurityExpressionRoot and implement a custom AbstractSecurityExpressionHandler and define my own expressions to be used in the intercept-url access-control expressions. I'm not sure how I can access the @PathVariables when defining custom methods in my WebSecurityExpressionRoot implementation.

Which approach is preferable, or is there another way to do this cleanly?

答:
I do have a solution.
In a configuration class

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
</code>```

I could have method

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/student/{id}/**")
            .access("@guard.checkUserId(authentication,#id)");
}
</code>```

while @guard in SpEL links to

```<code>@Component
public class Guard {
    @Autowired
    private UserRepository repo;

    public boolean checkUserId(Authentication authentication, int id) {
        String name = authentication.getName();
        System.out.println(name+" at "+id);
        User result = repo.findByUsername(name);
        return result != null && result.getPid() == id;
    }
}
</code>```

In practice, the #id in SpEL can get the value extracted from {id} in the previous line. You can do whatever you want in checkUserId, and the return value decides whether the access to the path would be allowed.

Body:
I do have a solution.
In a configuration class

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter

I could have method

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/student/{id}/**")
            .access("@guard.checkUserId(authentication,#id)");
}

while @guard in SpEL links to

@Component
public class Guard {
    @Autowired
    private UserRepository repo;

    public boolean checkUserId(Authentication authentication, int id) {
        String name = authentication.getName();
        System.out.println(name+" at "+id);
        User result = repo.findByUsername(name);
        return result != null && result.getPid() == id;
    }
}

In practice, the #id in SpEL can get the value extracted from {id} in the previous line. You can do whatever you want in checkUserId, and the return value decides whether the access to the path would be allowed.


问:
MiniZinc can not find a solution when output statement introduced
I have a simple model written in minizinc and I use gecode to solve it by compiling it into flat-zinc first. As an input, the model takes some constants, arrays, and matrices (in the form of 2-dimensional arrays). The output of the model is another 2d matrix that has to satisfy some constraints.

Target optimization is to minimize the value of "target" which is a particular function of the output matrix and defined as following:

```<code>var float: target = sum(i in 1..nodes, j in 1..nodes) (F(i, j) * output_matrix[i, j]);
solve minimize target;
</code>```

When I execute this model as follows:

```<code>mzn2fzn model.mzn model.dzn
fzn-gecode -a model.fzn
</code>```

I can see a stream of possible solutions with the last one in the list to be the optimal. However, if I add an output statement into the model to print the value of the "target" variable - gecode hangs for hours without finding any solutions at all and prints ==UNKNOWN== if interrupted.

```<code>output [
"target: ", show(target), "\n"
];
</code>```

Is this is an expected behavior, if so, could you explain why?

Cheers

答: output [ "target: " ++ show(target) ++ "\n"];</p>

Body:
I have a simple model written in minizinc and I use gecode to solve it by compiling it into flat-zinc first. As an input, the model takes some constants, arrays, and matrices (in the form of 2-dimensional arrays). The output of the model is another 2d matrix that has to satisfy some constraints.

Target optimization is to minimize the value of "target" which is a particular function of the output matrix and defined as following:

var float: target = sum(i in 1..nodes, j in 1..nodes) (F(i, j) * output_matrix[i, j]);
solve minimize target;

When I execute this model as follows:

mzn2fzn model.mzn model.dzn
fzn-gecode -a model.fzn

I can see a stream of possible solutions with the last one in the list to be the optimal. However, if I add an output statement into the model to print the value of the "target" variable - gecode hangs for hours without finding any solutions at all and prints ==UNKNOWN== if interrupted.

output [
"target: ", show(target), "\n"
];

Is this is an expected behavior, if so, could you explain why?

Cheers


问:
Excel Vlookup Formula required from pivoted data
I have a simple data table from a pivot table in the following format:

```<code> A                          B           C            D
 Names                      Dog         Cat          Horse
 John Smith                 1           1            0
 Jane Smith                 0           0            0
 Jane Dow                   0           1            0
 John Dow                   1           1            1
</code>```

I want to use a formula to populate another table using the one above. The second table has a different ordering to it. For example Horse is in Column B instead of D and John Smith is on Row 5 instead of 1.

```<code> A                          B           C            D
 Names                      Horse       Cat          Dog
 John Dow                   ?
 Jane Smith
 Jane Dow
 John Smith
</code>```

What is the best formula to use given these circumstances, I do not think a Vlookup/hlookup will work because it is dependent on both horizontal and vertical variables.

答: A much more robust solution is to use the GETPIVOTDATA function...it does exactly what you are asking in your question, and users can radically change the layout of the PivotTable without the formula breaking.

Body:
I have a simple data table from a pivot table in the following format:

 A                          B           C            D
 Names                      Dog         Cat          Horse
 John Smith                 1           1            0
 Jane Smith                 0           0            0
 Jane Dow                   0           1            0
 John Dow                   1           1            1

I want to use a formula to populate another table using the one above. The second table has a different ordering to it. For example Horse is in Column B instead of D and John Smith is on Row 5 instead of 1.

 A                          B           C            D
 Names                      Horse       Cat          Dog
 John Dow                   ?
 Jane Smith
 Jane Dow
 John Smith

What is the best formula to use given these circumstances, I do not think a Vlookup/hlookup will work because it is dependent on both horizontal and vertical variables.


问:
BeautifulSoup
 scraping suddenly stopped working
I am trying to scrape some divs from a NASA website and put all the contents in a list. THIS CODE WAS WORKING EARLIER and has suddenly decided not to. I didn't change anything knowingly except to add some print statements, all of which return nothing or [] with no error of any kind.

```<code>import re
import urllib2
from BeautifulSoup import BeautifulSoup as soup
import ssl

url = "https://climate.nasa.gov"
context = ssl._create_unverified_context()
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
web_soup = soup(urllib2.urlopen(url,  context=context))

l = []

# get main-content div
main_div = web_soup.findAll(name="div", attrs={'class': 'change_number'})
print main_div
for element in main_div:
    print element
    l.append(float(str(element)[27:-7]))

print l
</code>```

Any help with pinpointing this sudden error would be greatly appreciated!

UPDATE1: Just tried it in the interpreter, fails in the same way. main_div seems to be returning [].

UPDATE2: Just checked the website to ensure that the div change_number exists. It does.

UPDATE3: Now I am really confused. I have this code, which I am pretty sure is basically identical to the one above:

```<code>import re
import urllib2
from BeautifulSoup import BeautifulSoup as soup
import ssl

url = "https://climate.nasa.gov"
context = ssl._create_unverified_context()
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
web_soup = soup(urllib2.urlopen(url,  context=context))

l = []

# get main-content div
main_div = web_soup.findAll(name="div", attrs={'class': 'change_number'})
for element in main_div:
    print element
    l.append(float(str(element)[27:-7]))

print l
</code>```

But it is throwing a UnicodeEncodeError on the websoup definition line:

```<code>Traceback (most recent call last):
  File "climate_nasa_change.py", line 10, in <module>
    web_soup = soup(urllib2.urlopen(url,  context=context))
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1522, in __init__
    BeautifulStoneSoup.__init__(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1147, in __init__
    self._feed(isHTML=isHTML)
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1189, in _feed
    SGMLParser.feed(self, markup)
  File "C:\Python27\lib\sgmllib.py", line 104, in feed
    self.goahead(0)
  File "C:\Python27\lib\sgmllib.py", line 143, in goahead
    k = self.parse_endtag(i)
  File "C:\Python27\lib\sgmllib.py", line 320, in parse_endtag
    self.finish_endtag(tag)
  File "C:\Python27\lib\sgmllib.py", line 358, in finish_endtag
    method = getattr(self, 'end_' + tag)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 11-12: ordinal not in range(128)
</code>```

UPDATE4: aaaaaaaaaaaaaand now its magically working. I really have no idea what the hell is going on right now.

UPDATE5: and now its broken. I swear I am not changing. Seriously considering exorcising my computer. Please help.

UPDATE6: Just tried pinging climate.nasa.gov. It doesn't always go through, despite the page consistently loading in my browser. Could this be causing BeautifulSoup to fail?

答:
The problem is that the site sometimes returns a gzip encoded response and other times plaintext.

You can resolve this easily if you use requests , as it decodes the content automatically :

```<code>web_soup = soup(requests.get(url, verify=False).text)
</code>```

Note that requests is not a standard lib, you have to install it.

If you insist on using urllib2 you can decode the response with zlib if it's encoded :

```<code>decode = lambda response : zlib.decompress(response, 16 + zlib.MAX_WBITS)
response = urllib2.urlopen(url,  context=context)
headers = response.info()
html = decode(response.read()) if headers.get('content-encoding') == 'gzip' else response
web_soup = soup(html)
</code>```

Title: BeautifulSoup </div> scraping suddenly stopped working

Body:
I am trying to scrape some divs from a NASA website and put all the contents in a list. THIS CODE WAS WORKING EARLIER and has suddenly decided not to. I didn't change anything knowingly except to add some print statements, all of which return nothing or [] with no error of any kind.

import re
import urllib2
from BeautifulSoup import BeautifulSoup as soup
import ssl

url = "https://climate.nasa.gov"
context = ssl._create_unverified_context()
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
web_soup = soup(urllib2.urlopen(url,  context=context))

l = []

# get main-content div
main_div = web_soup.findAll(name="div", attrs={'class': 'change_number'})
print main_div
for element in main_div:
    print element
    l.append(float(str(element)[27:-7]))

print l

Any help with pinpointing this sudden error would be greatly appreciated!

UPDATE1: Just tried it in the interpreter, fails in the same way. main_div seems to be returning [].

UPDATE2: Just checked the website to ensure that the div change_number exists. It does.

UPDATE3: Now I am really confused. I have this code, which I am pretty sure is basically identical to the one above:

import re
import urllib2
from BeautifulSoup import BeautifulSoup as soup
import ssl

url = "https://climate.nasa.gov"
context = ssl._create_unverified_context()
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
web_soup = soup(urllib2.urlopen(url,  context=context))

l = []

# get main-content div
main_div = web_soup.findAll(name="div", attrs={'class': 'change_number'})
for element in main_div:
    print element
    l.append(float(str(element)[27:-7]))

print l

But it is throwing a UnicodeEncodeError on the websoup definition line:

Traceback (most recent call last):
  File "climate_nasa_change.py", line 10, in <module>
    web_soup = soup(urllib2.urlopen(url,  context=context))
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1522, in __init__
    BeautifulStoneSoup.__init__(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1147, in __init__
    self._feed(isHTML=isHTML)
  File "C:\Python27\lib\site-packages\BeautifulSoup.py", line 1189, in _feed
    SGMLParser.feed(self, markup)
  File "C:\Python27\lib\sgmllib.py", line 104, in feed
    self.goahead(0)
  File "C:\Python27\lib\sgmllib.py", line 143, in goahead
    k = self.parse_endtag(i)
  File "C:\Python27\lib\sgmllib.py", line 320, in parse_endtag
    self.finish_endtag(tag)
  File "C:\Python27\lib\sgmllib.py", line 358, in finish_endtag
    method = getattr(self, 'end_' + tag)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 11-12: ordinal not in range(128)

UPDATE4: aaaaaaaaaaaaaand now its magically working. I really have no idea what the hell is going on right now.

UPDATE5: and now its broken. I swear I am not changing. Seriously considering exorcising my computer. Please help.

UPDATE6: Just tried pinging climate.nasa.gov. It doesn't always go through, despite the page consistently loading in my browser. Could this be causing BeautifulSoup to fail?

Body:
The problem is that the site sometimes returns a gzip encoded response and other times plaintext.

You can resolve this easily if you use requests , as it decodes the content automatically :

web_soup = soup(requests.get(url, verify=False).text)

Note that requests is not a standard lib, you have to install it.

If you insist on using urllib2 you can decode the response with zlib if it's encoded :

decode = lambda response : zlib.decompress(response, 16 + zlib.MAX_WBITS)
response = urllib2.urlopen(url,  context=context)
headers = response.info()
html = decode(response.read()) if headers.get('content-encoding') == 'gzip' else response
web_soup = soup(html)


问:
textscan with different format data
I have a data which has two formats which I'm trying to scan using textscan in MATLAB

```<code>1,2,3,four,five,6
7,8,9,ten,eleven,12
</code>```

and so on, followed by another bunch of data with format as below

```<code>1,2,three,4
5,6,seven,8
</code>```

I'm trying to scan this data using

```<code>fid=fopen('data.txt');
C=textscan(fid,'%f %f %f %s %s %f','delimiter',',');
D=textscan(fid,'%f %f %s %f','delimiter',',');
</code>```

The whole data looks like

```<code>1,2,3,four,five,6
7,8,9,ten,eleven,12

1,2,three,4
5,6,seven,8
</code>```

Different format data is separated by an empty line, the problem is C gets data from the second table too, up to 1,2 hence upsets the format of D

How can I stop textscan once I encounter an empty line?

答:
You may want to look into matlab's readtable function. https://www.mathworks.com/help/matlab/ref/readtable.html

I've used this function to read in files delimited by a comma that contained both text and numbers, where textscan was being difficult. This table can then be converted into a cell array or matrix for whatever processing you want to do with it.

Title: textscan with different format data

Body:
I have a data which has two formats which I'm trying to scan using textscan in MATLAB

1,2,3,four,five,6
7,8,9,ten,eleven,12

and so on, followed by another bunch of data with format as below

1,2,three,4
5,6,seven,8

I'm trying to scan this data using

fid=fopen('data.txt');
C=textscan(fid,'%f %f %f %s %s %f','delimiter',',');
D=textscan(fid,'%f %f %s %f','delimiter',',');

The whole data looks like

1,2,3,four,five,6
7,8,9,ten,eleven,12

1,2,three,4
5,6,seven,8

Different format data is separated by an empty line, the problem is C gets data from the second table too, up to 1,2 hence upsets the format of D

How can I stop textscan once I encounter an empty line?


问:
How would I set the background image CSS property to a random file in a folder in JavaScript
Psuedo Code:

```<code>if currentCondition is snow {
    aFunction()
} else {
    // something else
}

function aFunction {
    look inside the snow folder at /images/condition/snow
    chose random jpeg/jpg from that folder
    use JQuery to set the css background-image property of a div
}
</code>```

How would I make the above in JavaScript? I can accomplish everything except choosing the random picture inside the snow folder. Thanks.

EDIT: The files are incrementing (file_1.jpg, file_2.jpg, etc.)

答:
This example shows you that, if you have image in 'images/' directory with all the images named as image_0.jpg, image_1.jpg, image_2.jpg incrementing ...
change the image file name structure according to your requirement. (Javascript directly cannot search file in server directory, as this might be helpful)

```<code><img src="" align="middle" border="0" name="RandomImg" >

<script language="JavaScript">
// Genarate random value from 0-5, change 6 to any number you want
var rand_no = Math.floor(6*Math.random());

// This defines the source of the preview image  (For example images/image_0.jpg)
document.images['RandomImg'].src="images/image_" + rand_no + ".jpg";

</script>
</code>```

Body:
Psuedo Code:

if currentCondition is snow {
    aFunction()
} else {
    // something else
}

function aFunction {
    look inside the snow folder at /images/condition/snow
    chose random jpeg/jpg from that folder
    use JQuery to set the css background-image property of a div
}

How would I make the above in JavaScript? I can accomplish everything except choosing the random picture inside the snow folder. Thanks.

EDIT: The files are incrementing (file_1.jpg, file_2.jpg, etc.)

Body:
This example shows you that, if you have image in 'images/' directory with all the images named as image_0.jpg, image_1.jpg, image_2.jpg incrementing ...
change the image file name structure according to your requirement. (Javascript directly cannot search file in server directory, as this might be helpful)

<img src="" align="middle" border="0" name="RandomImg" >

<script language="JavaScript">
// Genarate random value from 0-5, change 6 to any number you want
var rand_no = Math.floor(6*Math.random());

// This defines the source of the preview image  (For example images/image_0.jpg)
document.images['RandomImg'].src="images/image_" + rand_no + ".jpg";

</script>


问:
How can I get some of the data from the following URL?
I want to get some data from the following URLs like sunriseTime, outTemp, outsideHumidity and others.If you know how i can do this please help me.

URL
enter link description here

答:
You need to do the following:

Open the URL

Read the contents of the web page

Create a pattern that you want to find in the data

Use Regex (Regular Expression) to match the patterns you want from the data

I have written a Java program which does the above. Hope it helps :)

```<code>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class URLReader {

    public static List<String> getAttributesFromURL(String urlString,
                                                    String [] keys) {
        StringBuilder sb = new StringBuilder();
        try {

            //Opening the URL
            URL url = new URL(urlString);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            // Reading the URL contents into a StringBuilder object
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Copying the StringBuilder contents into a string
        String contents = sb.toString();

        List<String> keyList = Arrays.asList(keys);
        List<String> result = new ArrayList<String>();
        for (String key : keyList) {

            // Defining the pattern to be found in contents
            String patternToFind = key + "=\"(.*)\"";
            Pattern p = Pattern.compile(patternToFind);
            Matcher m = p.matcher(contents);
            if (m.find()) {

                // If pattern found, store them in the result list
                result.add(key + ": " + m.group(1).trim());
            }
        }
        // Returning the result
        return result;
    }
    public static void main(String[] args) throws java.lang.Exception {
        String urlString ="http://www.metar.gr/ws/alexan/ZWNTANA.htm";

        // List all the keys whose values need to be extracted
        String[] keys = {"sunriseTime", "outsideTemp", "outsideHumidity"};

        // Getting the result
        List<String> attributeValuePairs = getAttributesFromURL(urlString, keys);
        System.out.println(attributeValuePairs);
    }
}
</code>```

The output of the above program will be:

[sunriseTime: 6:14, outsideTemp: 21.7, outsideHumidity: 57]

You can get the values of other attributes you want by specifying the attribute names in the keysarray in the program.

Body:
You need to do the following:

Open the URL

Read the contents of the web page

Create a pattern that you want to find in the data

Use Regex (Regular Expression) to match the patterns you want from the data

I have written a Java program which does the above. Hope it helps :)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class URLReader {

    public static List<String> getAttributesFromURL(String urlString,
                                                    String [] keys) {
        StringBuilder sb = new StringBuilder();
        try {

            //Opening the URL
            URL url = new URL(urlString);
            URLConnection urlConnection = url.openConnection();
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream()));

            // Reading the URL contents into a StringBuilder object
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Copying the StringBuilder contents into a string
        String contents = sb.toString();

        List<String> keyList = Arrays.asList(keys);
        List<String> result = new ArrayList<String>();
        for (String key : keyList) {

            // Defining the pattern to be found in contents
            String patternToFind = key + "=\"(.*)\"";
            Pattern p = Pattern.compile(patternToFind);
            Matcher m = p.matcher(contents);
            if (m.find()) {

                // If pattern found, store them in the result list
                result.add(key + ": " + m.group(1).trim());
            }
        }
        // Returning the result
        return result;
    }
    public static void main(String[] args) throws java.lang.Exception {
        String urlString ="http://www.metar.gr/ws/alexan/ZWNTANA.htm";

        // List all the keys whose values need to be extracted
        String[] keys = {"sunriseTime", "outsideTemp", "outsideHumidity"};

        // Getting the result
        List<String> attributeValuePairs = getAttributesFromURL(urlString, keys);
        System.out.println(attributeValuePairs);
    }
}

The output of the above program will be:

[sunriseTime: 6:14, outsideTemp: 21.7, outsideHumidity: 57]

You can get the values of other attributes you want by specifying the attribute names in the keysarray in the program.


问:
Customized Buttons on a UIActionsheet
I am trying to create a UIActionsheet with several buttons as options.

Is it possible?.

If it is, will apple let in onto apps store. I have seen in some blogs that these types of windows are rejected?

if not possible is there an alternative to UIActionsheet, that will achieve similar functionallity?.

答:
Action sheet is like a UIView you can add anything in that. Yes! you can create a UIActionsheet as you specified.

Apple will not be rejecting if it is customized. it may be due to some other issues.

Refer answer 1. Why cant you use a normal UIView.

To know more about UIActionsheet read the documentation

Title: Customized Buttons on a UIActionsheet


问:
Does Google Cloud Vision API support face recognition or face identification?
I am looking for a Google Cloud API that can do both face recognition and identification. My understanding is that the Google Cloud Vision API will support only face detection, but not recognition.

Is there any Google Cloud API that can do face recognition?

答:
Cloud Vision currently supports face detection, but not face recognition.

That is, it can tell you whether or not there are faces in an image (and where they all are), but it cannot tell you which faces are in the image.


问:
Using Node.js to Send Database Queries to Website
I'm new to Node.js and am unsure how to use it for my website as defined in the following example. Here's what I'd like to do:

I have a website http://example.com with a real-time stock dashboard located at http://example.com/stocks. I'd like to use Node to

1) populate a mysql database (located on my web server through Namecheap hosting) with stock data scraped every 5 minutes (say from Bloomberg)

2) pull the stock data from the mysql database and serve it to the page to be displayed through the dashboard on a client's end when they visit http://example.com/stocks.

I'm by no means asking for the code behind this, I just don't know where to start! Every tutorial online seems to use their machine localhost as the only place to display and use their Node output. How can I use Node to achieve the tasks above through my web server associated with my domain and not my localhost machine? Thanks for any advice!

答:
This is easier than you may think. I would recommend using the MEAN stack or a slight alternative (still considered MEAN stack), MySQL, Loopback, Angular4+ (current), and Node.js.

With Loopback you are able to create Models, in your case, we may have a Stock model. The Model is connected to a datasource, in your case it would be MySQL. Loopback will automatically create the basic CRUD methods (GET, CREATE, UPDATE,...) as well create custom remote methods for further data manipulation. We can also build a Loopback SDK for an Angular client. The SDK allows us to call methods from our server side. In addition, the real-time socket.io is also generated when you build the SDK.

From this point, it is just handling the JSON object, error handling, and displaying these values to the user. You will be able to see both your client at localhost:4200 and your server at localhost:3000 (also use the explorer, at localhost:3000/explorer). With a little bit of set up you can build this to be a powerful application. I have written about and I am now teaching many of these concepts. Give my site a look link where I have written out this exact set up as well as others that are related to your use case. Hope this help. Please let me know if you have any more specific questions and I will do my best to help.


问:
Form Validation event.preventdefault not working
I am new to Javascript & Jquery. I am currently working on college project, I have a form input control for new password change and I want to avoid submitting the form if the use have not entered anything. I am not sure if I have chained the method well or if it is a correct to match the value from the two input fields.
I know there is a validation plugin but I want to try work things out before that.

Any help or suggestion will be appreciated

Here is the code

```<code><form id="accmanager" name="accmanager" action="view-acc.php" method="POST">
    <h1>Account Management</h1>
    <p>
      <ul type="none">
        <li><input type="radio" name="optaccmanager" checked="checked" id="viewaccinfo" /> View Account Information</li>
        <li><input type="radio" name="optaccmanager" id="addacc" /> Add Account</li>
        <li><input type="radio" name="optaccmanager" id="tochangepass" /> Change Password
         <ul id="changepass" type="none" style="display: none">
            <li><input type="text" name="newpassword" id="newpassword" size="23" title="Enter new password" /></li>
            <li><input type="text" name="confirmpassword" id="confirmpassword" size="23" title="Re-type new password" /></li>
        </ul>
        </li>
    </ul>
    <input id="submitbtn" type="submit" value="View Account" style="display: inline-block;position: absolute;left: 5em;top:20em;" />
</form>
</code>```

and the script code

```<code><script>
    //form validation section
    $(document).ready(function(){
        var changepass = $("#changepass"),
            addacc = $("#addacc"),
            viewaccinfo = $("#viewaccinfo"),
            tochangepass = $("#tochangepass");

            addacc.on("click",function(event){
              changepass.css("display","none");
              $("#submitbtn").attr("value","Add Account");
            });

            viewaccinfo.on("click",function(event){
                changepass.css("display","none");
                $("#submitbtn").attr("value","View Account");
            });

            tochangepass.on("click",function(event){
                changepass.css("display","inline");
                $("#submitbtn").attr("value","Change Password");
            });

            $("form").submit(function(event){
                var newpassword = $("#newpassword"),
                    confirmpassword = $("#confirmpassword");

                if ((newpassword.val == null) || (confirmpassword.val == null)) {
                    event.preventDefault;
                    newpassword.attr("title","Please enter new password");
                }
            });
   });
</code>```

答:
Thanks you all for your help guys I sorted the bug by changing the if block expression.

From previous code:

```<code>$("form").submit(function(event){
            var newpassword = $("#newpassword"),
                confirmpassword = $("#confirmpassword");

            if ((newpassword.val == null) || (confirmpassword.val == null)) {
                event.preventDefault;
                newpassword.attr("title","Please enter new password");
            }
        });
</code>```

To new code:

```<code>$("form").submit(function(event){
if ($("#tochangepass").is(":checked")){
   if (  ($("#newpassword").val().length == 0) || ($("#confirmpassword").val().length == 0)  ) {
        event.preventDefault();
        newpassword.attr("title","Please enter new password");
    }
    else  {
        return true;
    }
}
</code>```

}

Body:
I am new to Javascript & Jquery. I am currently working on college project, I have a form input control for new password change and I want to avoid submitting the form if the use have not entered anything. I am not sure if I have chained the method well or if it is a correct to match the value from the two input fields.
I know there is a validation plugin but I want to try work things out before that.

Any help or suggestion will be appreciated

Here is the code

<form id="accmanager" name="accmanager" action="view-acc.php" method="POST">

Account Management

<input type="radio" name="optaccmanager" checked="checked" id="viewaccinfo" /> View Account Information

<input type="radio" name="optaccmanager" id="addacc" /> Add Account

<input type="radio" name="optaccmanager" id="tochangepass" /> Change Password

<input type="text" name="newpassword" id="newpassword" size="23" title="Enter new password" />

<input type="text" name="confirmpassword" id="confirmpassword" size="23" title="Re-type new password" />

    <input id="submitbtn" type="submit" value="View Account" style="display: inline-block;position: absolute;left: 5em;top:20em;" />
</form>

and the script code

Body:
Thanks you all for your help guys I sorted the bug by changing the if block expression.

From previous code:

$("form").submit(function(event){
            var newpassword = $("#newpassword"),
                confirmpassword = $("#confirmpassword");

            if ((newpassword.val == null) || (confirmpassword.val == null)) {
                event.preventDefault;
                newpassword.attr("title","Please enter new password");
            }
        });

To new code:

$("form").submit(function(event){
if ($("#tochangepass").is(":checked")){
   if (  ($("#newpassword").val().length == 0) || ($("#confirmpassword").val().length == 0)  ) {
        event.preventDefault();
        newpassword.attr("title","Please enter new password");
    }
    else  {
        return true;
    }
}

}


问:
How does OSGi manage interaction of components running in separate JVMs?
I have been trying to understand a bit more about the wider picture of OSGi without reading thru the entire specification. As with so many things, the introduction to what OSGi actually is was probably written by someone who had been working on it for a decade and perhaps wasn't best placed to put themselves in the mindset of someone who knows nothing about it :-)

Looking at Felix's example DictionaryService, I don't really understand what is going on. Is OSGi a distinct instance of a JVM into which you load bundles which can then find each other?

Obviously it is not just this because other answers on StackOverflow are explicit that OSGi can solve the dependency problem of a distributed system containing modules deployed within distinct JVMs (plus the FAQ keeps talking about networks).

In this latter case, how does a component running in one JVM interact with another component in a separate JVM? Can the two components "use" each other as if they were running within the same JVM (i.e. via local method calls), and how does OSGi manage the marshalling of data across a network (do you have to use Serializable for example)?

Or does the component author have to use some other distinct mechanism (either provided by OSGi or written themselves) for communication between remote components?

Any help much appreciated!

答:
Yes, OSGi only deals with bundles and services running on the same VM. However, one should note that it is a distinct feature of OSGi that it facilitates running multiple applications (in a controlled way and sharing common modules) on the same JVM at all.

When it comes to accessing services outside the clients JVM, there is currently no standardized solution. Paremus Infiniflow and the derived open-source project Newton use an SCA approach. The upcoming 4.2 release of the OSGi specs will address one side of the problem, namely how to use generic distribution software in such a way that it can bring remote services into the client's JVM.

As somebody mentioned R-OSGi, this approach also deals with the other side of the problem, being how to manage dependencies between distributed OSGi frameworks. Since R-OSGi is not generic distribution software but explicitly deals with the lifecycle issues and dependency management of OSGi bundles.

OwnerDisplayName: Chris Marshall

OwnerDisplayName: Jan S Rellermeyer


问:
How to convert facebook Graph date time into c# DateTime
I have "2010-12-20T11:36:28+0000".
How do I parse it into DateTime?

Thanks

答:
```<code>string date = "2010-12-20T11:36:28+0000";
string start = date.Substring(0, date.IndexOf("T"));
string end = date.Substring(date.IndexOf("T") + 1, date.IndexOf("+") - (date.IndexOf("T") + 1));
DateTime dt = Convert.ToDateTime(start +" "+ end);
</code>```


问:
Can't see "+" sign in PyCharm

I wish to download new Python packages into PyCharm but I cannot see the "+" sign in the interpreter tab. Please advise on what I should do to be able to view it so that I can continue the steps to download Python packages. I am using a Mac btw.

Thanks!

答: Have you tried clicking on the ... button to the right of Project Interpreter? I've looked on both Windows and Linux and they both have a gear wheel with +/- buttons. Perhaps for some reason they pulled the +/- functionality into the ... on Macs. On both Windows and Linux, my gear wheel gives me Add Local, Add Remote, Create VirtualEnv, More.... Do you see anything different? What version of Pycharm are you using?

Title: Can't see "+" sign in PyCharm


问:
Deserialize nested field from JSON using LoganSquare
I am using LoganSquare with Retrofit to consume data from a web service.

For one particular API, the web service returns a relatively complex JSON response, and the only piece of information I am interested in is nested a couple of layers deep. e.g.,

```<code>{"outer": { "middle": { "inner": ... }}}
</code>```

Since I'm only interested in the inner value, I created a data object like:

```<code>@JsonObject
class MyData implements Serializable {
    @JsonField(name = "outer.middle.inner")
    public String inner;
}
</code>```

And I've mapped the return value of the web service to this data type.

However, it appears it was just wishful thinking that this dot syntax (outer.middle.inner) would do what I had hoped, as the field is not mapped upon successful invocation of the method.

Is there any way to map a field in a LoganSquare JSON object to a nested value?

答:
I think you have to declare each JsonObject as an inner class so:</p>

```<code>@JsonObject
public class MyData implements Serializable {
    @JsonObject
    public static class Outer {
        @JsonObject
        public static class Middle {
            @JsonField
            public String inner;
        }
    }
}
</code>```

Body:
I am using LoganSquare with Retrofit to consume data from a web service.

For one particular API, the web service returns a relatively complex JSON response, and the only piece of information I am interested in is nested a couple of layers deep. e.g.,

{"outer": { "middle": { "inner": ... }}}

Since I'm only interested in the inner value, I created a data object like:

@JsonObject
class MyData implements Serializable {
    @JsonField(name = "outer.middle.inner")
    public String inner;
}

And I've mapped the return value of the web service to this data type.

However, it appears it was just wishful thinking that this dot syntax (outer.middle.inner) would do what I had hoped, as the field is not mapped upon successful invocation of the method.

Is there any way to map a field in a LoganSquare JSON object to a nested value?

Body:
I think you have to declare each JsonObject as an inner class so:

@JsonObject
public class MyData implements Serializable {
    @JsonObject
    public static class Outer {
        @JsonObject
        public static class Middle {
            @JsonField
            public String inner;
        }
    }
}


问:
How to show a count of 0 in Oracle SQL?
I need to create a table that determines the number of orders that fall into different order size ranges. However, I need to display a count of 0 for the order size range of 1,001 and Above and it isn't showing up when I run my query.

```<code>SELECT "Bucket", COUNT(*) AS "Order Count"
FROM
(SELECT CASE
   WHEN O.QuantityShares <= 100 THEN '0-100'
   WHEN O.QuantityShares <= 400 THEN '101-400'
   WHEN O.QuantityShares <= 800 THEN '401-800'
   WHEN O.QuantityShares <= 1000 THEN '801-1,000'
   ELSE '1,001 and Above'
FROM OrderTransactions O)
GROUP BY "Bucket"
ORDER BY "Bucket" ASC;
</code>```

答:
You just need to create a table of your buckets then 'LEFT JOIN' your quantities to that.</p>

```<code>    SELECT "Bucket", COUNT(*) AS "Order Count"
FROM
(SELECT '0-100' As Bucket
 UNION
 SELECT '101-400' AS Bucket
 UNION
 SELECT '401-800' AS Bucket
 UNION
 SELECT '801-1,000') Buckets
 LEFT JOIN
(SELECT CASE
   WHEN O.QuantityShares <= 100 THEN '0-100'
   WHEN O.QuantityShares <= 400 THEN '101-400'
   WHEN O.QuantityShares <= 800 THEN '401-800'
   WHEN O.QuantityShares <= 1000 THEN '801-1,000'
   ELSE '1,001 and Above' END As Bucket
FROM OrderTransactions O) QTY
ON Buckets.Bucket = QTY.Bucket
GROUP BY Buckets.Bucket
ORDER BY Buckets.Bucket ASC;
</code>```

Title: How to show a count of 0 in Oracle SQL?

Body:
I need to create a table that determines the number of orders that fall into different order size ranges. However, I need to display a count of 0 for the order size range of 1,001 and Above and it isn't showing up when I run my query.

SELECT "Bucket", COUNT(*) AS "Order Count"
FROM
(SELECT CASE
   WHEN O.QuantityShares <= 100 THEN '0-100'
   WHEN O.QuantityShares <= 400 THEN '101-400'
   WHEN O.QuantityShares <= 800 THEN '401-800'
   WHEN O.QuantityShares <= 1000 THEN '801-1,000'
   ELSE '1,001 and Above'
FROM OrderTransactions O)
GROUP BY "Bucket"
ORDER BY "Bucket" ASC;

Body:
You just need to create a table of your buckets then 'LEFT JOIN' your quantities to that.

    SELECT "Bucket", COUNT(*) AS "Order Count"
FROM
(SELECT '0-100' As Bucket
 UNION
 SELECT '101-400' AS Bucket
 UNION
 SELECT '401-800' AS Bucket
 UNION
 SELECT '801-1,000') Buckets
 LEFT JOIN
(SELECT CASE
   WHEN O.QuantityShares <= 100 THEN '0-100'
   WHEN O.QuantityShares <= 400 THEN '101-400'
   WHEN O.QuantityShares <= 800 THEN '401-800'
   WHEN O.QuantityShares <= 1000 THEN '801-1,000'
   ELSE '1,001 and Above' END As Bucket
FROM OrderTransactions O) QTY
ON Buckets.Bucket = QTY.Bucket
GROUP BY Buckets.Bucket
ORDER BY Buckets.Bucket ASC;


问:
load image from firebase and caching swift3
I have a little problem. I get images from Firebase and I'm trying to add cache because  I tried with this way but like this they are not cached:

I declared this variable

```<code>var uid:String = ""
var partitionUrl:String = ""
var titre:String = ""
</code>```

And this to link to firebase.

```<code>let storageRef = FIRStorage.storage().reference()
let databaseRef = FIRDatabase.database().reference().child("canticles")
</code>```

The app use the uid to get the title and the image and show it in UIlabel and UIImageView

```<code>@IBOutlet weak var titleCantique: UILabel!
@IBOutlet weak var partitionImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    getPartitionImage()
}

override func viewWillAppear(_ animated: Bool) {
    print("partition uid : " + uid)
    print("partition URL : " + partitionUrl)
    print("partition TITLE : " + titre)
    self.titleCantique.text = titre
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func getPartitionImage(){

        DispatchQueue.main.async(execute: {
            self.storageRef.child(self.partitionUrl).data(withMaxSize: 10*1024*1024, completion: { (data, error) in

            if error != nil {
            print(error!)
            return

            }
            let image = UIImage(data: data!)
            self.partitionImageView.image = image
        })
    })
  }
}
</code>```

The problem is when the phone is not connected, the images are not appearing.
What could I do to solve this by adding a cache for the images then it will appears in offline?

答:
I just proceeded like this

At first time, i added FirebaseStorageCache with cocoapod

In the swift file:

```<code>import UIKit
import Firebase
import FirebaseStorageCache
</code>```

And implemented my getPartitionImage function like this

```<code>func getPartitionImage() {

    let ref: FIRStorageReference = self.storageRef.child(self.partitionUrl)

    FirebaseStorageCache.main.get(storageReference: ref) { data in

        self.partitionImageView.setImage(storageReference: ref)

    }
  }
}
</code>```

Body:
I have a little problem. I get images from Firebase and I'm trying to add cache because  I tried with this way but like this they are not cached:

I declared this variable

var uid:String = ""
var partitionUrl:String = ""
var titre:String = ""

And this to link to firebase.

let storageRef = FIRStorage.storage().reference()
let databaseRef = FIRDatabase.database().reference().child("canticles")

The app use the uid to get the title and the image and show it in UIlabel and UIImageView

@IBOutlet weak var titleCantique: UILabel!
@IBOutlet weak var partitionImageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    getPartitionImage()
}

override func viewWillAppear(_ animated: Bool) {
    print("partition uid : " + uid)
    print("partition URL : " + partitionUrl)
    print("partition TITLE : " + titre)
    self.titleCantique.text = titre
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func getPartitionImage(){

        DispatchQueue.main.async(execute: {
            self.storageRef.child(self.partitionUrl).data(withMaxSize: 10*1024*1024, completion: { (data, error) in

            if error != nil {
            print(error!)
            return

            }
            let image = UIImage(data: data!)
            self.partitionImageView.image = image
        })
    })
  }
}

The problem is when the phone is not connected, the images are not appearing.
What could I do to solve this by adding a cache for the images then it will appears in offline?

Body:
I just proceeded like this

At first time, i added FirebaseStorageCache with cocoapod

In the swift file:

import UIKit
import Firebase
import FirebaseStorageCache

And implemented my getPartitionImage function like this

func getPartitionImage() {

    let ref: FIRStorageReference = self.storageRef.child(self.partitionUrl)

    FirebaseStorageCache.main.get(storageReference: ref) { data in

        self.partitionImageView.setImage(storageReference: ref)

    }
  }
}