问:
Use multiline regex on cat output
I've the following file queries.sql that contains a number of queries, structured like this:

```<code>/* Query 1 */
SELECT cab_type_id,
       Count(*)
FROM   trips
GROUP  BY 1;

/* Query 2 */
SELECT passenger_count,
       Avg(total_amount)
FROM   trips
GROUP  BY 1;

/* Query 3 */
SELECT passenger_count,
       Extract(year FROM pickup_datetime),
       Count(*)
FROM   trips
GROUP  BY 1,
          2;
</code>```

Then I've written a regex, that finds all those queries in the file:

```<code>/\*[^\*]*\*/[^;]*;
</code>```

What I'd like to achieve is the following:

Select all the queries with the regex.

Prefix each query with EXPLAIN ANALYZE

Execute each query and output the results to a new file. That means, query 1 will create a file q1.txt with the corresponding output, query 2 create q2.txt etc.

One of my main challenges (there are no problems, right? ;-)) is, that I'm rather unfamiliar with the linux bash I've to use.

I tried cat queries.sql | grep '/\*[^\*]*\*/[^;]*;' but that doesn't return anything.

So a solution could look like:

```<code>count = 0
for query in (cat queries.sql | grep 'somehow-here-comes-my-regex') do
    count = $count+1
    query = 'EXPLAIN ANALYZE '+query
    psql -U postgres -h localhost -d nyc-taxi-data -c query > 'q'$count'.txt'
</code>```

Except from: that doesn't work and I don't know how to make it work.

答:
You have to omit spaces for variable assignments.

The following script would help. Save it in a file eg.: explain.sh, make it executable using chmod 0700 explain.sh and run in the following way: ./explain.sh query.sql.

```<code>#!/bin/bash

qfile="$1"

# number of queries
n="$(grep -oP '(?<=Query )[0-9]+ ' $qfile)"

count=1
for q in $n; do
    # Corrected solution, modified after the remarks of @EdMorton
    qn="EXPLAIN ANALYZE $(awk -v n="Query $q" 'flag; $0 ~ n {flag=1} /;/{flag=0}' $qfile)"
    #qn="EXPLAIN ANALYZE $(awk -v n=$q "flag; /Query $q/{flag=1} /;/{flag=0}" $qfile)"
    # psql -U postgres -h localhost -d nyc-taxi-data -c "$qn" > q$count.txt
    echo "$qn" > q$count.txt
    count=$(( $count + 1 ))
done
</code>```

First of all, the script accounts for one argument (your example input query.sql file). It reads out the number of queries and save into a variable n. Then in a for loop it iterates through the query numbers and uses awk to extract the number n query and append EXPLAIN ANALYZE to the beginning. Then you can run your psql with the desired query. Here I commented out the psql part. This example script only creates qN.txt files for each explain query.

UPDATE:

The awk part: It is possible to use a shell variable in awk using the -v flag. Here we creates an awk variable n with the value of the q shell variable. n is used to create the starter pattern ie: Query 1. awk -v n="Query $q" 'flag; $0 ~ n {flag=1} /;/{flag=0}' $qfile matches everything between Query 1 and the first occurence of a semi-colon (;) excluding the line of Query 1 from query.sql. The $(...) means command-substitution in bash, thus we can save the output of a shell command into a variable. Here we save the output of awk and prefix it with the EXPLAIN ANALYZE string.

Here is a great answer about awk pattern matching.

Title: Use multiline regex on cat output

Body:
I've the following file queries.sql that contains a number of queries, structured like this:

/* Query 1 */
SELECT cab_type_id,
       Count(*)
FROM   trips
GROUP  BY 1;

/* Query 2 */
SELECT passenger_count,
       Avg(total_amount)
FROM   trips
GROUP  BY 1;

/* Query 3 */
SELECT passenger_count,
       Extract(year FROM pickup_datetime),
       Count(*)
FROM   trips
GROUP  BY 1,
          2;

Then I've written a regex, that finds all those queries in the file:

/\*[^\*]*\*/[^;]*;

What I'd like to achieve is the following:

Select all the queries with the regex.

Prefix each query with EXPLAIN ANALYZE

Execute each query and output the results to a new file. That means, query 1 will create a file q1.txt with the corresponding output, query 2 create q2.txt etc.

One of my main challenges (there are no problems, right? ;-)) is, that I'm rather unfamiliar with the linux bash I've to use.

I tried cat queries.sql | grep '/\*[^\*]*\*/[^;]*;' but that doesn't return anything.

So a solution could look like:

count = 0
for query in (cat queries.sql | grep 'somehow-here-comes-my-regex') do
    count = $count+1
    query = 'EXPLAIN ANALYZE '+query
    psql -U postgres -h localhost -d nyc-taxi-data -c query > 'q'$count'.txt'

Except from: that doesn't work and I don't know how to make it work.

Body:
You have to omit spaces for variable assignments.

The following script would help. Save it in a file eg.: explain.sh, make it executable using chmod 0700 explain.sh and run in the following way: ./explain.sh query.sql.

#!/bin/bash

qfile="$1"

# number of queries
n="$(grep -oP '(?<=Query )[0-9]+ ' $qfile)"

count=1
for q in $n; do
    # Corrected solution, modified after the remarks of @EdMorton
    qn="EXPLAIN ANALYZE $(awk -v n="Query $q" 'flag; $0 ~ n {flag=1} /;/{flag=0}' $qfile)"
    #qn="EXPLAIN ANALYZE $(awk -v n=$q "flag; /Query $q/{flag=1} /;/{flag=0}" $qfile)"
    # psql -U postgres -h localhost -d nyc-taxi-data -c "$qn" > q$count.txt
    echo "$qn" > q$count.txt
    count=$(( $count + 1 ))
done

First of all, the script accounts for one argument (your example input query.sql file). It reads out the number of queries and save into a variable n. Then in a for loop it iterates through the query numbers and uses awk to extract the number n query and append EXPLAIN ANALYZE to the beginning. Then you can run your psql with the desired query. Here I commented out the psql part. This example script only creates qN.txt files for each explain query.

UPDATE:

The awk part: It is possible to use a shell variable in awk using the -v flag. Here we creates an awk variable n with the value of the q shell variable. n is used to create the starter pattern ie: Query 1. awk -v n="Query $q" 'flag; $0 ~ n {flag=1} /;/{flag=0}' $qfile matches everything between Query 1 and the first occurence of a semi-colon (;) excluding the line of Query 1 from query.sql. The $(...) means command-substitution in bash, thus we can save the output of a shell command into a variable. Here we save the output of awk and prefix it with the EXPLAIN ANALYZE string.

Here is a great answer about awk pattern matching.


来源: stackexchange

问:
convert array of array of objects into single array of objects in lodash
I have an array of arrays of objects as below which is generated by _.filter lodash function which returns objects for the matched values:

```<code>const matchedPositions = _.filter(allPositions, function(o) {
return o.company.toLowerCase() === value.toLowerCase();
});//matchedPositions have array of objects
let allCheckboxFiltered = [...allCheckboxFiltered, matchedPositions]; //allCheckboxFiltered  have below results

   [
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
    ];
</code>```

I wanted as below intended result;

```<code>[
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}
];
</code>```

I have tried reduce function to generate such intended result as below:

```<code>let result = temp1.reduce(function(res, obj) {
console.log(res, obj);
Object.keys(obj).forEach(function(k) {
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
}, []);
</code>```

Above code is not generating the result, I wanted. I have tried other stuffs e.g. lodash functions as well but all in vain.

Thanks

答:
You can use reduce

```<code>var output = temp1.reduce( (a,b) => (a = a.concat(b), a) ,[] ) ;
</code>```

Or simply

```<code>var output = temp1.reduce( (a,b) => a.concat(b) ,[] ) ;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array of arrays of objects as below which is generated by _.filter lodash function which returns objects for the matched values:

const matchedPositions = _.filter(allPositions, function(o) {
return o.company.toLowerCase() === value.toLowerCase();
});//matchedPositions have array of objects
let allCheckboxFiltered = [...allCheckboxFiltered, matchedPositions]; //allCheckboxFiltered  have below results

   [
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
    ];

I wanted as below intended result;

[
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}
];

I have tried reduce function to generate such intended result as below:

let result = temp1.reduce(function(res, obj) {
console.log(res, obj);
Object.keys(obj).forEach(function(k) {
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
}, []);

Above code is not generating the result, I wanted. I have tried other stuffs e.g. lodash functions as well but all in vain.

Thanks

Body:
You can use reduce

var output = temp1.reduce( (a,b) => (a = a.concat(b), a) ,[] ) ;

Or simply

var output = temp1.reduce( (a,b) => a.concat(b) ,[] ) ;


问:
Haskell Best Practise: Early termination in Haskeline
I am using the Haskeline package and I want to get three strings in a row from the command line before I do anything and I have come up with what seems to be a neat solution to me. But I am sure that there might be a better way to do it. I am looking for best practices while using the Haskeline package. Please evaluate the merits of the following example code:

```<code>import System.Console.Haskeline
import Control.Monad.Trans
import Control.Monad.Maybe
import Data.Maybe
import Control.Monad

main :: IO ()
main = runInputT defaultSettings (runMaybeT getStrings) >>= print

getStrings :: MaybeT (InputT IO) (String, String, String)
getStrings = do
   mone <- lift $ getInputLine "food> "
   notNothing mone
   mtwo <- lift $ getInputLine "drink> "
   notNothing mtwo
   mthree <- lift $ getInputLine "dessert> "
   notNothing mthree
   return (fromJust mone, fromJust mtwo, fromJust mthree)
      where
         notNothing a = guard (a /= Nothing)
</code>```

As you can see it accomplishes the task of early termination but it looks a bit yucky still. I'm thinking of trying to convert the notNothing's and the getInputLine's into a single line like:

```<code>mone <- notNothing =<< lift $ getInputLine "food> " -- does not type check
</code>```

Which I think does not look that bad. I think that is pretty clear and concise (though it does not type check so I will have to write a version that does).

However, this is the best I have come up with and my question finally is: How would you go about improving this code to be neater and more readily readable? Am I even on the right track?

Edit: If your guard is something other than 'a /= Nothing' then a nice helper function that I just discovered is:

```<code>myGuard s = guard (someConditionFunc s) >> s
</code>```

Because then you can write (as luqui suggested):

```<code>mone <- myGuard =<< (lift $ getInputLine prompt)
</code>```

Which is pretty cool. But if you are matching against only Nothing then TomMD's answer is better.

答:
Why not just leverage the fact that fail _ = Nothing for the Maybe monad?

```<code>mthree <- lift $ getInputLine "dessert> "
notNothing mthree
</code>```

becomes

```<code>Just mthree <- lift $ getInputLine "dessert> "
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am using the Haskeline package and I want to get three strings in a row from the command line before I do anything and I have come up with what seems to be a neat solution to me. But I am sure that there might be a better way to do it. I am looking for best practices while using the Haskeline package. Please evaluate the merits of the following example code:

import System.Console.Haskeline
import Control.Monad.Trans
import Control.Monad.Maybe
import Data.Maybe
import Control.Monad

main :: IO ()
main = runInputT defaultSettings (runMaybeT getStrings) >>= print

getStrings :: MaybeT (InputT IO) (String, String, String)
getStrings = do
   mone <- lift $ getInputLine "food> "
   notNothing mone
   mtwo <- lift $ getInputLine "drink> "
   notNothing mtwo
   mthree <- lift $ getInputLine "dessert> "
   notNothing mthree
   return (fromJust mone, fromJust mtwo, fromJust mthree)
      where
         notNothing a = guard (a /= Nothing)

As you can see it accomplishes the task of early termination but it looks a bit yucky still. I'm thinking of trying to convert the notNothing's and the getInputLine's into a single line like:

mone <- notNothing =<< lift $ getInputLine "food> " -- does not type check

Which I think does not look that bad. I think that is pretty clear and concise (though it does not type check so I will have to write a version that does).

However, this is the best I have come up with and my question finally is: How would you go about improving this code to be neater and more readily readable? Am I even on the right track?

Edit: If your guard is something other than 'a /= Nothing' then a nice helper function that I just discovered is:

myGuard s = guard (someConditionFunc s) >> s

Because then you can write (as luqui suggested):

mone <- myGuard =<< (lift $ getInputLine prompt)

Which is pretty cool. But if you are matching against only Nothing then TomMD's answer is better.

Body:
Why not just leverage the fact that fail _ = Nothing for the Maybe monad?

mthree <- lift $ getInputLine "dessert> "
notNothing mthree

becomes

Just mthree <- lift $ getInputLine "dessert> "


问:
How do I convert a hex triplet to an RGB tuple and back?
I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet. </p>

答:
Here you go. I use it to convert color to graphviz color format in #RGBA format with prefix=#.

```<code>def rgba_hex( color, prefix = '0x' ):
    if len( color ) == 3:
       color = color + (255,)
    hexColor = prefix + ''.join( [ '%02x' % x for x in color ] )
    return hexColor
</code>```

USAGE:

```<code>In [3]: rgba_hex( (222, 100, 34) )
Out[3]: '0xde6422ff'

In [4]: rgba_hex( (0,255,255) )
Out[4]: '0x00ffffff'

In [5]: rgba_hex( (0,255,255,0) )
Out[5]: '0x00ffff00'
</code>```

Body:
Here you go. I use it to convert color to graphviz color format in #RGBA format with prefix=#.

def rgba_hex( color, prefix = '0x' ):
    if len( color ) == 3:
       color = color + (255,)
    hexColor = prefix + ''.join( [ '%02x' % x for x in color ] )
    return hexColor

USAGE:

In [3]: rgba_hex( (222, 100, 34) )
Out[3]: '0xde6422ff'

In [4]: rgba_hex( (0,255,255) )
Out[4]: '0x00ffffff'

In [5]: rgba_hex( (0,255,255,0) )
Out[5]: '0x00ffff00'


问:
Bootstrap 4 Popover with HTML Content
This is my code, but it will not work.

When I use the native Bootstrap PopOver with HTML in it's content, the frontend is not displaying that PopOver and the HTML Source is malformatted.

<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
        <title>test</title>

             Toggle popover

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

<p>Remove Class property.
It can work.</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-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
        <title>test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://cdn.bootcss.com/popper.js/1.11.0/umd/popper.min.js" ></script>
        <script src="https://cdn.bootcss.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script>
        <style>
            .popover{
                color: #757575 !important;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <span href="#" data-toggle="popover" title="Popover Header" data-html="true" data-content="<div>text text</div>">Toggle popover</span>
        </div>
        <script>
            $(function () {
                $('[data-toggle="popover"]').popover()
            })
        </script>
    </body>
</html></code>```

I am trying to display HTML inside a bootstrap popover, but somehow it's not working. I found some answers here but it won't work for me. Please let me know if I'm doing something wrong.

答:
Remember to set data-html="true" (along with the other data- attributes) on the popover element. Otherwise HTML content won't be rendered correctly.

More details can be found in the docs for Bootstrap: https://getbootstrap.com/docs/4.6/components/popovers/#options

Title: Bootstrap 4 Popover with HTML Content

Body:
This is my code, but it will not work.

When I use the native Bootstrap PopOver with HTML in it's content, the frontend is not displaying that PopOver and the HTML Source is malformatted.

<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
        <title>test</title>

             Toggle popover

Remove Class property.
It can work.

<!DOCTYPE html>

        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>
        <title>test</title>

            Toggle popover

I am trying to display HTML inside a bootstrap popover, but somehow it's not working. I found some answers here but it won't work for me. Please let me know if I'm doing something wrong.

ContentLicense: CC BY-SA 4.0


问:
how to implement an asynch sub call in vb.net and c#
Probably the most common and neeeded programming pattern of all is that where an asynch function is called and the calling function waits for its completion.

Psuedo Code:

```<code>do

  Execute TimeConsumingSub asynchronously

  Wait for TimeConsumingSub to complete for a maximum of 100 seconds

  if TimeConsumingSub has timed out
    do something
  else
    do something else
  end if

loop
</code>```

What is the c#, vb.net equivalent of this pseudo code?

答:
Here is the code equivelent, built as small as possible:

```<code>Dim _TimeConsumingSubCompleted as Boolean = False
'global variable to use, set to true at end of your subroutine.
            Do
            Await Threading.Tasks.Task.WaitAny(TimeConsumingSub, Threading.Tasks.Task.Delay(100000))
            If _TimeConsumingSubCompleted Then
                'do something
            Else
                'Do something else
            End If
        Loop
</code>```

This makes use of Task.WaitAny to run both your consuming sub and a delay next to each other, and finishes awaiting execution until either one is complete.

Body:
Probably the most common and neeeded programming pattern of all is that where an asynch function is called and the calling function waits for its completion.

Psuedo Code:

do

  Execute TimeConsumingSub asynchronously

  Wait for TimeConsumingSub to complete for a maximum of 100 seconds

  if TimeConsumingSub has timed out
    do something
  else
    do something else
  end if

loop

What is the c#, vb.net equivalent of this pseudo code?

Body:
Here is the code equivelent, built as small as possible:

Dim _TimeConsumingSubCompleted as Boolean = False
'global variable to use, set to true at end of your subroutine.
            Do
            Await Threading.Tasks.Task.WaitAny(TimeConsumingSub, Threading.Tasks.Task.Delay(100000))
            If _TimeConsumingSubCompleted Then
                'do something
            Else
                'Do something else
            End If
        Loop

This makes use of Task.WaitAny to run both your consuming sub and a delay next to each other, and finishes awaiting execution until either one is complete.


问:
How to set firebase analytics events with ionic 3
I'm trying to get my analytics events with firebase but all I get is only session_start event. I'm using the firebase plugin for ionic.

This is my code:

```<code>constructor(public navCtrl: NavController, private nav: NavController,
            private firebaseAnalytics: FirebaseAnalytics) {
    this.firebaseAnalytics.setEnabled(true);
    this.firebaseAnalytics.logEvent('home_page_viewed', {page: "dashboard"})
        .then((res: any) => console.log(res))
        .catch((error: any) => console.error(error));
    }
</code>```

So, I expect to see in firebase console an event that called 'home_page_viewed' but I don't see such event. All I see is only session_start event.

Anyone knows what should I do?

答:
You probably have lazy-loading enabled in your application and a page view does not always create a new page object. So the construct method is NOT called for every page view.

Further the constructor method of the page class is not the correct place to log a page-view.

You should move the logEvent call to one of Ionic's lifecycle events.

```<code>public ionViewDidEnter()
{
  this.firebaseAnalytics.logEvent('home_page_viewed', {page: 'dashboard'})
    .then((res: any) => console.log(res))
    .catch((error: any) => console.error(error));
}
</code>```

Body:
I'm trying to get my analytics events with firebase but all I get is only session_start event. I'm using the firebase plugin for ionic.

This is my code:

constructor(public navCtrl: NavController, private nav: NavController,
            private firebaseAnalytics: FirebaseAnalytics) {
    this.firebaseAnalytics.setEnabled(true);
    this.firebaseAnalytics.logEvent('home_page_viewed', {page: "dashboard"})
        .then((res: any) => console.log(res))
        .catch((error: any) => console.error(error));
    }

So, I expect to see in firebase console an event that called 'home_page_viewed' but I don't see such event. All I see is only session_start event.

Anyone knows what should I do?

Body:
You probably have lazy-loading enabled in your application and a page view does not always create a new page object. So the construct method is NOT called for every page view.

Further the constructor method of the page class is not the correct place to log a page-view.

You should move the logEvent call to one of Ionic's lifecycle events.

public ionViewDidEnter()
{
  this.firebaseAnalytics.logEvent('home_page_viewed', {page: 'dashboard'})
    .then((res: any) => console.log(res))
    .catch((error: any) => console.error(error));
}


问:
How to call dynamic library(.so file) with root priority in Ubuntu
I'm writing camera interface for HALCON 13.0 in Ubuntu platform, the interface is named hAcqxVision and realized by file with name hAcqxVision.so, and this interface fill will cal the vendor's driver named libtycam.so, but calling libtycam.so should be with root authority, otherwise it will report error.

Then I wrote a executable binary that call libtycam.so directly with root authority, it worked well. but it would fail when with HALCON and hAcqxVision.so, and HALCON can't run with root authority.

could you please tell any way to realize this? Thanks.

答: This is a generic answer, but the usual way to do this on unix-es is to start as root (use the suid bit if you have to), then drop privileges for the part of the program that doesn't require root. Take a look at seteuid and the saved used id concepts.</p>


问:
Is there a mean to reboot WinCE 5.0 programmatically?
I am very new to WinCE, sorry if the question is stupid.
Is there something for rebooting a WinCE 5 system by executing a command ( like "shutdown -r now" on Linux) or by calling an API-Function?

Thank you very much!

答: KernelIoControl with IOCTL_HAL_REBOOT is the API way (if the OS supports it).  There is no standard command-line app that does it.</p>


问:
Race condition when multiple processes attempts to read / delete files in the same directory
I have a Python script which performs operations like read, write and delete on files in a directory. Before performing any of these operations, os.listdir is done to get the list of files. A file is picked at random and an operation is performed on it.

But I have to run multiple instances of the script. So there is a possibility of race condition. A file could get deleted by an instance while another instance still attempts to read it.

What is a good way to overcome this problem?

答: the best approach is for you to decide what the correct behaviour should be. these are classic issues in file and database management,  a clear policy is needed first.</p>


问:
PresenterWidget removeFromSlot fails
When trying to remove presenterWidget from slot, comparison in class PresenterWidget method rawRemoveFromSlot() fails and getView().removeFromSlot() is not being called.

Exmaple:

```<code>//this is called from my presenter
//widget here is an extension of PresenterWidget
WidgetSlot removeSlot = new WidgetSlot("widget" + widget.getId());
removeFromSlot(removeSlot, widget);
</code>```

WidgetSlot class:

```<code>public class WidgetSlot<T extends PresenterWidget<?>> extends Slot<T> {

    private Object identifier;

    public WidgetSlot(Object identifier) {
        super();
        this.identifier = identifier;
    }

    public Object getIdentifier() {
        return identifier;
    }
}
</code>```

When debugging client side code with browser:

```<code>public abstract class PresenterWidget <> {
   ...
    //this method is called
    private void rawRemoveFromSlot(IsSlot<?> slot, PresenterWidget<?> child) {
        if (child != null && child.slot == slot) { <!-- this fails because child.slot is not equal to slot even though they are...
            if (!child.isPopup()) {
                this.getView().removeFromSlot(slot.getRawSlot(), child);
            }

            child.orphan();
        }
    }
   ...
}
</code>```

slot in method (copied from browser debugger):

```<code>slot_0_g$: bZy_g$
    identifier_2_g$: "widget1"
</code>```

child.slot in method (copied from browser debugger):

```<code>slot_3_g$: bZy_g$
    identifier_2_g$: "widget1"
</code>```

Unless I am misunderstanding debugger information, both slots seem to be equal? The only way the slot comparison in the method would fail is if slot objects had different references.

Any ideas?

GWT version: 2.8.2

GWTP version: 1.6

答:
Problem is that to determine if slot and child.slot is equal, GWTP implementation uses direct comparison, meaning object references must be equal. In the GWT 2.7 and GWTP 1.4 you could send String as slot, like removeFromSlot("SOME_SLOT", widget) and this would work, since mthod was removeFromSlot(Object object, PresenterWidget w).

With new version, this method was deprecated and one would have to pass Slot object to method instead...and since I don't have these Slot objects saved and instead have them created on runtime by widget id, removeFromSlot() slot comparison fails.

Solution would be to save Slot references when widget is created with method setInslot() or maybe there already is way to retrieve widget slot...

In general using == to compare objects is not advisable. It would be so easy to fix my problem if equals() was used instead.

Title: PresenterWidget removeFromSlot fails

Body:
When trying to remove presenterWidget from slot, comparison in class PresenterWidget method rawRemoveFromSlot() fails and getView().removeFromSlot() is not being called.

Exmaple:

//this is called from my presenter
//widget here is an extension of PresenterWidget
WidgetSlot removeSlot = new WidgetSlot("widget" + widget.getId());
removeFromSlot(removeSlot, widget);

WidgetSlot class:

public class WidgetSlot<T extends PresenterWidget<?>> extends Slot<T> {

    private Object identifier;

    public WidgetSlot(Object identifier) {
        super();
        this.identifier = identifier;
    }

    public Object getIdentifier() {
        return identifier;
    }
}

When debugging client side code with browser:

public abstract class PresenterWidget <> {
   ...
    //this method is called
    private void rawRemoveFromSlot(IsSlot<?> slot, PresenterWidget<?> child) {
        if (child != null && child.slot == slot) {


问:
Coverage exclusion in Eclipse [EclEmma] is not working?
According to this post on StackOverflow and EclEmma's documentation, exclusion of classes from the coverage should be very possible. However, while the "includes" field works just as described, the "excludes" field does not.

Take the following project hierarchy and coverage runtime settings respectively:

But, after running the coverage operation, the exclude setting does not work:

As one can see, the excluded package is still being included in the overall coverage testing. In addition, if you mark '*' in "includes" and mark a package in the "excludes," it is still not excluded.

According to this issue and Godlin's answer:

Unfortunately currently EclEmma does not support exclusions from the report as stated in [issue]

However, this problem is well over a year old. I am asking if I am doing something incorrect or if this problem is still ongoing? What is the point of including these two fields if they don't work as intended?

Version(s):

Eclipse: Oxygen Release (4.7.0)

答:
I think there is misunderstanding about how these fields currently work, because

However, while the "includes" field works just as described, the "excludes" field does not.

this statement about "includes" field is incorrect as even shown on your screenshot - while only audio.* and linguistics.* are included, there are other packages in a report.

And here is why: these fields are about "Coverage Runtime" and correspond to respective options of JaCoCo agent - they allow to specify classes whose bytecode will be modified, they do not include/exclude classes from generation of report. Classes whose bytecode wasn't modified will be presented in report with "0%". Such specification is useful for the rare cases when bytecode modification interferes with code under test as stated in cited by you documentation:

For technical reasons it might be necessary to exclude certain classes from code coverage analysis. The following options configure the coverage agent to exclude certain classes from analysis. Except for performance optimization or technical corner cases these options are normally not required.

and few lines below:

Warning: ... Excluded classes will still show as not covered.

And so yes - there is still no exclusions for report.

However, this problem is well over a year old.

Eclipse EclEmma Project is open-source, so feel free to implement this feature and contribute back.


问:
How to remove Ext JS textfield displayed value?
I've defined a Text field class for specialised usage and inherit a new class through the base one. The problem textfield keeps display value on it's own display field. Click the link please:

Here is some snippets. Could anyone explain the situation?

Base Class:

```<code>Ext.define('---.---.base.OoTextFld',{
    extend: 'Ext.form.field.Text',
    xtype: 'ootextfld',
    grow: true,
    flex: 1,
    labelAlign:'right'
});
</code>```

Inherited one which is used on Form:

```<code>Ext.define('---.---.base.InheritedFld',{
    extend:'---.----.base.OoTextFld',
    xtype:'inheritedfld',

    requires: [],

    name:---.---.inherited,
    fieldLabel: ---.inherited,
    afterLabelTextTpl: ---.Globals.required,
    bind: '{currRec.inherited}',
    grow: false
});
</code>```

答: It seems that the field is bound to an integer model field, so that when the a record is created with no value specified for this field, it automatically gets 0 as value.

Body:
I've defined a Text field class for specialised usage and inherit a new class through the base one. The problem textfield keeps display value on it's own display field. Click the link please:

Here is some snippets. Could anyone explain the situation?

Base Class:

Ext.define('---.---.base.OoTextFld',{
    extend: 'Ext.form.field.Text',
    xtype: 'ootextfld',
    grow: true,
    flex: 1,
    labelAlign:'right'
});

Inherited one which is used on Form:

Ext.define('---.---.base.InheritedFld',{
    extend:'---.----.base.OoTextFld',
    xtype:'inheritedfld',

    requires: [],

    name:---.---.inherited,
    fieldLabel: ---.inherited,
    afterLabelTextTpl: ---.Globals.required,
    bind: '{currRec.inherited}',
    grow: false
});


答:
You can use reduce like below:

var temp1 = [
[{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
[{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
];

var result= temp1.reduce((o, m) => m.concat(o), []);
console.log(result);```
</div>
</div>
</p>

<p>In case you want to play with more ES6 features:</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>var temp1 = [
[{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
[{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
];

var result= temp1.reduce((o, m) => [...m, ...o], []);
console.log(result);</code>```

Title: convert array of array of objects into single array of objects in lodash

Body:
You can use reduce like below:

var temp1 = [
[{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
[{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
];

var result= temp1.reduce((o, m) => m.concat(o), []);
console.log(result);

In case you want to play with more ES6 features:

var temp1 = [
[{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
[{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
];

var result= temp1.reduce((o, m) => [...m, ...o], []);
console.log(result);


问:
I am not able to record Mobile Native Banking apps using JMeter
I am using JMeter 3.3.

I am not able to record traffic from our mobile banking app but I am able to record traffic from simple app which are less secure like weather channel. Can anyone help me here to make my mobile banking app work?

答:
Most probably you need to install JMeter's self-signed certificate onto your mobile device:

Locate ApacheJMeterTemporaryRootCA.crt file (it's being generated in "bin" folder of your JMeter installation when you start HTTP(S) Test Script Recorder)

Transfer it to device somehow (i.e. send it via email and open the attachment on the device side)

Import the certificate to the device, follow your mobile operating system instructions on how to do this

Assuming everything goes well JMeter should be able to intercept, decrypt and record mobile traffic (You might need a 3rd-party application to proxy the secure traffic, i.e. ProxyDroid for Android OS)

You can also consider using a cloud proxy which makes the process of installing the certificate easier, check out A Step by Step Guide to Performance Testing on Native Mobile Apps article for more details.


问:
How do I remove applications with broken applescript dictionaries
I've recently begun trying to figure out how to add support for applescript commands to macos apps and so far haven't gotten very far. I have, however, managed to fubar my installation of applescript dictionaries. This results in having about 15 or so entries of my failures in the scripting tool and I can't seem to get rid of them.

How do I get rid of the dictionaries?

答: Using the Scripting tool, you can get a list of all known dictionaries in Archive/Open Dictionary. The list contains a path entry, which will lead you to a file that you can delete. If you do, the dictionary will be removed from the system.</p>


问:
Creating a separate php file for WooCommerce hooks
I can't seem to find any documentation on this so maybe someone here can help. I have been adding all my WooCommerce hooks to my functions.php file but I would rather have all of them in a separate file to keep things tidy. Obviously I will need another php file for these but how do I link it to the functions.php file so that the code runs as it does now? Thanks </p>

答:
just create new file with your woocommerce hooks code name anything what u want.
Ex. woocommercehook.php and place file in theme folder.

in function.php file just include your woocommercehook.php file at last.

```<code>include("woocommercehook.php");
</code>```

Done. all work same as early.

Body:
just create new file with your woocommerce hooks code name anything what u want.
Ex. woocommercehook.php and place file in theme folder.

in function.php file just include your woocommercehook.php file at last.

include("woocommercehook.php");

Done. all work same as early.


问:
Javascript - code and decode from base64 using atob() and btoa() functions
I am trying some simple code - decode logic using the standard browser functionalities atob() and btoa() and I am encountering behaviors I can not fully understand.

I have written a very simple test case

```<code> it('converts from base64 to ascii', () => {
    const stringA = 'I am Enrico in Asci';
    const stringB = atob(stringA);
    const stringA1 = btoa(stringB);
    console.log('My ASCCI to binary and viceversa', stringA1);
    expect(stringA1).toBe(stringA);
  });
</code>```

The test case fails. What I see on the console of Chrome is

```<code>Expected 'IamEnricoinAscg=' to be 'I am Enrico in Asci'.
</code>```

Apparently all spaces have gone and end character is wrong.
Any help is appreciated.

答:
Just do it in the proper order ;)

    const stringA = 'I am Enrico in Asci';
    const stringB = btoa(stringA);
    const stringA1 = atob(stringB);
    console.log('stringA', stringA);
    console.log('stringA1', stringA1);
    console.log('equals', stringA === stringA1);```

Body:
I am trying some simple code - decode logic using the standard browser functionalities atob() and btoa() and I am encountering behaviors I can not fully understand.

I have written a very simple test case

 it('converts from base64 to ascii', () => {
    const stringA = 'I am Enrico in Asci';
    const stringB = atob(stringA);
    const stringA1 = btoa(stringB);
    console.log('My ASCCI to binary and viceversa', stringA1);
    expect(stringA1).toBe(stringA);
  });

The test case fails. What I see on the console of Chrome is

Expected 'IamEnricoinAscg=' to be 'I am Enrico in Asci'.

Apparently all spaces have gone and end character is wrong.
Any help is appreciated.


问:
Realm Object Server: Access Denied Error after successful login using Custom Authentication
I am trying to setup a Realm Object Server for my company's mobile application. I have to use a custom authentication to allow users to access the database.

```<code>import { BasicServer } from 'realm-object-server'
import * as path from 'path'
import { AuthProvider } from './lib/auth'

const server = new BasicServer()

server.start({
  dataPath: path.join(__dirname, '../data'),
  address: '192.168.0.24',
  authProviders: [new AuthProvider()]
 })
 .then(() => {
    console.log(`Realm Object Server was started on ${server.address}`)
 })
 .catch(err => {
    console.error(`Error starting Realm Object Server: ${err.message}`)
 })
</code>```

Here is the custom auth that I have to apply. The authentication will be done by another backend server.

```<code>import { post } from 'superagent'
import { auth, User, errors } from 'realm-object-server'
import { pick } from 'lodash';

export class AuthProvider extends auth.AuthProvider {

  name = 'authprovider'

  authenticateOrCreateUser(body: any): Promise<User> {
   return post('https://XYZ/signin')
  .send({
    'email': body.user_info.email,
    'password': body.user_info.password
  })
  .then((successResponseJSON: any) => {
    return this.service.createOrUpdateUser(
      successResponseJSON.body.id,
      this.name, // this is the name of the provider,
      false, // this is if the user should or should not be an admin
      pick(successResponseJSON.body, ['id', 'email'])
    )
  })
  .catch(err => {
    throw new errors.realm.InvalidCredentials({ detail: err })
  })
 }
}
</code>```

I have added code for custom authentication to the example for provided by realm to add data to the realm server. Here I am asking that the user be authenticated using 'authprovider'

```<code>var URL = "192.168.0.24:9080"

Realm.Sync.User.registerWithProvider(`http://${URL}`, {
provider: 'authprovider',
providerToken: null,
userInfo: {
  email: username,
  password: password
}
 }).then(user => {
console.log('user', user, user.identity)
Realm.open({
  sync: {
    url: `realm://${URL}/abc`,
    user: user
  },
  schema: [TickerSchema],
})
</code>```

Even though the user is successfully authenticated, I am getting access denied error. I am not able to understand why.

```<code>user User {} 9ae6033cd9b55e3aca62a291af8726ea
Unhandled session token refresh error { Error: The path is invalid or current user has no access.
at new AuthError (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/errors.js:22:25)
at performFetch.then.then (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/user-methods.js:105:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
name: 'AuthError',
message: 'The path is invalid or current user has no access.',
stack: 'Error: The path is invalid or current user has no access.\n    at new AuthError (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/errors.js:22:25)\n    at performFetch.then.then (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/user-methods.js:105:29)\n    at <anonymous>\n    at process._tickCallback (internal/process/next_tick.js:188:7)',
type: 'https://realm.io/docs/object-server/problems/access-denied',
title: 'The path is invalid or current user has no access.',
status: 403,
code: 614 }
</code>```

答: The realm url was incorrect: it should have been realm://${URL}/~/abc instead of realm://${URL}/abc

Body:
I am trying to setup a Realm Object Server for my company's mobile application. I have to use a custom authentication to allow users to access the database.

import { BasicServer } from 'realm-object-server'
import * as path from 'path'
import { AuthProvider } from './lib/auth'

const server = new BasicServer()

server.start({
  dataPath: path.join(__dirname, '../data'),
  address: '192.168.0.24',
  authProviders: [new AuthProvider()]
 })
 .then(() => {
    console.log(`Realm Object Server was started on ${server.address}`)
 })
 .catch(err => {
    console.error(`Error starting Realm Object Server: ${err.message}`)
 })

Here is the custom auth that I have to apply. The authentication will be done by another backend server.

import { post } from 'superagent'
import { auth, User, errors } from 'realm-object-server'
import { pick } from 'lodash';

export class AuthProvider extends auth.AuthProvider {

  name = 'authprovider'

  authenticateOrCreateUser(body: any): Promise<User> {
   return post('https://XYZ/signin')
  .send({
    'email': body.user_info.email,
    'password': body.user_info.password
  })
  .then((successResponseJSON: any) => {
    return this.service.createOrUpdateUser(
      successResponseJSON.body.id,
      this.name, // this is the name of the provider,
      false, // this is if the user should or should not be an admin
      pick(successResponseJSON.body, ['id', 'email'])
    )
  })
  .catch(err => {
    throw new errors.realm.InvalidCredentials({ detail: err })
  })
 }
}

I have added code for custom authentication to the example for provided by realm to add data to the realm server. Here I am asking that the user be authenticated using 'authprovider'

var URL = "192.168.0.24:9080"

Realm.Sync.User.registerWithProvider(`http://${URL}`, {
provider: 'authprovider',
providerToken: null,
userInfo: {
  email: username,
  password: password
}
 }).then(user => {
console.log('user', user, user.identity)
Realm.open({
  sync: {
    url: `realm://${URL}/abc`,
    user: user
  },
  schema: [TickerSchema],
})

Even though the user is successfully authenticated, I am getting access denied error. I am not able to understand why.

user User {} 9ae6033cd9b55e3aca62a291af8726ea
Unhandled session token refresh error { Error: The path is invalid or current user has no access.
at new AuthError (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/errors.js:22:25)
at performFetch.then.then (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/user-methods.js:105:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
name: 'AuthError',
message: 'The path is invalid or current user has no access.',
stack: 'Error: The path is invalid or current user has no access.\n    at new AuthError (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/errors.js:22:25)\n    at performFetch.then.then (/home/sukumar/code_snippets/realm-test/node_modules/realm/lib/user-methods.js:105:29)\n    at <anonymous>\n    at process._tickCallback (internal/process/next_tick.js:188:7)',
type: 'https://realm.io/docs/object-server/problems/access-denied',
title: 'The path is invalid or current user has no access.',
status: 403,
code: 614 }


问:
I'm making several requests for JSONP data using jQuery, how do I figure out which request goes with which result?
The results comeback out of order from the sequence I made them.  If I wait for each request to finish the results are OK but it takes longer than I'd like.  Is there a way for me to keep track of which result belongs to which request?

EDIT: Per request I'm adding the code that performs the JSON calls.

```<code>for (var i = 0; i < rssLinkDB.length; i++) {
  jQuery.getJSON(encoded, function(data){
    yLinkDB.push(data.query.results.result);
    index++;
    if (index == 10) {
      state = "RequestLikes";
    }
  });
}
</code>```

答:
Make the callback function names unique/dynamic, it's best to namespace these functions so that you don't pollute your global scope.</p>

```<code>callbackHandlersNS.callback1 = function () {/* handle first request*/};
callbackHandlersNS.callback2 = function () {/* handle second request*/};
...
</code>```

Body:
The results comeback out of order from the sequence I made them.  If I wait for each request to finish the results are OK but it takes longer than I'd like.  Is there a way for me to keep track of which result belongs to which request?

EDIT: Per request I'm adding the code that performs the JSON calls.

for (var i = 0; i < rssLinkDB.length; i++) {
  jQuery.getJSON(encoded, function(data){
    yLinkDB.push(data.query.results.result);
    index++;
    if (index == 10) {
      state = "RequestLikes";
    }
  });
}

Body:
Make the callback function names unique/dynamic, it's best to namespace these functions so that you don't pollute your global scope.

callbackHandlersNS.callback1 = function () {/* handle first request*/};
callbackHandlersNS.callback2 = function () {/* handle second request*/};
...


问:
Liquibase is trying to execute change-set which has already been executed previously and thus throwing error that table already exist

    @Bean
    public SpringLiquibase liquibase()  {
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setDataSource(vsDataSource());
        liquibase.setChangeLog("classpath:liquibase/avt_changelog_master.xml");
        return liquibase;
    }
```

This is how I am initializing liquibase through a spring boot application.

I have checked databasechangelog table and I can find that for that changeset entry is there and it has been executed successfully.

Why liquibase is not skipping that changeset and executing new unique changeset Ids.

答:
Problem could be with name of your changelog. If you executed that changelog from within other application/maven/... and you didn't specified the logicalFilePath then liquibase could think of it as a different changelog. Try to set logicalFilePath in your changelog definition and try to execute it then.

this is example:

<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd"
                   logicalFilePath="db-changelog-master.xml">
```

Body:
    @Bean
    public SpringLiquibase liquibase()  {
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setDataSource(vsDataSource());
        liquibase.setChangeLog("classpath:liquibase/avt_changelog_master.xml");
        return liquibase;
    }

This is how I am initializing liquibase through a spring boot application.

I have checked databasechangelog table and I can find that for that changeset entry is there and it has been executed successfully.

Why liquibase is not skipping that changeset and executing new unique changeset Ids.


问:
Load different UI for different devices in nativescript
I am new to Native script with Angular2. I am developing application for Tablet and Mobile devices. I want to load different UI (html) files for different devices. I created four files like,

```<code>1) test.html
2) test.minWH320.html
3) test.minWH480.html
4) test.minWH600.html
5) test.minWH700.html
</code>```

But it is loading test.html file for all devices
 Can anybody help me..Please

答:
I would suggest you to bootstrap your app according to screen size i:e use @media queries. which will load the page with a different layout for different screens.

More on media queries

Angular a.k.a one framework ticks a lot of boxes when comes to out of the box support for mobile devices

Body:
I am new to Native script with Angular2. I am developing application for Tablet and Mobile devices. I want to load different UI (html) files for different devices. I created four files like,

1) test.html
2) test.minWH320.html
3) test.minWH480.html
4) test.minWH600.html
5) test.minWH700.html

But it is loading test.html file for all devices
 Can anybody help me..Please


问:
HTML mobile button show/hide after few seconds
i have for my mobilesite some buttons.

```<code><div class="menubottom" id="menumobile">
    <div >
        <div class="mobilebutton displaynone" id="mobilebuttonLeft" style="float:left;" onclick="swipeRight();"><i class="fa fa-chevron-circle-left fa-3x" aria-hidden="true"></i></div>
        <div class="mobilebutton" id="mobilebuttonRight" style="float:right;" onclick="swipeLeft()"><i class="fa fa-chevron-circle-right fa-3x" aria-hidden="true"></i></div>
    </div>

</div>
</code>```

now i want them to disappear if a amount of time with no TouchInput passes away.
And if i Touch again on the display the buttons should be appear again.
I have jquery and jquery mobile installed but i cant find a good resolution for my problem. Did you have any idea?

答:
now i want them to disappear if a amount of time with no TouchInput
  passes away

You can do setTimeout which will hide the menu after 2 seconds

```<code>function hideMenu(){
    setTimeout( function(){
      $ ( "#menumobile" ).hide();
    }, 2000);
}
</code>```

To make it reappear again on click, just bind a touchend event

```<code>$(document).on( "touchend click", function(){
  $ ( "#menumobile" ).show();
  hideMenu(); //hide again after 2 seconds
})
</code>```

Body:
i have for my mobilesite some buttons.

now i want them to disappear if a amount of time with no TouchInput passes away.
And if i Touch again on the display the buttons should be appear again.
I have jquery and jquery mobile installed but i cant find a good resolution for my problem. Did you have any idea?

Body:
now i want them to disappear if a amount of time with no TouchInput
  passes away

You can do setTimeout which will hide the menu after 2 seconds

function hideMenu(){
    setTimeout( function(){
      $ ( "#menumobile" ).hide();
    }, 2000);
}

To make it reappear again on click, just bind a touchend event

$(document).on( "touchend click", function(){
  $ ( "#menumobile" ).show();
  hideMenu(); //hide again after 2 seconds
})


问:
How to find minimum of BigDecimal field in collection with java streams?
I want to use java streams to iterate a list and find the BigDecimal minimum price. The following illustrates, but does not work (because min() cannot accept BigDecimal.

```<code>class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);
</code>```

答:
Since BigDecimal already is Comparable, it is as simple as :

```<code> BigDecimal min = products
        .stream()
        .map(Product::getPrice)
        .min(Comparator.naturalOrder())
        .orElse(BigDecimal.ZERO);
</code>```

Body:
I want to use java streams to iterate a list and find the BigDecimal minimum price. The following illustrates, but does not work (because min() cannot accept BigDecimal.

class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);

Body:
Since BigDecimal already is Comparable, it is as simple as :

 BigDecimal min = products
        .stream()
        .map(Product::getPrice)
        .min(Comparator.naturalOrder())
        .orElse(BigDecimal.ZERO);


答:
You can use touchstart and touchend event for hiding show mobilebutton

settimeout of 3s for hide button after touchend

```<code>$("body").on('touchstart mousedown',function (e){
    $('.mobilebutton').show();
});
$("body").on('touchend',function (e){
    setTimeout(function(){
        $('.mobilebutton').hide();
    }, 3000);
});
</code>```

Title: HTML mobile button show/hide after few seconds

Body:
You can use touchstart and touchend event for hiding show mobilebutton

settimeout of 3s for hide button after touchend

$("body").on('touchstart mousedown',function (e){
    $('.mobilebutton').show();
});
$("body").on('touchend',function (e){
    setTimeout(function(){
        $('.mobilebutton').hide();
    }, 3000);
});


问:
Rails 5 Foundation 6 not loading css
I cannot get foundation + rails working. I've installed foundation gem without problems and when I create simple page with foundation content it can't load stylesheets.

Example:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>

    <%= stylesheet_link_tag    "application" %>
    <%= javascript_include_tag "application", 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
  </head>

  <body>
    <nav class="top-bar" data-topbar role="navigation">
      <ul class="title-area">
        <li class="name">
          <h1><a href="#">My Site</a></h1>
        </li>
         <!-- Remove the class "menu-icon" to get rid of menu icon. Take out "Menu" to just have icon alone -->
        <li class="toggle-topbar menu-icon"><a href="#"><span>Menu</span></a></li>
      </ul>

      <section class="top-bar-section">
        <!-- Right Nav Section -->
        <ul class="right">
          <li class="active"><a href="#">Right Button Active</a></li>
          <li class="has-dropdown">
            <a href="#">Right Button Dropdown</a>
            <ul class="dropdown">
              <li><a href="#">First link in dropdown</a></li>
              <li class="active"><a href="#">Active link in dropdown</a></li>
            </ul>
          </li>
        </ul>

        <!-- Left Nav Section -->
        <ul class="left">
          <li><a href="#">Left Nav Button</a></li>
        </ul>
      </section>
    </nav>
    <%= yield %>

  </body>
</code>```

Rails version: 5.0.2

Foundation: 6.3.1.0

Any ideas how to get this working ?

答:
I had this issue working with rails 5 and foundation 6. It had been a while since last using rails and I was a bit rusty. I had spent a good couple of hours scratching my head and searching the net.

I use rvm to keep all of my gems seperate so decided to take a look in my gemset and found that I had two versions of the gem installed:

foundation-rails-5.4.5.0/ and foundation-rails-6.4.1.3/

After removing version 5.4.5.0 I ran the rails g foundation:install command again, this fixed the issue.

I assume I ran the installer using the older version which generates a completely different foundation_and_overrides.scss file to the new version.

this is what the new version looks like:

```<code>@charset 'utf-8';

@import 'settings';
@import 'foundation';

// If you'd like to include motion-ui the foundation-rails gem comes prepackaged with it, uncomment the 3 @imports, if you are not using the gem you need to install the motion-ui sass package.
//
// @import 'motion-ui/motion-ui';

// We include everything by default.  To slim your CSS, remove components you don't use.

@include foundation-global-styles;
@include foundation-xy-grid-classes;
//@include foundation-grid;
//@include foundation-flex-grid;
@include foundation-flex-classes;
@include foundation-typography;
@include foundation-forms;
@include foundation-button;
@include foundation-accordion;
@include foundation-accordion-menu;
@include foundation-badge;
@include foundation-breadcrumbs;
@include foundation-button-group;
@include foundation-callout;
@include foundation-card;
@include foundation-close-button;
@include foundation-menu;
@include foundation-menu-icon;
@include foundation-drilldown-menu;
@include foundation-dropdown;
@include foundation-dropdown-menu;
@include foundation-responsive-embed;
@include foundation-label;
@include foundation-media-object;
@include foundation-off-canvas;
@include foundation-orbit;
@include foundation-pagination;
@include foundation-progress-bar;
@include foundation-slider;
@include foundation-sticky;
@include foundation-reveal;
@include foundation-switch;
@include foundation-table;
@include foundation-tabs;
@include foundation-thumbnail;
@include foundation-title-bar;
@include foundation-tooltip;
@include foundation-top-bar;
@include foundation-visibility-classes;
@include foundation-float-classes;

// If you'd like to include motion-ui the foundation-rails gem comes prepackaged with it, uncomment the 3 @imports, if you are not using the gem you need to install the motion-ui sass package.
//
// @include motion-ui-transitions;
// @include motion-ui-animations;
</code>```

The older version was largely commented out variable declarations and only inlcluded two uncommented imports:

```<code>@import 'foundation/functions' //which gave a file not found error
@import 'foundation'
</code>```

Hopefully this will help others in this situation.

Title: Rails 5 Foundation 6 not loading css

Body:
I cannot get foundation + rails working. I've installed foundation gem without problems and when I create simple page with foundation content it can't load stylesheets.

Example:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>

    <%= stylesheet_link_tag    "application" %>
    <%= javascript_include_tag "application", 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>

My Site

Menu

Right Button Active

            Right Button Dropdown

First link in dropdown

Active link in dropdown

Left Nav Button

    <%= yield %>

Rails version: 5.0.2

Foundation: 6.3.1.0

Any ideas how to get this working ?

Body:
I had this issue working with rails 5 and foundation 6. It had been a while since last using rails and I was a bit rusty. I had spent a good couple of hours scratching my head and searching the net.

I use rvm to keep all of my gems seperate so decided to take a look in my gemset and found that I had two versions of the gem installed:

foundation-rails-5.4.5.0/ and foundation-rails-6.4.1.3/

After removing version 5.4.5.0 I ran the rails g foundation:install command again, this fixed the issue.

I assume I ran the installer using the older version which generates a completely different foundation_and_overrides.scss file to the new version.

this is what the new version looks like:

@charset 'utf-8';

@import 'settings';
@import 'foundation';

// If you'd like to include motion-ui the foundation-rails gem comes prepackaged with it, uncomment the 3 @imports, if you are not using the gem you need to install the motion-ui sass package.
//
// @import 'motion-ui/motion-ui';

// We include everything by default.  To slim your CSS, remove components you don't use.

@include foundation-global-styles;
@include foundation-xy-grid-classes;
//@include foundation-grid;
//@include foundation-flex-grid;
@include foundation-flex-classes;
@include foundation-typography;
@include foundation-forms;
@include foundation-button;
@include foundation-accordion;
@include foundation-accordion-menu;
@include foundation-badge;
@include foundation-breadcrumbs;
@include foundation-button-group;
@include foundation-callout;
@include foundation-card;
@include foundation-close-button;
@include foundation-menu;
@include foundation-menu-icon;
@include foundation-drilldown-menu;
@include foundation-dropdown;
@include foundation-dropdown-menu;
@include foundation-responsive-embed;
@include foundation-label;
@include foundation-media-object;
@include foundation-off-canvas;
@include foundation-orbit;
@include foundation-pagination;
@include foundation-progress-bar;
@include foundation-slider;
@include foundation-sticky;
@include foundation-reveal;
@include foundation-switch;
@include foundation-table;
@include foundation-tabs;
@include foundation-thumbnail;
@include foundation-title-bar;
@include foundation-tooltip;
@include foundation-top-bar;
@include foundation-visibility-classes;
@include foundation-float-classes;

// If you'd like to include motion-ui the foundation-rails gem comes prepackaged with it, uncomment the 3 @imports, if you are not using the gem you need to install the motion-ui sass package.
//
// @include motion-ui-transitions;
// @include motion-ui-animations;

The older version was largely commented out variable declarations and only inlcluded two uncommented imports:

@import 'foundation/functions' //which gave a file not found error
@import 'foundation'

Hopefully this will help others in this situation.


问:
Converting Java date string to JavaScript date
Is there any JavaScript library that takes Java's SimpleDateFormat pattern and parses a date/time string into a Date object?

For example, given "2010-12-20" and "yyyy-MM-dd", the function would parse "2010-12-20" and return a JavaScript Date.

I noticed that jQuery UI's Date Picker can format and parse a date string, but it doesn't work with a time string.

Thanks.

答: This might be what you want: http://www.timdown.co.uk/code/simpledateformat.php</p>


问:
convert array of array of objects into single array of objects in lodash
I have an array of arrays of objects as below which is generated by _.filter lodash function which returns objects for the matched values:

```<code>const matchedPositions = _.filter(allPositions, function(o) {
return o.company.toLowerCase() === value.toLowerCase();
});//matchedPositions have array of objects
let allCheckboxFiltered = [...allCheckboxFiltered, matchedPositions]; //allCheckboxFiltered  have below results

   [
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
    ];
</code>```

I wanted as below intended result;

```<code>[
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}
];
</code>```

I have tried reduce function to generate such intended result as below:

```<code>let result = temp1.reduce(function(res, obj) {
console.log(res, obj);
Object.keys(obj).forEach(function(k) {
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
}, []);
</code>```

Above code is not generating the result, I wanted. I have tried other stuffs e.g. lodash functions as well but all in vain.

Thanks

答:
You can use Array.concat in order to spread the inner array.

var temp1 = [
  [{
      serialNo: 9,
      sector: null,
      company: "AMERICAN LIFE INSURANCE COMPANY",
      location: null,
      position: "INSURANCE Operations  MANAGER"
    },
    {
      serialNo: 9,
      sector: null,
      company: "AMERICAN LIFE INSURANCE COMPANY",
      location: null,
      position: "INSURANCE Operations  MANAGER"
    }
  ],
  [{
      serialNo: 9,
      sector: null,
      company: "AMERICAN LIFE INSURANCE COMPANY",
      location: null,
      position: "INSURANCE Operations  MANAGER"
    },
    {
      serialNo: 9,
      sector: null,
      company: "AMERICAN LIFE INSURANCE COMPANY",
      location: null,
      position: "INSURANCE Operations  MANAGER"
    },
    {
      serialNo: 9,
      sector: null,
      company: "AMERICAN LIFE INSURANCE COMPANY",
      location: null,
      position: "INSURANCE Operations  MANAGER"
    }
  ]
];

const result = temp1.reduce((res, currentArr) => res.concat(currentArr), [])
console.log(result);```

Body:
I have an array of arrays of objects as below which is generated by _.filter lodash function which returns objects for the matched values:

const matchedPositions = _.filter(allPositions, function(o) {
return o.company.toLowerCase() === value.toLowerCase();
});//matchedPositions have array of objects
let allCheckboxFiltered = [...allCheckboxFiltered, matchedPositions]; //allCheckboxFiltered  have below results

   [
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}],
    [{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
    {serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}]
    ];

I wanted as below intended result;

[
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"},
{serialNo: 9, sector: null, company: "AMERICAN LIFE INSURANCE COMPANY", location: null, position: "INSURANCE Operations  MANAGER"}
];

I have tried reduce function to generate such intended result as below:

let result = temp1.reduce(function(res, obj) {
console.log(res, obj);
Object.keys(obj).forEach(function(k) {
res[k] = res[k] || [];
res[k] = res[k].concat(obj[k]);
});
return res;
}, []);

Above code is not generating the result, I wanted. I have tried other stuffs e.g. lodash functions as well but all in vain.

Thanks


问:
Get week in array of days
I have a array of days:

```<code>var days = [1,5,7,9,12,16,23,27,45,66];
</code>```

Now I want to find out which days belong to which week. i.e.

```<code>Week 1: 1,5,7
Week 2: 9,12
Week 3: 23,27
</code>```

and so on.

How can I achieve that?

答:
deceze's comment was what I was looking for, thank you.</p>

```<code>var days = [1, 5, 7, 9, 12, 16, 23, 27, 45, 66];
var weekNumber;

for (i= 0; i <= days.length; i++) {
 weekNumber = Math.ceil(days[i] / 7);

}
</code>```

Title: Get week in array of days

Body:
I have a array of days:

var days = [1,5,7,9,12,16,23,27,45,66];

Now I want to find out which days belong to which week. i.e.

Week 1: 1,5,7
Week 2: 9,12
Week 3: 23,27

and so on.

How can I achieve that?

Body:
deceze's comment was what I was looking for, thank you.

var days = [1, 5, 7, 9, 12, 16, 23, 27, 45, 66];
var weekNumber;

for (i= 0; i <= days.length; i++) {
 weekNumber = Math.ceil(days[i] / 7);

}


问:
how to compare date with GETDATE() in sql server 2008
I have a stored procedure, which is used to insert some kind of information to table 'demotable', in that i have a field loginTime where datatype is dateTime.
i am using GETDATE() to get the current datetime, problem is i want to compare whether this GETDATE() is lower than 9:00 AM and then make it as 9:00AM, if not lower keep the output as it is without any changes. -using microsoft sql server 2008.

below is my sample stored procedure

```<code>         //Beg Stored Procedure Contents...

            insert into dbo.demoTable([loginTime],[nStatus]) values(GETDATE(),'1')

         //End
</code>```

答:
-- Should work on 2008 and above

SELECT CASE WHEN DATEPART(HOUR,GETDATE()) < 9 THEN DATEADD(HOUR,9,CAST(GETDATE() AS DATE)) ELSE GetDate() END

Body:
I have a stored procedure, which is used to insert some kind of information to table 'demotable', in that i have a field loginTime where datatype is dateTime.
i am using GETDATE() to get the current datetime, problem is i want to compare whether this GETDATE() is lower than 9:00 AM and then make it as 9:00AM, if not lower keep the output as it is without any changes. -using microsoft sql server 2008.

below is my sample stored procedure

         //Beg Stored Procedure Contents...

            insert into dbo.demoTable([loginTime],[nStatus]) values(GETDATE(),'1')

         //End


问:
How do I remove an object from an array with JavaScript?
I have an JavaScript object like this:

```<code>id="1";
name = "serdar";
</code>```

and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:

```<code>obj[1].remove();
</code>```

答:
var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];

// get index of object with id:37

var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);

// remove object

apps.splice(removeIndex, 1);

Body:
I have an JavaScript object like this:

id="1";
name = "serdar";

and I have an Array which contains many objects of above. How can I remove an object from that array such as like that:

obj[1].remove();


问:
PHP - Zip extractTo() performance
I'm running PHP 5.6.3.
One of my professional project includes a dezip function :

```<code>// ZIP file to extract
$my_file = "repository.zip";

$zip = new ZipArchive;
if ($zip->open($my_file) === TRUE)
{
    //Unpack all files from zip
    $zip->extractTo($this->target_directory);
}

$zip->close();
</code>```

... which is processed on a big ZIP file (~300Mo).

I made many excution time benchmark and I found that the extractTo() function is more than 90%/95% (20sec.) of the total processing time ! Worst of all, the ZIP size is going to increase in the next weeks (maybe up to 500 Mo).

Is there a way to optimize this part of my script ?
Knowing that I do have to extract all the files from the ZIP.

Thanks.

答:
Is there a way to optimize this part of my script ?

No - its a single line of code, called once. It should be obvious that there is no way to optimize it.

I suspect what you really want to know is if you can get the file unzipped sonner - and that is a very different question.

the extractTo() function is more than 90%/95% (20sec.) of the total processing time

Of the elapsed time? CPU time? PHP execution time?

There may be scope for getting the results faster, but you are not asking the right questions. You are not going to get a solution here - we don't have access to your system to fix it for you.

Since you've told us nothing about the OS and hardware this sits on, we are further constrained in the advice we can give. Moving to a faster CPU might help - but based on the information you've provided we don't know if its the CPU or the storage I/O which is the bottleneck here. How you make the whole system go faster would fill a large book (I know, I've written one).

Doing the extraction outside of PHP might help.

Using a different compression algorithm might help.

Creating multiple files and unzipping them in parallel would probably help.

....but you've also told us nothing about the constraints here.

Title: PHP - Zip extractTo() performance

Body:
I'm running PHP 5.6.3.
One of my professional project includes a dezip function :

// ZIP file to extract
$my_file = "repository.zip";

$zip = new ZipArchive;
if ($zip->open($my_file) === TRUE)
{
    //Unpack all files from zip
    $zip->extractTo($this->target_directory);
}

$zip->close();

... which is processed on a big ZIP file (~300Mo).

I made many excution time benchmark and I found that the extractTo() function is more than 90%/95% (20sec.) of the total processing time ! Worst of all, the ZIP size is going to increase in the next weeks (maybe up to 500 Mo).

Is there a way to optimize this part of my script ?
Knowing that I do have to extract all the files from the ZIP.

Thanks.


问:
static import not working in lombok builder in intelliJ
I am using Lombok in IntelliJ. Though everything else is working fine when I try to do the static import of the Lombok builder, IntelliJ build project doesn't find the builder class. If you don't use static import, it works fine.</p>

答:
This is a known bug, and not something that's easy to fix. Static imports are resolved before the annotation processors are run. This is a problem in javac, not lombok.

Disclosure: I am a lombok developer.


问:
Simple cocoa calculator
I'm in the process of teaching myself basic cocoa application development and so I'm stepping up to the classic "calculator" project.

What I was wondering is this: to create the actual calculator interface would it be best to just add 4 rows of 4 NSButton controls and edit them to have the label/functionality I want or is there a more efficient way to create the layout?

I know this is a basic application but following OS X rules I want my code to be as efficient as possible so I want to make sure I'm doing it right.

Thanks for any help guys.

答: There's really nothing wrong with creating 4x4 buttons and you'll have the most flexibility with this approach. The most efficient way though would be to use an NSMatrix. To create a matrix of buttons in Interface Builder, create one button (your prototype), then select Layout->Embed Objects in->Matrix from the menu. When you now select the matrix, you can specify 4 rows and 4 columns in the Attributes tab of the inspector window.</p>

Title: Simple cocoa calculator


问:
data-callback is called after Google recaptcha is shown in IE11
Got some legacy to support. Details:

We have Google  recaptcha on our site which is normally called after form fields validation is checked in function defined with data-callback attr.

```<code><form class="v_form" id="c-form">
    <div class="label erorr fullName-error" >Please enter your name</div>
    <input type="text" class="simple-input" name="fullName" placeholder="Full name..." required>

    <div class="label">Email*</div>
    <div class="label erorr email-error" >Please enter your e-mail</div>
    <input type="email" class="simple-input" name="email" placeholder="Email..." required>

    <button class="btn send g-recaptcha" data-sitekey="bla-bla" data-callback='onSubmitContact' data-size="invisible">Send!</button>
</form>
</code>```

in JS:

```<code>function onSubmitContact(){
  ... //some input values validation, if not valid return false - else true;
return false;
}
</code>```

It works well in Chrome - so if , for example, any field is empty - JS function return false and recaptcha is not even shown.
In IE11 - it anyway first shows recaptcha window, I select correct answer - and then it calls data-callback function. And then recaptcha crashes with error and stops working:

```<code>SCRIPT5007: Unable to get property 'toString' of undefined or null reference
File: recaptcha__en.js, Line: 376, Column: 41
</code>```

Can I somehow make it work correctly in IE like in Chrome?

答:
I found a workaround for my question but with remark:
1. I decided to implement manual creation of google recaptcha on Load event.

```<code><body onload="onLoad()">
...
<form>
<button class="btn send" id="submit_button">Send!</button>
<div id='recaptcha' class="g-recaptcha"
      data-sitekey="<somekey>"
      data-callback="onSubmit"
      data-size="invisible">
</div>
</form>
...

<script>
function onLoad() {
    window.grecaptcha_id = window.grecaptcha.render('recaptcha', {});
}

function onSubmit(response) { // recaptcha callback
    sendForm();
}

 $('#submit_button').on('click', function (e) {
var error = validateForm(); // validate function, if no error - false
if(error) {
//mark with red, no sending
} else {
grecaptcha.execute(grecaptcha_id);
})
    <script/>
</code>```

So first I validate on Submit by myself and then, if succeeded - I run
grecaptcha.execute to start recaptcha check.

Remarks:

When to show pictures to choose in hidden captcha - google decides by itself. I cannot affect this.

grecaptcha.reset doesn't work. Whether I call it or not - anyway recaptcha sends uservalidate request to google and according to response decides about showing captcha.

nothing really was changed in app logic - just another way to call recaptcha - but now I have no error in IE11.

Body:
Got some legacy to support. Details:

We have Google  recaptcha on our site which is normally called after form fields validation is checked in function defined with data-callback attr.

<form class="v_form" id="c-form">

Please enter your name

    <input type="text" class="simple-input" name="fullName" placeholder="Full name..." required>

Email*

Please enter your e-mail

    <input type="email" class="simple-input" name="email" placeholder="Email..." required>

    <button class="btn send g-recaptcha" data-sitekey="bla-bla" data-callback='onSubmitContact' data-size="invisible">Send!</button>
</form>

in JS:

function onSubmitContact(){
  ... //some input values validation, if not valid return false - else true;
return false;
}

It works well in Chrome - so if , for example, any field is empty - JS function return false and recaptcha is not even shown.
In IE11 - it anyway first shows recaptcha window, I select correct answer - and then it calls data-callback function. And then recaptcha crashes with error and stops working:

SCRIPT5007: Unable to get property 'toString' of undefined or null reference
File: recaptcha__en.js, Line: 376, Column: 41

Can I somehow make it work correctly in IE like in Chrome?

Body:
I found a workaround for my question but with remark:
1. I decided to implement manual creation of google recaptcha on Load event.

<body onload="onLoad()">
...
<form>
<button class="btn send" id="submit_button">Send!</button>
<div id='recaptcha' class="g-recaptcha"
      data-sitekey="<somekey>"
      data-callback="onSubmit"
      data-size="invisible">
</div>
</form>
...

<script>
function onLoad() {
    window.grecaptcha_id = window.grecaptcha.render('recaptcha', {});
}

function onSubmit(response) { // recaptcha callback
    sendForm();
}

 $('#submit_button').on('click', function (e) {
var error = validateForm(); // validate function, if no error - false
if(error) {
//mark with red, no sending
} else {
grecaptcha.execute(grecaptcha_id);
})
    <script/>

So first I validate on Submit by myself and then, if succeeded - I run
grecaptcha.execute to start recaptcha check.

Remarks:

When to show pictures to choose in hidden captcha - google decides by itself. I cannot affect this.

grecaptcha.reset doesn't work. Whether I call it or not - anyway recaptcha sends uservalidate request to google and according to response decides about showing captcha.

nothing really was changed in app logic - just another way to call recaptcha - but now I have no error in IE11.


问:
Using hops and join against datasets, how to get the highest value of a certain property. DTL
I'm running hops against a dataset in sesam and my output is as the example below, my problem is that need a join where i only end up with the property with the highest priority. </p>

```<code>[{
    "id": "AAA",
    "priority": 10
  }, {
    "id": "AAB",
    "priority": 7
  }]
</code>```

答:
You can solve this using "sorted", "reverse", "first" and "path":

```<code>{
  "_id": "sort-by-prop",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "foo",
      "bar": [{
        "id": "AAA",
        "priority": 10
      }, {
        "id": "AAB",
        "priority": 5
      }]
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["copy", "_id"],
        ["add", "foo",
          ["path", "id",
            ["first",
              ["reversed",
                ["sorted", "_.priority", "_S.bar"]
              ]
            ]
          ]
        ]
      ]
    }
  }
}
</code>```

The result will be:

```<code>[
  {
    "_id": "foo",
    "foo": "AAA"
  }
]
</code>```

Body:
I'm running hops against a dataset in sesam and my output is as the example below, my problem is that need a join where i only end up with the property with the highest priority.

[{
    "id": "AAA",
    "priority": 10
  }, {
    "id": "AAB",
    "priority": 7
  }]

Body:
You can solve this using "sorted", "reverse", "first" and "path":

{
  "_id": "sort-by-prop",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "foo",
      "bar": [{
        "id": "AAA",
        "priority": 10
      }, {
        "id": "AAB",
        "priority": 5
      }]
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["copy", "_id"],
        ["add", "foo",
          ["path", "id",
            ["first",
              ["reversed",
                ["sorted", "_.priority", "_S.bar"]
              ]
            ]
          ]
        ]
      ]
    }
  }
}

The result will be:

[
  {
    "_id": "foo",
    "foo": "AAA"
  }
]


问:
No known package when getting name for resource number 0xffffffff
```<code>W/ResourceType( 2739): No known package when getting name for resource number 0xffffffff
I/System.out( 2739): Resource not found for -1. Moving on.
</code>```

When I run automated UI tests I see the above two lines basically for every view which is shown. So far I could not isolate the "problem" any further. The UI tests pass more/less without problems and the UI looks just fine. When starting the app regularly, not from instrumentation, the logs do not appear.

This output, except for being noisy, does not come with any exception or immediate problem. So this is more a curiosity thing.

I am pretty sure it is not misuse of TextView.setText(), because everything works as expected and the log is only visible during instrumentation.

Can anybody give me a clue what to look for?

答:
Appreciate that this is an old post but found it while investigating this issue.

This warning was moved to calabash-android-server (and changed slightly since this post. From the next version of the server it should stop raising this error.

We're also looking in to why the error occurs so I'll update this post if we make any progress.

Body:
W/ResourceType( 2739): No known package when getting name for resource number 0xffffffff
I/System.out( 2739): Resource not found for -1. Moving on.

When I run automated UI tests I see the above two lines basically for every view which is shown. So far I could not isolate the "problem" any further. The UI tests pass more/less without problems and the UI looks just fine. When starting the app regularly, not from instrumentation, the logs do not appear.

This output, except for being noisy, does not come with any exception or immediate problem. So this is more a curiosity thing.

I am pretty sure it is not misuse of TextView.setText(), because everything works as expected and the log is only visible during instrumentation.

Can anybody give me a clue what to look for?


问:
increase accuracy of model in sklearn
The decision tree classification gives an accuracy of 0.52 but I want to increase the accuracy. How can I increase the accuracy by using any of the classification model available in sklearn.

I have used knn, decision tree, and cross-validation but all of them gives less accuracy.

Thanks

```<code>import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

#read from the csv file and return a Pandas DataFrame.
nba = pd.read_csv('wine.csv')

# print the column names
original_headers = list(nba.columns.values)
print(original_headers)

#print the first three rows.
print(nba[0:3])

# "Position (pos)" is the class attribute we are predicting.
class_column = 'quality'

#The dataset contains attributes such as player name and team name.
#We know that they are not useful for classification and thus do not
#include them as features.
feature_columns = ['fixed acidity', 'volatile acidity', 'citric     acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur         dioxide', 'density', 'pH','sulphates', 'alcohol']

#Pandas DataFrame allows you to select columns.
#We use column selection to split the data into features and class.
nba_feature = nba[feature_columns]
nba_class = nba[class_column]

print(nba_feature[0:3])
print(list(nba_class[0:3]))

train_feature, test_feature, train_class, test_class = \
train_test_split(nba_feature, nba_class, stratify=nba_class, \
train_size=0.75, test_size=0.25)

training_accuracy = []
test_accuracy = []

knn = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=1)
knn.fit(train_feature, train_class)
prediction = knn.predict(test_feature)
print("Test set predictions:\n{}".format(prediction))
print("Test set accuracy: {:.2f}".format(knn.score(test_feature, test_class)))

train_class_df = pd.DataFrame(train_class,columns=[class_column])
train_data_df = pd.merge(train_class_df, train_feature, left_index=True, right_index=True)
train_data_df.to_csv('train_data.csv', index=False)

temp_df = pd.DataFrame(test_class,columns=[class_column])
temp_df['Predicted Pos']=pd.Series(prediction, index=temp_df.index)
test_data_df = pd.merge(temp_df, test_feature, left_index=True, right_index=True)
test_data_df.to_csv('test_data.csv', index=False)

tree = DecisionTreeClassifier(max_depth=4, random_state=0)
tree.fit(train_feature, train_class)
print("Training set score: {:.3f}".format(tree.score(train_feature, train_class)))
print("Test set score Decision: {:.3f}".format(tree.score(test_feature, test_class)))

prediction = tree.predict(test_feature)
print("Confusion matrix:")
print(pd.crosstab(test_class, prediction, rownames=['True'], colnames=['Predicted'], margins=True))
cancer = nba.as_matrix()
tree = DecisionTreeClassifier(max_depth=4, random_state=0)

scores = cross_val_score(tree, train_feature,train_class, cv=10)
print("Cross-validation scores: {}".format(scores))
print("Average cross-validation score: {:.2f}".format(scores.mean()))
</code>```

答:
Usually the next step after DT are RF (and it's neighbors) or XGBoost (but it's not sklearn). Try them. And DT are very simple to overfit.

Remove outliers. Check classes in your dataset: if they are unbalanced, most of errors may be there. In this case you need to use weights while fitting or in metric function (or use f1).

You can attach here your Confusion Matrix - could be great to see.

Also NN (even from sklearn) may show better results.

Title: increase accuracy of model in sklearn

Body:
The decision tree classification gives an accuracy of 0.52 but I want to increase the accuracy. How can I increase the accuracy by using any of the classification model available in sklearn.

I have used knn, decision tree, and cross-validation but all of them gives less accuracy.

Thanks

import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier

#read from the csv file and return a Pandas DataFrame.
nba = pd.read_csv('wine.csv')

# print the column names
original_headers = list(nba.columns.values)
print(original_headers)

#print the first three rows.
print(nba[0:3])

# "Position (pos)" is the class attribute we are predicting.
class_column = 'quality'

#The dataset contains attributes such as player name and team name.
#We know that they are not useful for classification and thus do not
#include them as features.
feature_columns = ['fixed acidity', 'volatile acidity', 'citric     acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur         dioxide', 'density', 'pH','sulphates', 'alcohol']

#Pandas DataFrame allows you to select columns.
#We use column selection to split the data into features and class.
nba_feature = nba[feature_columns]
nba_class = nba[class_column]

print(nba_feature[0:3])
print(list(nba_class[0:3]))

train_feature, test_feature, train_class, test_class = \
train_test_split(nba_feature, nba_class, stratify=nba_class, \
train_size=0.75, test_size=0.25)

training_accuracy = []
test_accuracy = []

knn = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=1)
knn.fit(train_feature, train_class)
prediction = knn.predict(test_feature)
print("Test set predictions:\n{}".format(prediction))
print("Test set accuracy: {:.2f}".format(knn.score(test_feature, test_class)))

train_class_df = pd.DataFrame(train_class,columns=[class_column])
train_data_df = pd.merge(train_class_df, train_feature, left_index=True, right_index=True)
train_data_df.to_csv('train_data.csv', index=False)

temp_df = pd.DataFrame(test_class,columns=[class_column])
temp_df['Predicted Pos']=pd.Series(prediction, index=temp_df.index)
test_data_df = pd.merge(temp_df, test_feature, left_index=True, right_index=True)
test_data_df.to_csv('test_data.csv', index=False)

tree = DecisionTreeClassifier(max_depth=4, random_state=0)
tree.fit(train_feature, train_class)
print("Training set score: {:.3f}".format(tree.score(train_feature, train_class)))
print("Test set score Decision: {:.3f}".format(tree.score(test_feature, test_class)))

prediction = tree.predict(test_feature)
print("Confusion matrix:")
print(pd.crosstab(test_class, prediction, rownames=['True'], colnames=['Predicted'], margins=True))
cancer = nba.as_matrix()
tree = DecisionTreeClassifier(max_depth=4, random_state=0)

scores = cross_val_score(tree, train_feature,train_class, cv=10)
print("Cross-validation scores: {}".format(scores))
print("Average cross-validation score: {:.2f}".format(scores.mean()))