问:
Using Google Sign in button with React, can't get button to load
As the title mentions, I can't seem to get the button to load.

I am not getting any errors. The Hi text is rendering, but no button.

Index.html

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="google-signin-client_id" content="....apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>

    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>

  </body>
</html>
</code>```

index.js

```<code>const App = () => (
    <MuiThemeProvider>
        <SignIn />
    </MuiThemeProvider>
);
ReactDOM.render(<App />, document.getElementById('root'));
</code>```

Login.js

```<code>/* global gapi */

import React from 'react';

class SignIn extends React.Component{

    constructor(props){
        super(props);
        this.onSignIn = this.onSignIn.bind(this)
    }

    componentDidMount() {
        console.log('this mounted')
        gapi.signin2.render('g-signin2', {
            'scope': 'profile email',
            'width': 200,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }

    onSignIn(googleUser) {
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
    }

    render() {
        return(
            <div>
                <div>Hi</div>
                <div id="my-signin2" data-onsuccess={this.onSignIn}></div>
            </div>
        )
    }

}

export default SignIn
</code>```

What am I doing wrong?

答:
The first argument in gapi.signin2.render(..) is the button's id.

Your are passing g-signin2 whereas it should be my-signin2.

Body:
As the title mentions, I can't seem to get the button to load.

I am not getting any errors. The Hi text is rendering, but no button.

Index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="google-signin-client_id" content="....apps.googleusercontent.com">

    <title>React App</title>

index.js

const App = () => (
    <MuiThemeProvider>
        <SignIn />
    </MuiThemeProvider>
);
ReactDOM.render(<App />, document.getElementById('root'));

Login.js

/* global gapi */

import React from 'react';

class SignIn extends React.Component{

    constructor(props){
        super(props);
        this.onSignIn = this.onSignIn.bind(this)
    }

    componentDidMount() {
        console.log('this mounted')
        gapi.signin2.render('g-signin2', {
            'scope': 'profile email',
            'width': 200,
            'height': 50,
            'longtitle': true,
            'theme': 'dark',
            'onsuccess': this.onSignIn,
        });
    }

    onSignIn(googleUser) {
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present.
    }

    render() {
        return(

Hi

        )
    }

}

export default SignIn

What am I doing wrong?


来源: stackexchange

问:
AngularJs - .success is not a function after minification
I'm using angularJS(v1.5.7) in my MVC application. During the development, we used the syntax bellow to make ajax calling::

$http({
  method: 'GET',
  url: "",
  params: { }
}).success(function (data) {
  ...
}).finally(function () {
  ...
});```

When I published my application on the server, I'm using bundle to minify my javascript files.

After that, I'm geting the error: ".success is not a function"

Does anybody knows why this issue happen only when I minify the files?

答:
Syntax looks wrong.

Try below syntax.

```<code>    // Simple GET request example:
    $http({
      method: 'GET',
      url: '/someUrl'
    }).then(function successCallback(response) {
       // this callback will be called asynchronously
       // when the response is available
    }, function errorCallback(response) {
       // called asynchronously if an error occurs
       // or server returns response with an error status.
    });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using angularJS(v1.5.7) in my MVC application. During the development, we used the syntax bellow to make ajax calling::

$http({
  method: 'GET',
  url: "",
  params: { }
}).success(function (data) {
  ...
}).finally(function () {
  ...
});

When I published my application on the server, I'm using bundle to minify my javascript files.

After that, I'm geting the error: ".success is not a function"

Does anybody knows why this issue happen only when I minify the files?

Body:
Syntax looks wrong.

Try below syntax.

    // Simple GET request example:
    $http({
      method: 'GET',
      url: '/someUrl'
    }).then(function successCallback(response) {
       // this callback will be called asynchronously
       // when the response is available
    }, function errorCallback(response) {
       // called asynchronously if an error occurs
       // or server returns response with an error status.
    });


问:
Regex to ensure input starts with +/- then number, or is an hour in hh:mm format
I need a regex in a form in order to make sure the input either:

starts with + or - and then has numbers (for instance: +120 or -15)

or is an exact hour, for instance: 17:20 or 15:23

The regex I came up with is:

```<code>^[+-][\d]*|[\d]{2}:[\d]{2}$
</code>```

But it doesn't seem to work properly: each expression works separately (^[+-][\d]*$ or ^[\d]{2}:[\d]{2}$) but together with the | operator, it allows the input +120sds where it didn't when the expression was tested separately.

答:
You need to group the alternatives, e.g. using a non-capturing alternation group (?:...|...). That way, both the anchors will apply to all the alternatives. Also, to match time in 24h format, you may use a more precise expression, (?:[01][0-9]|2[0-3]):[0-5][0-9] (also, see this SO thread).

```<code>^(?:[+-]\d+|(?:[01][0-9]|2[0-3]):[0-5][0-9])$
  ^^       ^                               ^
</code>```

See the regex demo. Note that it seems there must be at least 1 digit after + and -, thus, use \d+ instead of \d*.

Pattern details

^ - start of string
-(?: - start of the grouping construct

[+-] - a + or -

\d+ - 1 or more digits

| - or

(?:[01][0-9]|2[0-3]) - 00 to 23

: - a colon

[0-5][0-9] - 00 to 59

) - end of the alternation group

$ - end of string.

Body:
I need a regex in a form in order to make sure the input either:

starts with + or - and then has numbers (for instance: +120 or -15)

or is an exact hour, for instance: 17:20 or 15:23

The regex I came up with is:

^[+-][\d]*|[\d]{2}:[\d]{2}$

But it doesn't seem to work properly: each expression works separately (^[+-][\d]*$ or ^[\d]{2}:[\d]{2}$) but together with the | operator, it allows the input +120sds where it didn't when the expression was tested separately.

Body:
You need to group the alternatives, e.g. using a non-capturing alternation group (?:...|...). That way, both the anchors will apply to all the alternatives. Also, to match time in 24h format, you may use a more precise expression, (?:[01][0-9]|2[0-3]):[0-5][0-9] (also, see this SO thread).

^(?:[+-]\d+|(?:[01][0-9]|2[0-3]):[0-5][0-9])$
  ^^       ^                               ^

See the regex demo. Note that it seems there must be at least 1 digit after + and -, thus, use \d+ instead of \d*.

Pattern details

^ - start of string
-(?: - start of the grouping construct

[+-] - a + or -

\d+ - 1 or more digits

| - or

(?:[01][0-9]|2[0-3]) - 00 to 23

: - a colon

[0-5][0-9] - 00 to 59

) - end of the alternation group

$ - end of string.


问:
jQuery Accordion problem
HI all.

I have this very simple code for simple accordion.

```<code>$('div.header').click(function() {
            $('div.content').slideUp('normal');
            $(this).next().slideDown('normal');
        }); $("div.content").hide();
</code>```

HTML

```<code><div class="header">Header</div>
<div class="content">Content... </div>
</code>```

So whenever header is being click content expands.

the problem is that when I click on the same header content slides up and going back down.

I'm not sure how to sort this out.

Any help much appreciated.

Thank you in advance

Dom

答:
You could determine if the content is already visible before sliding using </p>

```<code>if ((object-you-want-to-check).is(':visible') )
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery Accordion problem

Body:
HI all.

I have this very simple code for simple accordion.

$('div.header').click(function() {
            $('div.content').slideUp('normal');
            $(this).next().slideDown('normal');
        }); $("div.content").hide();

HTML

Header

Content...

So whenever header is being click content expands.

the problem is that when I click on the same header content slides up and going back down.

I'm not sure how to sort this out.

Any help much appreciated.

Thank you in advance

Dom

Body:
You could determine if the content is already visible before sliding using

if ((object-you-want-to-check).is(':visible') )


问:
Getting Exception in thread "main" Error
So I have array with those numbers and my task is to make 2 new arrays where one array(poz) will have all positive numbers from array and second array(neg) will take all negative values out of array </p>

```<code>public class obNiza {
    public static void main(String[] args) {
     int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
     Arrays.sort(array);

     int[] poz= new int[6];
     int[] neg= new int[5];

     for(int i=0; i<array.length; i++)
     {
         if(array[i] < 0)
             poz[i] = array[i];
         else neg[i] = array[i];
     }

       System.out.println(Arrays.toString(poz));
         System.out.println(Arrays.toString(neg));

    }
}
</code>```

答:
As you don't know in advance the amount of positive and negative numbers, you're better off using an ArrayList.

```<code>ArrayList<Integer> poz = new ArrayList<>();
ArrayList<Integer> neg = new ArrayList<>();
</code>```

Then loop through and add to the relevant ArrayList as needed

```<code>for (int i = 0; i < array.length; i++) {
            if (array[i] > 0) {
                poz.add(array[i]);
            } else {
                neg.add(array[i]);
            }
        }
</code>```

Note: change array[i] > 0 to array[i] >= 0 if you want 0s to go into poz

Output:

[12, 12, 23, 43, 43, 545]

[-999, -87, -55, -22, -4, 0, 0]

Body:
So I have array with those numbers and my task is to make 2 new arrays where one array(poz) will have all positive numbers from array and second array(neg) will take all negative values out of array

public class obNiza {
    public static void main(String[] args) {
     int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
     Arrays.sort(array);

     int[] poz= new int[6];
     int[] neg= new int[5];

     for(int i=0; i<array.length; i++)
     {
         if(array[i] < 0)
             poz[i] = array[i];
         else neg[i] = array[i];
     }

       System.out.println(Arrays.toString(poz));
         System.out.println(Arrays.toString(neg));

    }
}

Body:
As you don't know in advance the amount of positive and negative numbers, you're better off using an ArrayList.

ArrayList<Integer> poz = new ArrayList<>();
ArrayList<Integer> neg = new ArrayList<>();

Then loop through and add to the relevant ArrayList as needed

for (int i = 0; i < array.length; i++) {
            if (array[i] > 0) {
                poz.add(array[i]);
            } else {
                neg.add(array[i]);
            }
        }

Note: change array[i] > 0 to array[i] >= 0 if you want 0s to go into poz

Output:

[12, 12, 23, 43, 43, 545]

[-999, -87, -55, -22, -4, 0, 0]


问:
Solr DisMax" or "Extended DisMax" parser in Moodle
I have setup Global search in Moodle by using Solr search engine. Now my search is working like "Full-text" search. I want to use this search like dismax query parser too.

In other words,  My Solr is currently using the "basic" query parser instead of the more advanced "DisMax" or "Extended DisMax" parser.

For example, if I search for Spiderman or spiderman or SPIDRMAN or spider-man all of the string provide the same result.

currently, If I searched for "Spider man" then no result found whereas I want to display the same result as "Spiderman" get.

thanks to advanced.

答:
Neither of the cases you've mentioned is something that would be different with the dismax or edismax handler. They're all related to how the content of a field is processed when indexing or when querying, and the field type is what determines that. If the field type is a regular string field, or a textfield with a keyword tokenizer, the result would only match if you have the exact same value.

However, for "spider man" to match "spiderman", you'll have to add a ShingleFilter when querying (if you want to match "spiderman" when searching for "spider man") and indexing (if you want to match "spider man" when searching for "spiderman"), with the tokenSeparator set to "".


问:
how can git identify repositories owner?
I wonder if someone can pretend as a real github repository owner and do some push in that repository.
Does github verify the repository owner by using user.name and user.email?</p>

答:
After you do the first git clone and then git push , you will see a screen like this:

Depending if you use BitBucket or Github where you should enter your credentials.
Basically you login and you are good to go!
Good Luck with GIT and have fun Coding !


问:
jQuery call model by clicking on label
I'm trying to implement a feature when a user click on a label a modal pop up.

Problem

I can't open using a Label element, but if i use a button (with the same code) it works.

if i remove the comment on the hello, i can see the alert (so the code enter on the jquery statement

This is my code (just a code from the bootstrap site)

HTML

```<code><label id="some-label">Something</label>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

JS

```<code>$('#some-label').on('click', function() {
     //alert("hello");
     $('#myModal').show();
 });
</code>```

答:
Your code doesn't work because you're bypassing the standard bootstrap logic for showing the modal. You're calling show(), but the element is still set to opacity: 0 due to the fade class, hence nothing is displayed.

To fix this, use the appropriate data attributes on the trigger element (data-target and data-toggle). Then you don't need to include any explicit JS as Bootstrap will do the heavy lifting for you:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

Something

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

Title: jQuery call model by clicking on label

Body:
I'm trying to implement a feature when a user click on a label a modal pop up.

Problem

I can't open using a Label element, but if i use a button (with the same code) it works.

if i remove the comment on the hello, i can see the alert (so the code enter on the jquery statement

This is my code (just a code from the bootstrap site)

HTML

Something

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Modal title

        ...

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

JS

$('#some-label').on('click', function() {
     //alert("hello");
     $('#myModal').show();
 });

Body:
Your code doesn't work because you're bypassing the standard bootstrap logic for showing the modal. You're calling show(), but the element is still set to opacity: 0 due to the fade class, hence nothing is displayed.

To fix this, use the appropriate data attributes on the trigger element (data-target and data-toggle). Then you don't need to include any explicit JS as Bootstrap will do the heavy lifting for you:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

<label id="some-label" data-toggle="modal" data-target="#myModal">Something</label>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


问:
Convert to Sentence Case in Android
My app receives a large amount of paragraph length text. Some of it is all in upper case, some all lower and some a mix. I would like to convert it to sentence case i.e. all sentences should start with an uppercase letter. What would be the most efficient way to perform the conversion? - I could not find any sample code or a library to do this.</p>

答:
The code referenced in the links above did not quite work, so I extended it as follows to turn text like:

"this SENTENce is not neat. neither IS this sentence."

into

"This sentence is not neat. Neither is this sentence."

```<code>public static String sentenceCaseForText(String text) {

    if (text == null) return "";

    int pos = 0;
    boolean capitalize = true;
    StringBuilder sb = new StringBuilder(text);

    while (pos < sb.length()) {

        if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {

            sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
        }
        else if (!capitalize && !Character.isWhitespace(sb.charAt(pos))) {

            sb.setCharAt(pos, Character.toLowerCase(sb.charAt(pos)));
        }

        if (sb.charAt(pos) == '.' || (capitalize && Character.isWhitespace(sb.charAt(pos)))) {

            capitalize = true;
        }
        else {

            capitalize = false;
        }

        pos++;
    }

    return sb.toString();
}
</code>```

Title: Convert to Sentence Case in Android

Body:
The code referenced in the links above did not quite work, so I extended it as follows to turn text like:

"this SENTENce is not neat. neither IS this sentence."

into

"This sentence is not neat. Neither is this sentence."

public static String sentenceCaseForText(String text) {

    if (text == null) return "";

    int pos = 0;
    boolean capitalize = true;
    StringBuilder sb = new StringBuilder(text);

    while (pos < sb.length()) {

        if (capitalize && !Character.isWhitespace(sb.charAt(pos))) {

            sb.setCharAt(pos, Character.toUpperCase(sb.charAt(pos)));
        }
        else if (!capitalize && !Character.isWhitespace(sb.charAt(pos))) {

            sb.setCharAt(pos, Character.toLowerCase(sb.charAt(pos)));
        }

        if (sb.charAt(pos) == '.' || (capitalize && Character.isWhitespace(sb.charAt(pos)))) {

            capitalize = true;
        }
        else {

            capitalize = false;
        }

        pos++;
    }

    return sb.toString();
}


问:
Computing Growth of a Variable in R
I want to compute a growth variable in a data frame with R.

Lets say I have a starting variable X=100
and a vector Y of time length 10 with growth rates f.e

```<code>Y<-c(0.04, 0.03, -0.02 ... 0.02)
</code>```

Is there a solution to compute the growth rate of X o.v.t., so that I get a vector for my starting value X, e.g. : (100, 100*(1+0,04), (100*(1+0,04)*(1,03),... etc)

I hope I could make it clear.

Thanks,

答:
I think what you're looking for is the cumprod function. This is akin to calculating wealth indexes in finance. Try the following:</p>

```<code>library(tidyverse)
df <- data.frame( changes = c(0.04, 0.03, -0.02, 0.02) ) %>% tbl_df()

# Now calculate your growth rates, or wealth indexes, as follows:

start_value <- 100

df_growth_rate <- df %>% mutate( growth_rate = start_value * cumprod(1 + changes))
</code>```

Title: Computing Growth of a Variable in R

Body:
I want to compute a growth variable in a data frame with R.

Lets say I have a starting variable X=100
and a vector Y of time length 10 with growth rates f.e

Y<-c(0.04, 0.03, -0.02 ... 0.02)

Is there a solution to compute the growth rate of X o.v.t., so that I get a vector for my starting value X, e.g. : (100, 100*(1+0,04), (100*(1+0,04)*(1,03),... etc)

I hope I could make it clear.

Thanks,

Body:
I think what you're looking for is the cumprod function. This is akin to calculating wealth indexes in finance. Try the following:

library(tidyverse)
df <- data.frame( changes = c(0.04, 0.03, -0.02, 0.02) ) %>% tbl_df()

# Now calculate your growth rates, or wealth indexes, as follows:

start_value <- 100

df_growth_rate <- df %>% mutate( growth_rate = start_value * cumprod(1 + changes))


问:
About the Firestore query-data documentation specifically DocumentSnapshot
In the Firestore query-data get-data docs I want to know in what situation the document != null will evaluate to false? Shouldn't it instead be !document.exists()

```<code>DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});
</code>```

答:
The onComplete() callback provides a Google Task instance of Task<DocumentSnapshot> and calling getResult() on this should return a DocumentSnapshot, and never null.

This piqued my interest though so I did a little testing: I  attached an OnCompleteListener to a document that I know doesn't exist:

```<code>FirebaseFirestore.getInstance()
        .collection("this-does-not-exist")
        .document("neither-does-this")
        .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    if (task.getResult() == null) Log.d(TAG, "getResult is null");
                    Log.d(TAG, "getResult: " + task.getResult());
                }
            }
});
</code>```

When executed, the task.getResult() == null check evaluates to false and therefore the message "getResult is null" is not written to the log.

However, calling toString() on the return from getResult() throws the below error:

```<code>java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.
</code>```

This explicitly states to use exists() rather than a null-check, but the documentation for "get a document" says:

Note: If there is no document at the location referenced by docRef, the resulting document will be null.

Furthermore, examples in other languages on the same documentation page all use exists(), except Android and Objective-C. Most importantly: the Java example uses exists():

```<code>DocumentReference docRef = db.collection("cities").document("SF");
// asynchronously retrieve the document
ApiFuture<DocumentSnapshot> future = docRef.get();
// ...
// future.get() blocks on response
DocumentSnapshot document = future.get();
if (document.exists()) {
  System.out.println("Document data: " + document.getData());
} else {
  System.out.println("No such document!");
}
</code>```

In this case, I'd wager that this seems to be an error in the documentation, and we should be using document.exists() rather than document != null.

Body:
In the Firestore query-data get-data docs I want to know in what situation the document != null will evaluate to false? Shouldn't it instead be !document.exists()

DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document != null) {
                Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

Body:
The onComplete() callback provides a Google Task instance of Task<DocumentSnapshot> and calling getResult() on this should return a DocumentSnapshot, and never null.

This piqued my interest though so I did a little testing: I  attached an OnCompleteListener to a document that I know doesn't exist:

FirebaseFirestore.getInstance()
        .collection("this-does-not-exist")
        .document("neither-does-this")
        .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    if (task.getResult() == null) Log.d(TAG, "getResult is null");
                    Log.d(TAG, "getResult: " + task.getResult());
                }
            }
});

When executed, the task.getResult() == null check evaluates to false and therefore the message "getResult is null" is not written to the log.

However, calling toString() on the return from getResult() throws the below error:

java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.

This explicitly states to use exists() rather than a null-check, but the documentation for "get a document" says:

Note: If there is no document at the location referenced by docRef, the resulting document will be null.

Furthermore, examples in other languages on the same documentation page all use exists(), except Android and Objective-C. Most importantly: the Java example uses exists():

DocumentReference docRef = db.collection("cities").document("SF");
// asynchronously retrieve the document
ApiFuture<DocumentSnapshot> future = docRef.get();
// ...
// future.get() blocks on response
DocumentSnapshot document = future.get();
if (document.exists()) {
  System.out.println("Document data: " + document.getData());
} else {
  System.out.println("No such document!");
}

In this case, I'd wager that this seems to be an error in the documentation, and we should be using document.exists() rather than document != null.


问:
Debian pm2 unable to start elasticsearch server
I'm running a node server on a linux debian core.

I'm using pm2 to run all processes in the background and monitor them.

Everything is working properly except the elasticsearch server, I'm getting an error message which I do not understand.

```<code>SyntaxError: Unexpected token ILLEGAL
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function._load (/usr/lib/node_modules/pm2/node_modules/pmx/lib/transaction.js:62:21)
    at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/ProcessContainerFork.js:46:21)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
</code>```

When i do pm2 list to view the other processes, this is the result:

The command i use to start the elasticsearch server is simply pm2 start ./bin/elasticsearch instead of ./bin/elasticsearch which is what the docs says.

I'm going to run the elasticsearch server locally only so the correct ip is 127.0.0.1 port 9200.

I should also mention that the elasticsearch server DO work if i run it normally, without pm2.

Here is my elasticsearch.yml configuration file.

```<code>cluster.name: swissnet
node.name: "swissnet-data"
node.master: true
node.data: true
path.data: ../local-data/
path.logs: ../local-logs/
ES_HEAP_SIZE: 300m
network.host: 127.0.0.1
http.port: 9200
http.cors.enabled: true
http.cors.allow-origin: "*"
discovery.zen.ping.unicast.hosts: ["127.0.0.1"]
discovery.zen.minimum_master_nodes: 3
gateway.recover_after_nodes: 8
gateway.expected_nodes: 10
gateway.recover_after_time: 5m
ES_JAVA_OPTS: "-Des.insecure.allow.root=true"
</code>```

Any ideas? Elasticsearch.yml updates are also welcome.

答:
You need create file sh, for example: ES_service.sh

```<code>#!/bin/bash
sh /your_path/bin/elasticsearch
</code>```

then run your pm2 command:

```<code>pm2 start ES_service.sh --name=elasticsearch
</code>```

check your service with pm2 list
I was used it in Ubuntu and Centos 7, everything ok
maybe it help

Regards

Body:
I'm running a node server on a linux debian core.

I'm using pm2 to run all processes in the background and monitor them.

Everything is working properly except the elasticsearch server, I'm getting an error message which I do not understand.

SyntaxError: Unexpected token ILLEGAL
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function._load (/usr/lib/node_modules/pm2/node_modules/pmx/lib/transaction.js:62:21)
    at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/ProcessContainerFork.js:46:21)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)

When i do pm2 list to view the other processes, this is the result:

The command i use to start the elasticsearch server is simply pm2 start ./bin/elasticsearch instead of ./bin/elasticsearch which is what the docs says.

I'm going to run the elasticsearch server locally only so the correct ip is 127.0.0.1 port 9200.

I should also mention that the elasticsearch server DO work if i run it normally, without pm2.

Here is my elasticsearch.yml configuration file.

cluster.name: swissnet
node.name: "swissnet-data"
node.master: true
node.data: true
path.data: ../local-data/
path.logs: ../local-logs/
ES_HEAP_SIZE: 300m
network.host: 127.0.0.1
http.port: 9200
http.cors.enabled: true
http.cors.allow-origin: "*"
discovery.zen.ping.unicast.hosts: ["127.0.0.1"]
discovery.zen.minimum_master_nodes: 3
gateway.recover_after_nodes: 8
gateway.expected_nodes: 10
gateway.recover_after_time: 5m
ES_JAVA_OPTS: "-Des.insecure.allow.root=true"

Any ideas? Elasticsearch.yml updates are also welcome.

Body:
You need create file sh, for example: ES_service.sh

#!/bin/bash
sh /your_path/bin/elasticsearch

then run your pm2 command:

pm2 start ES_service.sh --name=elasticsearch

check your service with pm2 list
I was used it in Ubuntu and Centos 7, everything ok
maybe it help

Regards


问:
Icon inside a commun component fires error
I am trying to build a mobile app and to make my code clean, I decide to create commun components that I will use very ofter.

I want to create a Validation Button Component as follow :

```<code>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TouchableOpacity, Text, Icon } from 'react-native';
import styles from './styles';

/**
 * @export
 * @class ValidateButton
 * @extends {Component}
 */
export default class ValidateButton extends Component {
    /**
     * default props
     *
     * @static
     * @memberof ValidateButton
     */
    static defaultProps = {
      enabled: true,
    };

    /**
     * props validation
     *
     * @static
     * @memberof ValidateButton
     */
    static propTypes = {
      enabled: PropTypes.bool,
      clickHandler: PropTypes.func.isRequired,
      label: PropTypes.string.isRequired,
    };

  /**
   * Render the validation button
   *
   * @returns {object}
   * @memberof ValidateButton
   */
    render() {
      return (
        <TouchableOpacity style={styles.footerBoldButton} onPress={this.props.enabled && this.props.clickHandler}>
          <Icon name="check" type="material" color="#FFF" iconStyle={styles.footerBoldButtonIcon} size={16} />
          <Text style={styles.footerBoldButtonText}>{this.props.label}</Text>
        </TouchableOpacity>
      );
    }
}
</code>```

My problem is that when I call my component, an error is displayed :

```<code> Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
</code>```

And The weird thing, is that when I just delete the Icon element it works.

Does anyone have an explanation ?

答: I do not know why it does not work with Icon from react-native but I could make it work with Icon from react-native-elements

Body:
I am trying to build a mobile app and to make my code clean, I decide to create commun components that I will use very ofter.

I want to create a Validation Button Component as follow :

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { TouchableOpacity, Text, Icon } from 'react-native';
import styles from './styles';

/**
 * @export
 * @class ValidateButton
 * @extends {Component}
 */
export default class ValidateButton extends Component {
    /**
     * default props
     *
     * @static
     * @memberof ValidateButton
     */
    static defaultProps = {
      enabled: true,
    };

    /**
     * props validation
     *
     * @static
     * @memberof ValidateButton
     */
    static propTypes = {
      enabled: PropTypes.bool,
      clickHandler: PropTypes.func.isRequired,
      label: PropTypes.string.isRequired,
    };

  /**
   * Render the validation button
   *
   * @returns {object}
   * @memberof ValidateButton
   */
    render() {
      return (
        <TouchableOpacity style={styles.footerBoldButton} onPress={this.props.enabled && this.props.clickHandler}>
          <Icon name="check" type="material" color="#FFF" iconStyle={styles.footerBoldButtonIcon} size={16} />
          <Text style={styles.footerBoldButtonText}>{this.props.label}</Text>
        </TouchableOpacity>
      );
    }
}

My problem is that when I call my component, an error is displayed :

 Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

And The weird thing, is that when I just delete the Icon element it works.

Does anyone have an explanation ?


答:
IMHO you could use List (ArrayList):

```<code>import java.util.*;

public class ObNiza {
    public static void main(String[] args) {
    int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
    Arrays.sort(array);

    List<Integer> positivesList = new ArrayList<>();
    List<Integer> negativesList = new ArrayList<>();

    for(int i=0; i<array.length; i++) {
        if (array[i]==0) { // since 0 is not negative nor positive
            continue;
        }
        if(array[i] < 0) {
            positivesList.add(array[i]);
        } else {
            negativesList.add(array[i]);
        }
    }

    Integer[] poz = positivesList.toArray(new Integer[positivesList.size()]);
    Integer[] neg = negativesList.toArray(new Integer[negativesList.size()]);

    System.out.println(Arrays.toString(poz));
    System.out.println(Arrays.toString(neg));

    }
}
</code>```

Title: Getting Exception in thread "main" Error

Body:
IMHO you could use List (ArrayList):

import java.util.*;

public class ObNiza {
    public static void main(String[] args) {
    int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
    Arrays.sort(array);

    List<Integer> positivesList = new ArrayList<>();
    List<Integer> negativesList = new ArrayList<>();

    for(int i=0; i<array.length; i++) {
        if (array[i]==0) { // since 0 is not negative nor positive
            continue;
        }
        if(array[i] < 0) {
            positivesList.add(array[i]);
        } else {
            negativesList.add(array[i]);
        }
    }

    Integer[] poz = positivesList.toArray(new Integer[positivesList.size()]);
    Integer[] neg = negativesList.toArray(new Integer[negativesList.size()]);

    System.out.println(Arrays.toString(poz));
    System.out.println(Arrays.toString(neg));

    }
}


问:
Plot GeoIP data on a World Map
I need a library (preferably written in Python) which is able to take a series of IP addresses (or geographic coordinates) and plots them on a World Map.

I already found this one, but it outputs data as a .svg file and it's simply unable to cope with large data sets.

Please note that I need something which can be downloaded and run locally, so no data uploading to 3rd party web services.

Thanks!

答:
You might want to have a look at mapsplotlib.

Installation

ONLY PYTHON 2.7!

```<code>$ pip install mapsplotlib
$ pip install pandas
</code>```

You'll then need to have a Google Static Maps API key, go to https://console.developers.google.com

Usage

```<code>import pandas as pd
from mapsplotlib import mapsplot as mplt

df = pd.read_csv("data.csv")

mplt.register_api_key('your_google_api_key_here')
mplt.density_plot(df['latitude'], df['longitude'])
</code>```

Example output

Title: Plot GeoIP data on a World Map

Body:
You might want to have a look at mapsplotlib.

Installation

ONLY PYTHON 2.7!

$ pip install mapsplotlib
$ pip install pandas

You'll then need to have a Google Static Maps API key, go to https://console.developers.google.com

Usage

import pandas as pd
from mapsplotlib import mapsplot as mplt

df = pd.read_csv("data.csv")

mplt.register_api_key('your_google_api_key_here')
mplt.density_plot(df['latitude'], df['longitude'])

Example output


问:
Arity of methods
When classifying the arity of a method function, do you need to consider the use of this? For example:

```<code>// Unary
function double(num) {
    return num * 2;
}

// Binary
function add(num1, num2) {
    return num1 + num2;
}

class Calc {
    value;

    // Unary or binary?
    add(num1) {
        return this.value + num1;
    }

    // Nullary or unary?
    double() {
        return this.value * 2;
    }
}
</code>```

I've always thought of this as an implicit parameter.

(I'm assuming there is a language-agnostic answer to this, but it's JavaScript I'm most interested in the answer to)

答:
C++ and other OOP languages allow us to write something like this:

```<code>C a,b,c;
c = a + b;
</code>```

(C is a class, a, b and c are instances of class C)

The class C can define the + operator either as a method or as a friend function. As a method it accepts one argument (it is the second operand, the first operand is this). As a friend function it requires two arguments (the two operands).

The addition is a binary operator (we know this from mathematics and the usage above cannot deny this). The fact that in C++ it can be implemented as a method that accepts only one explicit argument is just an implementation detail. Its actual arity is set by the number of values it requires to be used.

The bottom line is: this must be counted as an argument. If the function does not use it then it should not be an instance method but a class method or an independent function.

Title: Arity of methods

Body:
When classifying the arity of a method function, do you need to consider the use of this? For example:

// Unary
function double(num) {
    return num * 2;
}

// Binary
function add(num1, num2) {
    return num1 + num2;
}

class Calc {
    value;

    // Unary or binary?
    add(num1) {
        return this.value + num1;
    }

    // Nullary or unary?
    double() {
        return this.value * 2;
    }
}

I've always thought of this as an implicit parameter.

(I'm assuming there is a language-agnostic answer to this, but it's JavaScript I'm most interested in the answer to)

Body:
C++ and other OOP languages allow us to write something like this:

C a,b,c;
c = a + b;

(C is a class, a, b and c are instances of class C)

The class C can define the + operator either as a method or as a friend function. As a method it accepts one argument (it is the second operand, the first operand is this). As a friend function it requires two arguments (the two operands).

The addition is a binary operator (we know this from mathematics and the usage above cannot deny this). The fact that in C++ it can be implemented as a method that accepts only one explicit argument is just an implementation detail. Its actual arity is set by the number of values it requires to be used.

The bottom line is: this must be counted as an argument. If the function does not use it then it should not be an instance method but a class method or an independent function.


问:
Does the order of cases in a switch statement matter?
```<code>var number = 10

var bool = false

switch (number, bool) {

case (_, false):
    print("bool is false")
case (10, _):
    print("number is 10")
default:
    print("whatever")
}
</code>```

The above would print "bool is false"

```<code>var number = 10

var bool = false

switch (number, bool) {
case (10, _):
    print("number is 10")
case (_, false):
    print("bool is false")
default:
    print("whatever")
}
</code>```

The above would print "number is 10"

To further test this I moved the default case to the top and got:

error: additional 'case' blocks cannot appear after the 'default'
  block of a 'switch'

Questions:

So is this standard Foundation behavior? I looked at the library but didn't find anything about the sequence of cases.

Additionally does this mean two cases can't be identical but can be overlapping...and it would just fall through whichever case happened first?

答:
The switch statement is part of the Swift language, not any particular library, and yes, order matters.

It might help to think of a switch statement as a shortcut for a series of "if-then-else" statements. Say I have the following statement:

```<code>switch(number) {
case (1):
    doSomethingForOne()
    break
case (2):
    doSomethingForTwo()
    break
default:
    doSomethingForDefault()
    break
}
</code>```

This is functionally equivalent to the following code:

```<code>if(number == 1) {
    doSomethingForOne()
}
else if (number == 2) {
    doSomethingForTwo()
}
else {
    doSomethingForDefault()
}
</code>```

You see that the default stands in for the else. It wouldn't make sense to add an else if() after that else, because it will never execute (the else 'eats' the input)

Body:
var number = 10

var bool = false

switch (number, bool) {

case (_, false):
    print("bool is false")
case (10, _):
    print("number is 10")
default:
    print("whatever")
}

The above would print "bool is false"

var number = 10

var bool = false

switch (number, bool) {
case (10, _):
    print("number is 10")
case (_, false):
    print("bool is false")
default:
    print("whatever")
}

The above would print "number is 10"

To further test this I moved the default case to the top and got:

error: additional 'case' blocks cannot appear after the 'default'
  block of a 'switch'

Questions:

So is this standard Foundation behavior? I looked at the library but didn't find anything about the sequence of cases.

Additionally does this mean two cases can't be identical but can be overlapping...and it would just fall through whichever case happened first?

Body:
The switch statement is part of the Swift language, not any particular library, and yes, order matters.

It might help to think of a switch statement as a shortcut for a series of "if-then-else" statements. Say I have the following statement:

switch(number) {
case (1):
    doSomethingForOne()
    break
case (2):
    doSomethingForTwo()
    break
default:
    doSomethingForDefault()
    break
}

This is functionally equivalent to the following code:

if(number == 1) {
    doSomethingForOne()
}
else if (number == 2) {
    doSomethingForTwo()
}
else {
    doSomethingForDefault()
}

You see that the default stands in for the else. It wouldn't make sense to add an else if() after that else, because it will never execute (the else 'eats' the input)

ContentLicense: CC BY-SA 4.0


问:
Recent Activities in Ruby on Rails
What is the best way to implement a StackOverflow-style Recent Activities page?

I have a Gallery with user's photos and I want them to be notified when other users comment or vote their photos.

Should I create a new table which contains recent activities (updated whenever a user posts a comment or votes) or should I simply use a MySQL query?

答:
This has been written up into a great article which shows the full use of AR, Observers and gives the migration you will need.

http://mickeyben.com/blog/2010/05/23/creating-an-activity-feed-with-rails/

Observers save you cluttering your models with this information so as well as adding activities you can send emails or whatever else you need to do.

Title: Recent Activities in Ruby on Rails


问:
Trying to find a set of letters within a string with a loop
I am trying to make a loop that checks all the cells in column A and if it finds that any of them contains the phrase "ISAW" within a string (like 1314_ISAW_STUFF) then it changes the value of the corresponding cell in column G to "COMPLIANT".

I have the following code, the loop works and the Cells.Find option should work but it doesn't activate any cells with matching criteria.

```<code>Sub mytestsub()

Dim sh1 As Worksheet
Set sh1 = Worksheets("Sheet1")

Dim i As Integer
sh1.Activate

On Error GoTo MyError
For i = 1 To InStr(ActiveSheet, "ISAW")
    sh1.Cells.Find("ISAW").Activate
    If InStr(ActiveCell, "ISAW") > 0 Then
        ActiveCell.Offset(, 7).Value = "COMPLIANT"
    End If
Next i

MyError:
On Error GoTo -1

End Sub
</code>```

Any help would be appreciated!

I altered the script Tom generously provided as seen below, but it doesn't seem to be working now.

```<code> Sub bugfix()
'QA N/A bugfix'
    Dim fndCell As Range
    Dim FirstAddress As String
    Worksheets("Summary").Unprotect
With Worksheets("Summary")
        .Activate

        On Error GoTo MyError
        Set fndCell = .Column(3).Find(what:="ISAW", lookat:=xlPart)
        If Not fndCell Is Nothing Then
         ' uncomment if you really want to visually track the cells
            'fndCell.Activate
            FirstAddress = fndCell.Address
            Do
                fndCell.Offset(0, 6).Value = "N/A"
                Set fndCell = .Cells.FindNext(fndCell)
            Loop Until fndCell.Address = FirstAddress
        End If
    End With
Exit Sub
MyError:
    On Error GoTo -1
End Sub
</code>```

答:
I can appreciate there could be good reason to use VBA but May I suggest a formula as an option, in first data cell in column G and then copied down

```<code>=IF(ISERR(FIND("ISAW",A1,1)),"","COMPLIANT")
</code>```

This looks for your string if it finds it then its start position is returned, if it doesn't then it returns #VALUE. The encapsulating IF statement converts this to COMPLIIANT or empty.

Body:
I am trying to make a loop that checks all the cells in column A and if it finds that any of them contains the phrase "ISAW" within a string (like 1314_ISAW_STUFF) then it changes the value of the corresponding cell in column G to "COMPLIANT".

I have the following code, the loop works and the Cells.Find option should work but it doesn't activate any cells with matching criteria.

Sub mytestsub()

Dim sh1 As Worksheet
Set sh1 = Worksheets("Sheet1")

Dim i As Integer
sh1.Activate

On Error GoTo MyError
For i = 1 To InStr(ActiveSheet, "ISAW")
    sh1.Cells.Find("ISAW").Activate
    If InStr(ActiveCell, "ISAW") > 0 Then
        ActiveCell.Offset(, 7).Value = "COMPLIANT"
    End If
Next i

MyError:
On Error GoTo -1

End Sub

Any help would be appreciated!

I altered the script Tom generously provided as seen below, but it doesn't seem to be working now.

 Sub bugfix()
'QA N/A bugfix'
    Dim fndCell As Range
    Dim FirstAddress As String
    Worksheets("Summary").Unprotect
With Worksheets("Summary")
        .Activate

        On Error GoTo MyError
        Set fndCell = .Column(3).Find(what:="ISAW", lookat:=xlPart)
        If Not fndCell Is Nothing Then
         ' uncomment if you really want to visually track the cells
            'fndCell.Activate
            FirstAddress = fndCell.Address
            Do
                fndCell.Offset(0, 6).Value = "N/A"
                Set fndCell = .Cells.FindNext(fndCell)
            Loop Until fndCell.Address = FirstAddress
        End If
    End With
Exit Sub
MyError:
    On Error GoTo -1
End Sub

Body:
I can appreciate there could be good reason to use VBA but May I suggest a formula as an option, in first data cell in column G and then copied down

=IF(ISERR(FIND("ISAW",A1,1)),"","COMPLIANT")

This looks for your string if it finds it then its start position is returned, if it doesn't then it returns #VALUE. The encapsulating IF statement converts this to COMPLIIANT or empty.


问:
Pandocs: Md to pdf, support of html-style colors?
I'm trying to convert a .md to pdf that contains both html-style colors:

```<code><span style="color:#3297A5">**Like this**</span>
</code>```

and math:

```<code>$$
J(\theta) = \frac{1}{2m} [\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})^2 + \
lambda\sum_{j=1}^{n}(\theta_j^2)].
$$
</code>```

using

```<code>pandoc -s -o test.pdf test.md
</code>```

outputs formatting and math fine, but no colors. Using this online md to
pdf tool http://www.markdowntopdf.com/ i get the colors right, but not
the math, which indicates that md to pdf conversion of html-style colors is possible?

答:
If you want to use CSS to change colors, you'll have to use wkhtmltopdf instead of LaTeX, e.g.

```<code>$ pandoc input.md --mathjax -t html5 -o output.pdf
</code>```

(or try --mathml instead of --mathjax, see the pandoc manual)

Alternatively, you can use a LaTeX template and do layouting there.
For more info, see http://pandoc.org/MANUAL.html#creating-a-pdf

Body:
I'm trying to convert a .md to pdf that contains both html-style colors:

**Like this**

and math:

$$
J(\theta) = \frac{1}{2m} [\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})^2 + \
lambda\sum_{j=1}^{n}(\theta_j^2)].
$$

using

pandoc -s -o test.pdf test.md

outputs formatting and math fine, but no colors. Using this online md to
pdf tool http://www.markdowntopdf.com/ i get the colors right, but not
the math, which indicates that md to pdf conversion of html-style colors is possible?

Body:
If you want to use CSS to change colors, you'll have to use wkhtmltopdf instead of LaTeX, e.g.

$ pandoc input.md --mathjax -t html5 -o output.pdf

(or try --mathml instead of --mathjax, see the pandoc manual)

Alternatively, you can use a LaTeX template and do layouting there.
For more info, see http://pandoc.org/MANUAL.html#creating-a-pdf


问:
Fetching aggregations of nested documents in ElasticSearch 5.6.3 leads to Lucene exception
I have an issue with aggregations of nested documents on ElasticSearch 5.6.3.

My query is structured in the following way:

```<code>  query
  aggs
  |_filter
    |_nested
      |_term
        |_top-hits
</code>```

If I try the aggregation on a non-nested field (and with the nested agg removed of course), everything works as expected. But as it is structured now, I receive an exception from Lucene:
Child query must not match same docs with parent filter. Combine them as must clauses (+) to find a problem doc. docId=2147483647, class org.apache.lucene.search.ConstantScoreScorer

This exception is not triggered on ElasticSearch 2.4.6.

I tried to structure the aggregations in a different way, but I couldn't come up with a combination that works and delivers the wanted results.

This is how the mapping looks like:

```<code>"recording": {
  "dynamic": "strict",
  "_all" : {
    "enabled" : false
  },
  "properties": {
    "id": {
      "type": "integer"
    },
    "soloists": {
      "properties": {
        "type": "nested",
        "person": {
          "properties": {
            "id": {
             "type": "integer"
            },
            "name": {
              "type": "string",
              "index": "not_analyzed"
            }
         }
      }
    },
    "work": {
      "id": {
        "type": integer
      },
      "title": {
        "type": "string",
        "index": "not_analyzed"
      }
    }
}
</code>```

And the query itself:

```<code>{
  "query": {},
  "aggs": {
    "my_top_results": {
      "global": {},
      "aggs": {
        "my_filter_agg": {
          "filter": {
            "bool": {
              "must": [
                {
                  "bool": {
                    "should": [
                      {
                        "nested": {
                          "path": "soloists",
                          "query": {
                            "bool": {
                              "must": {
                                "match": {
                                  "soloists.person.id": 77957
                                }
                              }
                            }
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          },
          "aggs": {
            "my_nested_agg": {
              "nested": {
                "path": "soloists"
              },
              "aggs": {
                "my_terms_agg": {
                  "term": {
                    "field": "soloists.person.id",
                    "size": 10
                  }
                  "aggs": {
                    "my_top_hits_agg": {
                      "size": 1,
                      "_source": {
                        "include": [
                          "soloists.person.id",
                          "soloists.person.name"
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Any help would be highly appreciated.

Some links I stumbled across while looking for a solution:

https://issues.apache.org/jira/browse/LUCENE-7674

https://discuss.elastic.co/t/querying-on-a-subobject-field-within-a-nested-object/65533

https://github.com/elastic/elasticsearch/issues/23280

https://github.com/elastic/elasticsearch/issues/11749

答:
There are some typos in your mapping and queries:

Here are some fixed command which does not trigger any error when used on a instance of Elasticsearch 5.6.3.

You can copy and paste either in Kibana or in a Linux terminal (in which case you should edit the first line) and test them on your Elasticsearch instance.

```<code>HOST=10.225.0.2:9200

curl -XPUT "http://$HOST/an_index"

curl -XPUT "http://$HOST/an_index/recording/_mapping" -H 'Content-Type: application/json' -d'
{
  "dynamic": "strict",
  "_all": {
    "enabled": false
  },
  "properties": {
    "id": {
      "type": "integer"
    },
    "soloists": {
      "type": "nested",
      "properties": {
        "person": {
          "properties": {
            "id": {
              "type": "integer"
            },
            "name": {
              "type": "string",
              "index": "not_analyzed"
            }
          }
        }
      }
    },
    "work": {
      "properties": {
        "id": {
          "type": "integer"
        },
        "title": {
          "type": "string",
          "index": "not_analyzed"
        }
      }
    }
  }
}'

curl -XPOST "http://$HOST/an_index/recording/1" -H 'Content-Type: application/json' -d'
{
  "id": 0,
  "soloists": [
    {
      "person": {
        "id": 77957,
        "name": "John doe"
      }
    },
    {
      "person": {
        "id": 1,
        "name": "Jane smith"
      }
    }
  ],
  "work": {
    "id": 0,
    "title": "Test"
  }
}'

curl -XGET "http://$HOST/an_index/recording/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "my_top_results": {
      "global": {},
      "aggs": {
        "my_filter_agg": {
          "filter": {
            "bool": {
              "must": [
                {
                  "bool": {
                    "should": [
                      {
                        "nested": {
                          "path": "soloists",
                          "query": {
                            "bool": {
                              "must": {
                                "match": {
                                  "soloists.person.id": 77957
                                }
                              }
                            }
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          },
          "aggs": {
            "my_nested_agg": {
              "nested": {
                "path": "soloists"
              },
              "aggs": {
                "my_terms_agg": {
                  "terms": {
                    "field": "soloists.person.id",
                    "size": 10
                  },
                  "aggs": {
                    "my_top_hits_agg": {
                      "top_hits": {
                        "size": 1,
                        "_source": {
                          "include": [
                            "soloists.person.id",
                            "soloists.person.name"
                          ]
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}'
</code>```

If those queries work but not when applied to your index, could you please update your question with the output of curl -XGET "http://$HOST/your_index_name" so that we can check the exact settings and mapping of your index? Such an error may be cause by conflict between type on a same index. I'll update my answer accordingly.

Body:
I have an issue with aggregations of nested documents on ElasticSearch 5.6.3.

My query is structured in the following way:

  query
  aggs
  |_filter
    |_nested
      |_term
        |_top-hits

If I try the aggregation on a non-nested field (and with the nested agg removed of course), everything works as expected. But as it is structured now, I receive an exception from Lucene:
Child query must not match same docs with parent filter. Combine them as must clauses (+) to find a problem doc. docId=2147483647, class org.apache.lucene.search.ConstantScoreScorer

This exception is not triggered on ElasticSearch 2.4.6.

I tried to structure the aggregations in a different way, but I couldn't come up with a combination that works and delivers the wanted results.

This is how the mapping looks like:

"recording": {
  "dynamic": "strict",
  "_all" : {
    "enabled" : false
  },
  "properties": {
    "id": {
      "type": "integer"
    },
    "soloists": {
      "properties": {
        "type": "nested",
        "person": {
          "properties": {
            "id": {
             "type": "integer"
            },
            "name": {
              "type": "string",
              "index": "not_analyzed"
            }
         }
      }
    },
    "work": {
      "id": {
        "type": integer
      },
      "title": {
        "type": "string",
        "index": "not_analyzed"
      }
    }
}

And the query itself:

{
  "query": {},
  "aggs": {
    "my_top_results": {
      "global": {},
      "aggs": {
        "my_filter_agg": {
          "filter": {
            "bool": {
              "must": [
                {
                  "bool": {
                    "should": [
                      {
                        "nested": {
                          "path": "soloists",
                          "query": {
                            "bool": {
                              "must": {
                                "match": {
                                  "soloists.person.id": 77957
                                }
                              }
                            }
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          },
          "aggs": {
            "my_nested_agg": {
              "nested": {
                "path": "soloists"
              },
              "aggs": {
                "my_terms_agg": {
                  "term": {
                    "field": "soloists.person.id",
                    "size": 10
                  }
                  "aggs": {
                    "my_top_hits_agg": {
                      "size": 1,
                      "_source": {
                        "include": [
                          "soloists.person.id",
                          "soloists.person.name"
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Any help would be highly appreciated.

Some links I stumbled across while looking for a solution:

https://issues.apache.org/jira/browse/LUCENE-7674

https://discuss.elastic.co/t/querying-on-a-subobject-field-within-a-nested-object/65533

https://github.com/elastic/elasticsearch/issues/23280

https://github.com/elastic/elasticsearch/issues/11749

Body:
There are some typos in your mapping and queries:

Here are some fixed command which does not trigger any error when used on a instance of Elasticsearch 5.6.3.

You can copy and paste either in Kibana or in a Linux terminal (in which case you should edit the first line) and test them on your Elasticsearch instance.

HOST=10.225.0.2:9200

curl -XPUT "http://$HOST/an_index"

curl -XPUT "http://$HOST/an_index/recording/_mapping" -H 'Content-Type: application/json' -d'
{
  "dynamic": "strict",
  "_all": {
    "enabled": false
  },
  "properties": {
    "id": {
      "type": "integer"
    },
    "soloists": {
      "type": "nested",
      "properties": {
        "person": {
          "properties": {
            "id": {
              "type": "integer"
            },
            "name": {
              "type": "string",
              "index": "not_analyzed"
            }
          }
        }
      }
    },
    "work": {
      "properties": {
        "id": {
          "type": "integer"
        },
        "title": {
          "type": "string",
          "index": "not_analyzed"
        }
      }
    }
  }
}'

curl -XPOST "http://$HOST/an_index/recording/1" -H 'Content-Type: application/json' -d'
{
  "id": 0,
  "soloists": [
    {
      "person": {
        "id": 77957,
        "name": "John doe"
      }
    },
    {
      "person": {
        "id": 1,
        "name": "Jane smith"
      }
    }
  ],
  "work": {
    "id": 0,
    "title": "Test"
  }
}'

curl -XGET "http://$HOST/an_index/recording/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "my_top_results": {
      "global": {},
      "aggs": {
        "my_filter_agg": {
          "filter": {
            "bool": {
              "must": [
                {
                  "bool": {
                    "should": [
                      {
                        "nested": {
                          "path": "soloists",
                          "query": {
                            "bool": {
                              "must": {
                                "match": {
                                  "soloists.person.id": 77957
                                }
                              }
                            }
                          }
                        }
                      }
                    ]
                  }
                }
              ]
            }
          },
          "aggs": {
            "my_nested_agg": {
              "nested": {
                "path": "soloists"
              },
              "aggs": {
                "my_terms_agg": {
                  "terms": {
                    "field": "soloists.person.id",
                    "size": 10
                  },
                  "aggs": {
                    "my_top_hits_agg": {
                      "top_hits": {
                        "size": 1,
                        "_source": {
                          "include": [
                            "soloists.person.id",
                            "soloists.person.name"
                          ]
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}'

If those queries work but not when applied to your index, could you please update your question with the output of curl -XGET "http://$HOST/your_index_name" so that we can check the exact settings and mapping of your index? Such an error may be cause by conflict between type on a same index. I'll update my answer accordingly.


问:
How do you query a database using a Date and Time from PHP Function
How do I fix my query code so that it searches the database using a Date and Time but the Date is a variable from the function? I am new to PHP and SQL and don't know how the Dots ( . ) and Quotations fully work ( "" '' ). How do i fix this piece of code?

```<code>WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'
</code>```

Please See code below

```<code>function FSearchDate($FixtureDate) {
    try {
        $conn = new PDO("mysql:host=" . $GLOBALS['servername'] . ";dbname=DATABASE_NAME", $GLOBALS['username'], $GLOBALS['password']);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $statement = $conn->query("
        SELECT Fixtures.fixtureid AS FixtureID,
        Fixtures.date AS Date,
        Fixtures.week AS Week,
        Fixtures.home_team AS HomeTeam,
        Fixtures.away_team AS AwayTeam,
        FixtureScores.home_team AS HomeScore,
        FixtureScores.away_team AS AwayScore
        FROM Fixtures
        INNER JOIN FixtureScores ON Fixtures.fixtureid=FixtureScores.fixtureid
        WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'"
        );
        $result = $statement->fetch();

        if ($result == null) { // Fixture ID Doesn't Exist
            echo '<script type="text/javascript">alert("The Fixture ID entered is not valid. Please enter a valid Fixture ID");</script>';
        } else {
            $GLOBALS['FixtureID'] = $result[0];
            $GLOBALS['FixtureDate'] = $result[1];
            $GLOBALS['FixtureWeek'] = $result[2];
            $GLOBALS['FixtureHomeTeamName'] = $result[3];
            $GLOBALS['FixtureAwayTeamName'] = $result[4];
            $GLOBALS['FixtureHomeTeamScore'] = $result[5];
            $GLOBALS['FixtureAwayTeamScore'] = $result[6];
        }
    }
    catch(PDOException $e) {
        echo "An problem occured: " . $e->getMessage();
    }

    $conn = null;
}
</code>```

答:
You can use here between

```<code>$statement = $conn->query("
    SELECT Fixtures.fixtureid AS FixtureID,
    Fixtures.date AS Date,
    Fixtures.week AS Week,
    Fixtures.home_team AS HomeTeam,
    Fixtures.away_team AS AwayTeam,
    FixtureScores.home_team AS HomeScore,
    FixtureScores.away_team AS AwayScore
    FROM Fixtures
    INNER JOIN FixtureScores ON Fixtures.fixtureid=FixtureScores.fixtureid
    WHERE Fixtures.date BETWEEN 'date('Y-m-d H:i:s',$FixtureDate)' AND 'date('Y-m-d H:i:s',$FixtureDate)'"
    );
</code>```

check this statement,

```<code>WHERE Fixtures.date BETWEEN 'date('Y-m-d H:i:s',$FixtureDate)' AND 'date('Y-m-d H:i:s',$FixtureDate)'
</code>```

Body:
How do I fix my query code so that it searches the database using a Date and Time but the Date is a variable from the function? I am new to PHP and SQL and don't know how the Dots ( . ) and Quotations fully work ( "" '' ). How do i fix this piece of code?

WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'

Please See code below

function FSearchDate($FixtureDate) {
    try {
        $conn = new PDO("mysql:host=" . $GLOBALS['servername'] . ";dbname=DATABASE_NAME", $GLOBALS['username'], $GLOBALS['password']);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $statement = $conn->query("
        SELECT Fixtures.fixtureid AS FixtureID,
        Fixtures.date AS Date,
        Fixtures.week AS Week,
        Fixtures.home_team AS HomeTeam,
        Fixtures.away_team AS AwayTeam,
        FixtureScores.home_team AS HomeScore,
        FixtureScores.away_team AS AwayScore
        FROM Fixtures
        INNER JOIN FixtureScores ON Fixtures.fixtureid=FixtureScores.fixtureid
        WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'"
        );
        $result = $statement->fetch();

        if ($result == null) { // Fixture ID Doesn't Exist
            echo '';
        } else {
            $GLOBALS['FixtureID'] = $result[0];
            $GLOBALS['FixtureDate'] = $result[1];
            $GLOBALS['FixtureWeek'] = $result[2];
            $GLOBALS['FixtureHomeTeamName'] = $result[3];
            $GLOBALS['FixtureAwayTeamName'] = $result[4];
            $GLOBALS['FixtureHomeTeamScore'] = $result[5];
            $GLOBALS['FixtureAwayTeamScore'] = $result[6];
        }
    }
    catch(PDOException $e) {
        echo "An problem occured: " . $e->getMessage();
    }

    $conn = null;
}

Body:
You can use here between

$statement = $conn->query("
    SELECT Fixtures.fixtureid AS FixtureID,
    Fixtures.date AS Date,
    Fixtures.week AS Week,
    Fixtures.home_team AS HomeTeam,
    Fixtures.away_team AS AwayTeam,
    FixtureScores.home_team AS HomeScore,
    FixtureScores.away_team AS AwayScore
    FROM Fixtures
    INNER JOIN FixtureScores ON Fixtures.fixtureid=FixtureScores.fixtureid
    WHERE Fixtures.date BETWEEN 'date('Y-m-d H:i:s',$FixtureDate)' AND 'date('Y-m-d H:i:s',$FixtureDate)'"
    );

check this statement,

WHERE Fixtures.date BETWEEN 'date('Y-m-d H:i:s',$FixtureDate)' AND 'date('Y-m-d H:i:s',$FixtureDate)'


问:
Embedded Cassandra with Spark and DataStax Driver Error
We are using following dependencies for our project.

```<code>val cassandraConnector = "com.datastax.spark" %% "spark-cassandra-connector" % "2.0.0"
val sparkSql = "org.apache.spark" % "spark-sql_2.11" % "2.2.0"
val phantomDsl = "com.outworkers" % "phantom-dsl_2.11" % "2.15.5"
val cassandraUnit = "org.cassandraunit" % "cassandra-unit" % "3.3.0.2" % "test"
</code>```

While running the test cases using the command sbt compile test.
We are getting following error:-

```<code>[error] java.lang.IncompatibleClassChangeError: Class com.datastax.driver.core.DefaultResultSetFuture does not implement the requested interface com.google.common.util.concurrent.ListenableFuture
[error]     at com.google.common.util.concurrent.Futures.addCallback(Futures.java:1776)
[error]     at com.outworkers.phantom.builder.query.execution.PromiseInterface$$anon$1.fromGuava(ExactlyOncePromise.scala:56)
[error]     at com.outworkers.phantom.builder.query.execution.PromiseInterface$$anon$1.fromGuava(ExactlyOncePromise.scala:63)
[error]     at com.outworkers.phantom.builder.query.execution.GuavaAdapter$class.fromGuava(ExecutableStatements.scala:44)
[error]     at com.outworkers.phantom.builder.query.execution.PromiseInterface$$anon$1.fromGuava(ExactlyOncePromise.scala:39)
[error]     at com.outworkers.phantom.builder.query.execution.ExecutableStatements$$anonfun$future$1.apply(ExecutableStatements.scala:112)
[error]     at com.outworkers.phantom.builder.query.execution.ExecutableStatements$$anonfun$future$1.apply(ExecutableStatements.scala:110)
[error]     at scala.collection.immutable.List.foreach(List.scala:381)
[error]     at com.outworkers.phantom.builder.query.execution.ExecutableStatements.future(ExecutableStatements.scala:110)
[error]     at com.outworkers.phantom.ops.DbOps.truncateAsync(DbOps.scala:104)
[error]     at com.outworkers.phantom.ops.DbOps.truncate(DbOps.scala:94)
[error]     at com.knoldus.cassandra.CassandraDatabaseCluster$class.afterAll(CassandraDatabaseCluster.scala:29)
[error]     at com.knoldus.model.PredicateHashingSuite.afterAll(PredicateHashingSuite.scala:7)
[error]     at org.scalatest.BeforeAndAfterAll$$anonfun$1.apply$mcV$sp(BeforeAndAfterAll.scala:225)
[error]     at org.scalatest.Status$$anonfun$withAfterEffect$1.apply(Status.scala:379)
[error]     at org.scalatest.Status$$anonfun$withAfterEffect$1.apply(Status.scala:375)
[error]     at org.scalatest.FailedStatus$.whenCompleted(Status.scala:497)
[error]     at org.scalatest.Status$class.withAfterEffect(Status.scala:375)
[error]     at org.scalatest.FailedStatus$.withAfterEffect(Status.scala:469)
[error]     at org.scalatest.BeforeAndAfterAll$class.run(BeforeAndAfterAll.scala:223)
[error]     at com.knoldus.model.PredicateHashingSuite.run(PredicateHashingSuite.scala:7)
[error]     at org.scalatest.tools.Framework.org$scalatest$tools$Framework$$runSuite(Framework.scala:314)
[error]     at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:480)
[error]     at sbt.TestRunner.runTest$1(TestFramework.scala:102)
[error]     at sbt.TestRunner.run(TestFramework.scala:113)
[error]     at sbt.TestFramework$$anon$2$$anonfun$$lessinit$greater$1.$anonfun$apply$1(TestFramework.scala:258)
[error]     at sbt.TestFramework$.sbt$TestFramework$$withContextLoader(TestFramework.scala:229)
[error]     at sbt.TestFramework$$anon$2$$anonfun$$lessinit$greater$1.apply(TestFramework.scala:258)
[error]     at sbt.TestFramework$$anon$2$$anonfun$$lessinit$greater$1.apply(TestFramework.scala:258)
[error]     at sbt.TestFunction.apply(TestFramework.scala:267)
[error]     at sbt.Tests$.$anonfun$toTask$1(Tests.scala:276)
[error]     at sbt.std.Transform$$anon$3.$anonfun$apply$2(System.scala:44)
[error]     at sbt.std.Transform$$anon$4.work(System.scala:64)
[error]     at sbt.Execute.$anonfun$submit$2(Execute.scala:257)
[error]     at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
[error]     at sbt.Execute.work(Execute.scala:266)
[error]     at sbt.Execute.$anonfun$submit$1(Execute.scala:257)
[error]     at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:167)
[error]     at sbt.CompletionService$$anon$2.call(CompletionService.scala:32)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[error]     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[error]     at java.lang.Thread.run(Thread.java:748)
</code>```

Is there something wrong within dependency?

How can we get rid of this error?

Thanks

答:
That's really interesting, however it's not to do with phantom, it's to do with the Guava Library dependency that somehow ends up clashing with what is on the classpath.

In short, basically the problem comes from a binary incompatibility/exclusion, so Spark or something else in your classpath overrides the version of Guava in phantom.

If you print out evictions I can help you further.

We also offer phantom-sbt as an integrated SBT plugin for Cassandra, which I would suspect as the root cause here, as well as a Docker integration via SBT(pro only feature). Maybe file a GitHub issue for phantom, and we can follow up there more easily as soon as we know which versions clash.

Body:
We are using following dependencies for our project.

val cassandraConnector = "com.datastax.spark" %% "spark-cassandra-connector" % "2.0.0"
val sparkSql = "org.apache.spark" % "spark-sql_2.11" % "2.2.0"
val phantomDsl = "com.outworkers" % "phantom-dsl_2.11" % "2.15.5"
val cassandraUnit = "org.cassandraunit" % "cassandra-unit" % "3.3.0.2" % "test"

While running the test cases using the command sbt compile test.
We are getting following error:-

[error] java.lang.IncompatibleClassChangeError: Class com.datastax.driver.core.DefaultResultSetFuture does not implement the requested interface com.google.common.util.concurrent.ListenableFuture
[error]     at com.google.common.util.concurrent.Futures.addCallback(Futures.java:1776)
[error]     at com.outworkers.phantom.builder.query.execution.PromiseInterface$$anon$1.fromGuava(ExactlyOncePromise.scala:56)
[error]     at com.outworkers.phantom.builder.query.execution.PromiseInterface$$anon$1.fromGuava(ExactlyOncePromise.scala:63)
[error]     at com.outworkers.phantom.builder.query.execution.GuavaAdapter$class.fromGuava(ExecutableStatements.scala:44)
[error]     at com.outworkers.phantom.builder.query.execution.PromiseInterface$$anon$1.fromGuava(ExactlyOncePromise.scala:39)
[error]     at com.outworkers.phantom.builder.query.execution.ExecutableStatements$$anonfun$future$1.apply(ExecutableStatements.scala:112)
[error]     at com.outworkers.phantom.builder.query.execution.ExecutableStatements$$anonfun$future$1.apply(ExecutableStatements.scala:110)
[error]     at scala.collection.immutable.List.foreach(List.scala:381)
[error]     at com.outworkers.phantom.builder.query.execution.ExecutableStatements.future(ExecutableStatements.scala:110)
[error]     at com.outworkers.phantom.ops.DbOps.truncateAsync(DbOps.scala:104)
[error]     at com.outworkers.phantom.ops.DbOps.truncate(DbOps.scala:94)
[error]     at com.knoldus.cassandra.CassandraDatabaseCluster$class.afterAll(CassandraDatabaseCluster.scala:29)
[error]     at com.knoldus.model.PredicateHashingSuite.afterAll(PredicateHashingSuite.scala:7)
[error]     at org.scalatest.BeforeAndAfterAll$$anonfun$1.apply$mcV$sp(BeforeAndAfterAll.scala:225)
[error]     at org.scalatest.Status$$anonfun$withAfterEffect$1.apply(Status.scala:379)
[error]     at org.scalatest.Status$$anonfun$withAfterEffect$1.apply(Status.scala:375)
[error]     at org.scalatest.FailedStatus$.whenCompleted(Status.scala:497)
[error]     at org.scalatest.Status$class.withAfterEffect(Status.scala:375)
[error]     at org.scalatest.FailedStatus$.withAfterEffect(Status.scala:469)
[error]     at org.scalatest.BeforeAndAfterAll$class.run(BeforeAndAfterAll.scala:223)
[error]     at com.knoldus.model.PredicateHashingSuite.run(PredicateHashingSuite.scala:7)
[error]     at org.scalatest.tools.Framework.org$scalatest$tools$Framework$$runSuite(Framework.scala:314)
[error]     at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:480)
[error]     at sbt.TestRunner.runTest$1(TestFramework.scala:102)
[error]     at sbt.TestRunner.run(TestFramework.scala:113)
[error]     at sbt.TestFramework$$anon$2$$anonfun$$lessinit$greater$1.$anonfun$apply$1(TestFramework.scala:258)
[error]     at sbt.TestFramework$.sbt$TestFramework$$withContextLoader(TestFramework.scala:229)
[error]     at sbt.TestFramework$$anon$2$$anonfun$$lessinit$greater$1.apply(TestFramework.scala:258)
[error]     at sbt.TestFramework$$anon$2$$anonfun$$lessinit$greater$1.apply(TestFramework.scala:258)
[error]     at sbt.TestFunction.apply(TestFramework.scala:267)
[error]     at sbt.Tests$.$anonfun$toTask$1(Tests.scala:276)
[error]     at sbt.std.Transform$$anon$3.$anonfun$apply$2(System.scala:44)
[error]     at sbt.std.Transform$$anon$4.work(System.scala:64)
[error]     at sbt.Execute.$anonfun$submit$2(Execute.scala:257)
[error]     at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
[error]     at sbt.Execute.work(Execute.scala:266)
[error]     at sbt.Execute.$anonfun$submit$1(Execute.scala:257)
[error]     at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:167)
[error]     at sbt.CompletionService$$anon$2.call(CompletionService.scala:32)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[error]     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[error]     at java.lang.Thread.run(Thread.java:748)

Is there something wrong within dependency?

How can we get rid of this error?

Thanks


问:
Possible Sum Of Numbers in a List
```<code>List1=[1,2,3]
</code>```

I want an output like below

```<code>[6,5,4,3]
</code>```

That is the maximum sum is 6.
But what I like to do is I want all possible sums inside that list.
That is 3+2 , 2+1 , 1+3 , etc.. like all possible ways.

答:
How's this work for you?

```<code>from itertools import chain, combinations

list1 = [1, 2, 3]
n = len(list1)
c = (combinations(list1, r) for r in range(2, n+1))
c = set(sum(i) for i in chain.from_iterable(c))

print(c)
# {3, 4, 5, 6}
</code>```

The result will be unique sums of each combination of length r, with r running from 2 up thru the length of your input list.  The result uses a set constructor to guarantee unique values.

In a function:

```<code>def unique_sum(obj):
    return set(sum(i) for i in chain.from_iterable(
        combinations(obj, r) for r in range(2, len(obj)+1)))

unique_sum([5, 5, 5])
# {10, 15}
</code>```

Title: Possible Sum Of Numbers in a List

Body:
List1=[1,2,3]

I want an output like below

[6,5,4,3]

That is the maximum sum is 6.
But what I like to do is I want all possible sums inside that list.
That is 3+2 , 2+1 , 1+3 , etc.. like all possible ways.

Body:
How's this work for you?

from itertools import chain, combinations

list1 = [1, 2, 3]
n = len(list1)
c = (combinations(list1, r) for r in range(2, n+1))
c = set(sum(i) for i in chain.from_iterable(c))

print(c)
# {3, 4, 5, 6}

The result will be unique sums of each combination of length r, with r running from 2 up thru the length of your input list.  The result uses a set constructor to guarantee unique values.

In a function:

def unique_sum(obj):
    return set(sum(i) for i in chain.from_iterable(
        combinations(obj, r) for r in range(2, len(obj)+1)))

unique_sum([5, 5, 5])
# {10, 15}


问:
How to make certain values in dictionary add up to 100?
I have a dictionary with varying number of items. Each item can have a value of either a 1 or 0. Those with a value of 1 are stored in a list and counted. This is then used to calculate a percentage which would then be used to replace the value 1.

For example: if I have 10 items and only 7 contain a value of 1, the calculated percentage would be 100 / 7 = 14. Therefore those 7 items will have a new value of 14.

But there is a remainder left over and what I would like is for some items to gain this remainder (so 5 items would have a value of 14, 2 items would have a value of 15 so that (5 * 14) + (2 * 15) = 100.

How could this be done?

This is the code I used which gets the percentage value but I am unsure how to implement the remainder part (I would like to only show integers in the dictionary):

```<code>someDict = {
        'item_01': 0,
        'item_02': 0,
        'item_03': 0,
        'item_04': 1,
        'item_05': 1,
        'item_06': 1,
        'item_07': 1,
        'item_08': 1,
        'item_09': 1,
        'item_010': 1
        }

percentage_list = []
for key, value in someDict.items():
    if value == 1:
        percentage_list.append(value)

percentage_value = int(100) / int(len(percentage_list))
# =98

# Replace all 1's in someDict with percentage value
for key, value in someDict.items():
    if value == 1:
        someDict[key] = percentage_value
</code>```

答:
You should use // for int division and % for the remainder:</p>

```<code>someDict = {
        'item_01': 0,
        'item_02': 0,
        'item_03': 0,
        'item_04': 1,
        'item_05': 1,
        'item_06': 1,
        'item_07': 1,
        'item_08': 1,
        'item_09': 1,
        'item_010': 1
        }

percentage_list = []
for key, value in someDict.items():
    if value == 1:
        percentage_list.append(value)

percentage_value = 100 // len(percentage_list)
remainder_value = 100 % len(percentage_list)

# Replace all 1's in someDict with percentage value
for key, value in someDict.items():
    if value == 1:
        if remainder_value > 0:
            someDict[key] = percentage_value + 1
            remainder_value -= 1
        else:
            someDict[key] = percentage_value

print(someDict)
</code>```

Body:
I have a dictionary with varying number of items. Each item can have a value of either a 1 or 0. Those with a value of 1 are stored in a list and counted. This is then used to calculate a percentage which would then be used to replace the value 1.

For example: if I have 10 items and only 7 contain a value of 1, the calculated percentage would be 100 / 7 = 14. Therefore those 7 items will have a new value of 14.

But there is a remainder left over and what I would like is for some items to gain this remainder (so 5 items would have a value of 14, 2 items would have a value of 15 so that (5 * 14) + (2 * 15) = 100.

How could this be done?

This is the code I used which gets the percentage value but I am unsure how to implement the remainder part (I would like to only show integers in the dictionary):

someDict = {
        'item_01': 0,
        'item_02': 0,
        'item_03': 0,
        'item_04': 1,
        'item_05': 1,
        'item_06': 1,
        'item_07': 1,
        'item_08': 1,
        'item_09': 1,
        'item_010': 1
        }

percentage_list = []
for key, value in someDict.items():
    if value == 1:
        percentage_list.append(value)

percentage_value = int(100) / int(len(percentage_list))
# =98

# Replace all 1's in someDict with percentage value
for key, value in someDict.items():
    if value == 1:
        someDict[key] = percentage_value

Body:
You should use // for int division and % for the remainder:

someDict = {
        'item_01': 0,
        'item_02': 0,
        'item_03': 0,
        'item_04': 1,
        'item_05': 1,
        'item_06': 1,
        'item_07': 1,
        'item_08': 1,
        'item_09': 1,
        'item_010': 1
        }

percentage_list = []
for key, value in someDict.items():
    if value == 1:
        percentage_list.append(value)

percentage_value = 100 // len(percentage_list)
remainder_value = 100 % len(percentage_list)

# Replace all 1's in someDict with percentage value
for key, value in someDict.items():
    if value == 1:
        if remainder_value > 0:
            someDict[key] = percentage_value + 1
            remainder_value -= 1
        else:
            someDict[key] = percentage_value

print(someDict)


问:
object oriented JavaScript
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

```<code>function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
</code>```

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

```<code>function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

and

```<code>var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

答:
Please see vo Wetzel's answer </p>

<p>You may be looking some thing similar to this </p>

```<code>// OOP style template obj
Point = {
    x:null,
    y:null
};

var newpoint = new Array(); // An array to hold Point type objects

// now add some entriedsto the above array
for(var i=0 ; i<10; i ++)
{
    newpoint[i] = new Point(); // create a new point object
    newpoint[i].x = 10*i; // set the values of the point object you just created
    newpoint[i].y = 10*i;
}

for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +', y='+newpoint[arrayindex].y);
}
</code>```

Title: object oriented JavaScript

Body:
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

and

var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

Body:
Please see vo Wetzel's answer

You may be looking some thing similar to this

// OOP style template obj
Point = {
    x:null,
    y:null
};

var newpoint = new Array(); // An array to hold Point type objects

// now add some entriedsto the above array
for(var i=0 ; i<10; i ++)
{
    newpoint[i] = new Point(); // create a new point object
    newpoint[i].x = 10*i; // set the values of the point object you just created
    newpoint[i].y = 10*i;
}

for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +', y='+newpoint[arrayindex].y);
}


问:
Center contents of div horizontally/vertically and align text to image
I have a bootstrap div container split into 3 divs of equal sizes (widths are equal but not sure how to maintain height as well). I am not able to center the contents of it vertically and horizontally. Also, I am unable to figure out how to center a text that lies on the right of an image.

My HTML code:

```<code><div class="container-fluid">
  <div>
    <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
    <div> Test comments </div>
  </div>
</div>
</code>```

Here is JsFiddle

And my expected output:

答:
You should use display:flex on the .container >div together with align-items:center and justify-content:center

Also, if you are using bootstrap, why don't you structure your html in rows and cols ? That's what bootstrap is for :)

For example in your case use make a structure like

```<code><div class="container-fluid">
    <div class="row">
         <div class="col-sm-4">
         </div>
         <div class="col-sm-4">
         </div>
         <div class="col-sm-4">
         </div>
    </div>
 </div>
</code>```

Anyway, see snippet below with the solution

.container-fluid {
  padding: 0 !important;
  margin: 0 !important;
}

.container-fluid > div {
  width: 33.33%;
  float: left;
  background-color: #34caf7;
  display: flex;
  align-items: center;
  justify-content: center;
}

.container-fluid > div > img {
  float: left;
  margin: auto;
  width: 20%;
}

.container-fluid > div > div {
  float: left;
  color: white;
  display: block;
  margin: auto;
}

@media (max-width: 480px) {
  .container-fluid > div {
    display: block;
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid">
  <div>
    <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
    <div> Test comments </div>
  </div>
</div></code>```

Body:
I have a bootstrap div container split into 3 divs of equal sizes (widths are equal but not sure how to maintain height as well). I am not able to center the contents of it vertically and horizontally. Also, I am unable to figure out how to center a text that lies on the right of an image.

My HTML code:

 Test comments

 Test comments

 Test comments

Here is JsFiddle

And my expected output:

Body:
You should use display:flex on the .container >div together with align-items:center and justify-content:center

Also, if you are using bootstrap, why don't you structure your html in rows and cols ? That's what bootstrap is for :)

For example in your case use make a structure like

<div class="container-fluid">
    <div class="row">
         <div class="col-sm-4">
         </div>
         <div class="col-sm-4">
         </div>
         <div class="col-sm-4">
         </div>
    </div>
 </div>

Anyway, see snippet below with the solution

.container-fluid {
  padding: 0 !important;
  margin: 0 !important;
}

.container-fluid > div {
  width: 33.33%;
  float: left;
  background-color: #34caf7;
  display: flex;
  align-items: center;
  justify-content: center;
}

.container-fluid > div > img {
  float: left;
  margin: auto;
  width: 20%;
}

.container-fluid > div > div {
  float: left;
  color: white;
  display: block;
  margin: auto;
}

@media (max-width: 480px) {
  .container-fluid > div {
    display: block;
    width: 100%;
  }
}

<div class="container-fluid">
  <div>
    <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
    <div> Test comments </div>
  </div>
</div>


问:
Can I share a service between Angular and Node?
I have a standard utility service in my Angular5 Typescript app.
I want to share that with my node application, which is serving the app.

I can't find any info around it but I see issues as:

Using require() to import a TS file, and if the generated js file
lives in the same place

Ignoring the @Injectable which is a decorator
used on the angular service.

I assume it's possible as that's a major benefit of using full stack Javascript, but how can it be done?

I've  tried the following in NodeJs, which throws an error:

```<code>const utilService = require('../../src/app/services/util/util.service');
</code>```

答:
I would create a private npm package containing your utilities requests.

Then import it into your angular project and node project.

Body:
I have a standard utility service in my Angular5 Typescript app.
I want to share that with my node application, which is serving the app.

I can't find any info around it but I see issues as:

Using require() to import a TS file, and if the generated js file
lives in the same place

Ignoring the @Injectable which is a decorator
used on the angular service.

I assume it's possible as that's a major benefit of using full stack Javascript, but how can it be done?

I've  tried the following in NodeJs, which throws an error:

const utilService = require('../../src/app/services/util/util.service');