问:
Add action in ionic2 notifications buttons
I'm trying to build an ionic2 application which send some guidance notifications to users,i want to send the user to a specific page when he click on the notification and not the homepage.
Here is my code:</p>

```<code>public schedule(title, text) {
        LocalNotifications.schedule({
            title,
            text,
            at: new Date(new Date().getTime() + 1* 1000)

        });
    }

LocalNotifications.on("click", (notification, state) => {

            let alert = this.alertCtrl.create({
                title: this.todos[this.num].info.nom_du_musee,
                subTitle: this.todos[this.num].info.periode_ouverture+" "+this.todos[this.num].info.adr+"  site web  "+this.todos[this.num].info.sitweb,
                buttons: ["OK"]
            });
            alert.present()
        });

  }
</code>```

答:
You can add a handler to the button as per https://ionicframework.com/docs/api/components/alert/AlertController/

```<code>let alert = this.alertCtrl.create({
    title: this.todos[this.num].info.nom_du_musee,
    subTitle: this.todos[this.num].info.periode_ouverture+" "+this.todos[this.num].info.adr+"  site web  "+this.todos[this.num].info.sitweb,
    buttons: [
      {
        text: 'OK',
        handler: () => {
          console.log('OK clicked');
        }
      }
    ]
});

alert.present()
</code>```

The next stage is to replace the console.log with the code to push the new page ..

```<code>this.navCtrl.push(DestinationPage);
</code>```

Body:
I'm trying to build an ionic2 application which send some guidance notifications to users,i want to send the user to a specific page when he click on the notification and not the homepage.
Here is my code:

public schedule(title, text) {
        LocalNotifications.schedule({
            title,
            text,
            at: new Date(new Date().getTime() + 1* 1000)

        });
    }

LocalNotifications.on("click", (notification, state) => {

            let alert = this.alertCtrl.create({
                title: this.todos[this.num].info.nom_du_musee,
                subTitle: this.todos[this.num].info.periode_ouverture+" "+this.todos[this.num].info.adr+"  site web  "+this.todos[this.num].info.sitweb,
                buttons: ["OK"]
            });
            alert.present()
        });

  }

Body:
You can add a handler to the button as per https://ionicframework.com/docs/api/components/alert/AlertController/

let alert = this.alertCtrl.create({
    title: this.todos[this.num].info.nom_du_musee,
    subTitle: this.todos[this.num].info.periode_ouverture+" "+this.todos[this.num].info.adr+"  site web  "+this.todos[this.num].info.sitweb,
    buttons: [
      {
        text: 'OK',
        handler: () => {
          console.log('OK clicked');
        }
      }
    ]
});

alert.present()

The next stage is to replace the console.log with the code to push the new page ..

this.navCtrl.push(DestinationPage);


来源: stackexchange

问:
Java: Hibernate does not see changes in DataBase
I have two different applications that share the same database. The problem is that when I have an application change something in the database, the other does not update.

I tried to make a session.flush() but it didn't work. The only way is to close the entire session and recreate it, but of course, that takes too long.

答:
Short answer: issue a session.refresh(obj) every time you want to display some object. It will force Hibernate to go to the database. Another solution is to use a StatelessSession, which won't cache anything (not even 1st level cache), forcing your applications to go the database every time a record is needed:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/batch.html#batch-statelesssession

But of course, if that's too much, then you can consider using some sort of locking (pessimistic or optimistic):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/transactions.html#transactions-optimistic

But really, if you have two different concurrent systems using the same record, there's nothing that Hibernate can solve by itself. It is something that you should consider in the architecture of your systems.

ContentLicense: CC BY-SA 3.0


问:
How to take Linear Model results with interactive variables & transformations and create an algebraic equation
I have a project to estimate commercial real estate properties given categorical and continuous variables. I have ran a step-wise linear regression model to pick out a good formula in RStudio. (Adj. Rsq = .90 also, I know I need to do PCA and some type of categorical ANOVA test still, but I just want to get a beta estimator out before going deeper.)

How do I take the resulting output from my step(lm()) function and create an character based algebraic expression/equation with the coefficients, like:

log(price)= M1X1 + M2X2 + ... + MnXn.

Where M is my coefficient, and X is my variable. I know I could do it by hand in excel but with so many interactions and base variables it seems excessive. Maybe there is a function in R, or I could make a function in python that would ask what are the values for the variables needed for the calculation; but I haven't thought of any.

Thank you so much! If anything is not specific enough I will do my best to further explain.

答:
As far as I know there is no built in function to do this (formulas can get quite messy for different model types). But if you have a simple linear model, perhaps this function can help

```<code>as_disp_eqn <- function(model, formatter=prettyNum, ...) {
    model_terms <- terms(model)
    model_response <- deparse(as.list(attr(model_terms, "variables")[-1])[[attr(model_terms, "response")]])
    coefs <- coef(model)
    rhs <- paste0(formatter(coefs, ...), ifelse(names(coefs)!="(Intercept)", paste(" *", names(coefs)),""))
    paste(model_response, "=", paste(rhs, collapse=" + "))
}
</code>```

You can pass in a model and get a printed display. For example

```<code>mm <- lm(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Species, data = iris)
as_disp_eqn(mm, digits=2)
# [1] "Sepal.Length = 2.4 + 0.43 * Sepal.Width + 0.78 * Petal.Length + -0.96 * Speciesversicolor + -1.4 * Speciesvirginica"
</code>```

Body:
As far as I know there is no built in function to do this (formulas can get quite messy for different model types). But if you have a simple linear model, perhaps this function can help

as_disp_eqn <- function(model, formatter=prettyNum, ...) {
    model_terms <- terms(model)
    model_response <- deparse(as.list(attr(model_terms, "variables")[-1])[[attr(model_terms, "response")]])
    coefs <- coef(model)
    rhs <- paste0(formatter(coefs, ...), ifelse(names(coefs)!="(Intercept)", paste(" *", names(coefs)),""))
    paste(model_response, "=", paste(rhs, collapse=" + "))
}

You can pass in a model and get a printed display. For example

mm <- lm(formula = Sepal.Length ~ Sepal.Width + Petal.Length + Species, data = iris)
as_disp_eqn(mm, digits=2)
# [1] "Sepal.Length = 2.4 + 0.43 * Sepal.Width + 0.78 * Petal.Length + -0.96 * Speciesversicolor + -1.4 * Speciesvirginica"


问:
Python argparse requiring option, depending on the defined flags
I have a small python script, which uses argparse to let the user define options. It uses two flags for different modes and an argument to let the user define a file. See the simplified example below:

```<code>#!/usr/bin/python3

import argparse
from shutil import copyfile

def check_file(f):
    # Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
    return f

def main():
    aFile = "/tmp/afile.txt"

    parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
    parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
    parser.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')

    args = parser.parse_args()
    f = args.file
    a = args.ay
    b = args.be

    if a:
        copyfile(f, f+".a")
    elif b:
        print("Method B")

if __name__ == "__main__":
    main()
</code>```

Method A requires the file.

Method B does not.

If I run the script with method A, I either use the default file or one that is defined with -f/--file. The script checks if the file exists and everything is fine.

Now, if I run the script with method B, it shouldn't require the file, but the default option is checked and if it doesn't exist the argparse function raises the exception and the script exits.

How can I configure argparse to make -f optional, if -b is defined and require it, if -a is defined?

edit: I just realized that it would be enough for me to make -f and -b mutually exclusive. But then, if I run -b only, the check_file is executed anyways. Is there a way to prevent that?

```<code>#!/usr/bin/python3

import argparse
from shutil import copyfile

def check_file(f):
    # Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
    print("chk file")
    return f

def main():
    aFile = "/tmp/afile.txt"

    parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
    group = parser.add_mutually_exclusive_group(required=True)

    group.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
    parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
    group.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')

    args = parser.parse_args()
    f = args.file
    a = args.ay
    b = args.be

    if a:
        print("File: "+str(f))
    elif b:
        print("Method B")
        print("file: "+str(f))

if __name__ == "__main__":
    main()
</code>```

Output:

```<code>chk file
Method B
file: /tmp/afile.txt
</code>```

答:
Your problem lies with how argparse handles defaults.  You'd get this behavior even if -f was the only argument.  If the default is a string value, it will be 'evaluated' if the Action isn't seen.

```<code>parser.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
</code>```

At the start of parsing defaults are put into the args namespace. During parsing it keeps track of whether Actions have been seen.  At the end of parsing it checks Namespace values for Actions which haven't been seen.  If they match the default (the usual case) and are strings, it passes the default through the type function.

In your -f case, the default is probably a file name, a string.  So it will be 'evaluated' if the user doesn't provide an alternative.  In earlier argparse versions defaults were evaluate regardless of whether they were used or not.  For something like a int or float type that wasn't a problem, but for FileType it could result in unneeded file opening/creation.

Ways around this?

write check_file so it gracefully handles aFile.

make sure aFile is valid so check_file runs without error.  This the usual case.

use a non-string default, e.g. an already open file.

use the default default None, and add the default value after parsing.

if args.file is None:
     args.file = aFile

Combining this with -a and -b actions you have to decide whether:

if -a, is a -f value required?  If -f isn't provided, what's the right default.

if -b, does it matter whether -f has a default or whether the user provides this argument?  Could you just ignore it?

If -f is useful only when -a is True, why not combine them?

```<code>parser.add_argument('-a', nargs='?', default=None, const='valid_file', type=check_file)
</code>```

With ?, this works in 3 ways. (docs on const)

no -a, args.a = default

bare -a, args.a = const

-a afile,args.a = afile

An even simpler example of this behavior

```<code>In [956]: p = argparse.ArgumentParser()
In [957]: p.add_argument('-f',type=int, default='astring')
...
In [958]: p.parse_args('-f 1'.split())
Out[958]: Namespace(f=1)
In [959]: p.parse_args(''.split())
usage: ipython3 [-h] [-f F]
ipython3: error: argument -f: invalid int value: 'astring'
</code>```

The string default is passed through int resulting in an error.  If I'd set default to something else like a list, default=[1,2,3], it would have run even though int would have choked on the default.

Body:
I have a small python script, which uses argparse to let the user define options. It uses two flags for different modes and an argument to let the user define a file. See the simplified example below:

#!/usr/bin/python3

import argparse
from shutil import copyfile

def check_file(f):
    # Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
    return f

def main():
    aFile = "/tmp/afile.txt"

    parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
    parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
    parser.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')

    args = parser.parse_args()
    f = args.file
    a = args.ay
    b = args.be

    if a:
        copyfile(f, f+".a")
    elif b:
        print("Method B")

if __name__ == "__main__":
    main()

Method A requires the file.

Method B does not.

If I run the script with method A, I either use the default file or one that is defined with -f/--file. The script checks if the file exists and everything is fine.

Now, if I run the script with method B, it shouldn't require the file, but the default option is checked and if it doesn't exist the argparse function raises the exception and the script exits.

How can I configure argparse to make -f optional, if -b is defined and require it, if -a is defined?

edit: I just realized that it would be enough for me to make -f and -b mutually exclusive. But then, if I run -b only, the check_file is executed anyways. Is there a way to prevent that?

#!/usr/bin/python3

import argparse
from shutil import copyfile

def check_file(f):
    # Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
    print("chk file")
    return f

def main():
    aFile = "/tmp/afile.txt"

    parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
    group = parser.add_mutually_exclusive_group(required=True)

    group.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
    parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
    group.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')

    args = parser.parse_args()
    f = args.file
    a = args.ay
    b = args.be

    if a:
        print("File: "+str(f))
    elif b:
        print("Method B")
        print("file: "+str(f))

if __name__ == "__main__":
    main()

Output:

chk file
Method B
file: /tmp/afile.txt

Body:
Your problem lies with how argparse handles defaults.  You'd get this behavior even if -f was the only argument.  If the default is a string value, it will be 'evaluated' if the Action isn't seen.

parser.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)

At the start of parsing defaults are put into the args namespace. During parsing it keeps track of whether Actions have been seen.  At the end of parsing it checks Namespace values for Actions which haven't been seen.  If they match the default (the usual case) and are strings, it passes the default through the type function.

In your -f case, the default is probably a file name, a string.  So it will be 'evaluated' if the user doesn't provide an alternative.  In earlier argparse versions defaults were evaluate regardless of whether they were used or not.  For something like a int or float type that wasn't a problem, but for FileType it could result in unneeded file opening/creation.

Ways around this?

write check_file so it gracefully handles aFile.

make sure aFile is valid so check_file runs without error.  This the usual case.

use a non-string default, e.g. an already open file.

use the default default None, and add the default value after parsing.

if args.file is None:
     args.file = aFile

Combining this with -a and -b actions you have to decide whether:

if -a, is a -f value required?  If -f isn't provided, what's the right default.

if -b, does it matter whether -f has a default or whether the user provides this argument?  Could you just ignore it?

If -f is useful only when -a is True, why not combine them?

parser.add_argument('-a', nargs='?', default=None, const='valid_file', type=check_file)

With ?, this works in 3 ways. (docs on const)

no -a, args.a = default

bare -a, args.a = const

-a afile,args.a = afile

An even simpler example of this behavior

In [956]: p = argparse.ArgumentParser()
In [957]: p.add_argument('-f',type=int, default='astring')
...
In [958]: p.parse_args('-f 1'.split())
Out[958]: Namespace(f=1)
In [959]: p.parse_args(''.split())
usage: ipython3 [-h] [-f F]
ipython3: error: argument -f: invalid int value: 'astring'

The string default is passed through int resulting in an error.  If I'd set default to something else like a list, default=[1,2,3], it would have run even though int would have choked on the default.


问:
Suppressing SUCCESS alert boxes?
I have three functions that called as shown below (Functions not included):

Code:

```<code>$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSourcepData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSpouseData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSpousData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllDividentData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveDividentData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
</code>```

When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".

This forces user to have to close three popup boxes.

Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?

答:
You can reorder a little your code to use the deferred method to jQuery 1.5+ otherwise you can implement as this answer:

jQuery callback for multiple ajax calls

Title: Suppressing SUCCESS alert boxes?

Body:
I have three functions that called as shown below (Functions not included):

Code:

$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSourcepData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSourceData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllSpouseData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveSpousData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});
$("#btnSubmit").click(function() {
    var data = JSON.stringify(getAllDividentData());
    console.log(data);
    $.ajax({
        url: 'closures.aspx/SaveDividentData',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            'empdata': data
        }),
        success: function() {
            alert("Data Added Successfully");
        },
        error: function() {
            alert("Error while inserting data");
        }
    });
});

When data is submitted successfully, three alert boxes popup, each with same message: "Data Added Successfully".

This forces user to have to close three popup boxes.

Is there a way to disable the success alert boxes leaving just one? Or even all three be disabled allowing me to come up with a custom Success message?


问:
Why body of html page does not extend to full width in Edge and IE but is ok for all other browsers?
I have a webpage under development. Let's forget the contents. It is not relevant. It looks fine in Chrome, Safari and Firefox, but it does not extend to full width in Edge or Internet Explorer.

If I write in their consoles (with the help of jQuery)

```<code>$('body').width($(window).width())
</code>```

the body extends to the full screen width and is ok again. I have been trying to debug the page via console, but have not managed to find the reason.

DOM of the page in the reference acts as a source.

This happens only when screen width is above 990 (due to the media queries I use).

答:
The CSS selector .svg that is being applied to your html element is is telling it to be an inline element with display: inline-block;. If you remove the display property from .svg or change the value to block the page will fill the browser viewport appropriately.

The CSS selector in question.

```<code>.svg {
  display: inline-block; /* <= the problem */
  background: 0 0;
  border: none;
}
</code>```

From what I can tell you're using Modernizr to do some feature detection and it added the .svg class to html and you create your own .svg for some other purpose not knowing that Modernizr added .svg to html.

If the above is true then change/rename/override the CSS selector. If changed/renamed update the elements that originally used .svg.

Body:
I have a webpage under development. Let's forget the contents. It is not relevant. It looks fine in Chrome, Safari and Firefox, but it does not extend to full width in Edge or Internet Explorer.

If I write in their consoles (with the help of jQuery)

$('body').width($(window).width())

the body extends to the full screen width and is ok again. I have been trying to debug the page via console, but have not managed to find the reason.

DOM of the page in the reference acts as a source.

This happens only when screen width is above 990 (due to the media queries I use).

Body:
The CSS selector .svg that is being applied to your html element is is telling it to be an inline element with display: inline-block;. If you remove the display property from .svg or change the value to block the page will fill the browser viewport appropriately.

The CSS selector in question.

.svg {
  display: inline-block; /* <= the problem */
  background: 0 0;
  border: none;
}

From what I can tell you're using Modernizr to do some feature detection and it added the .svg class to html and you create your own .svg for some other purpose not knowing that Modernizr added .svg to html.

If the above is true then change/rename/override the CSS selector. If changed/renamed update the elements that originally used .svg.


问:
How to simplify this regex to avoid recursion?
Regex:

```<code>(?|`(?>[^`\\]|\\.|``)*`|'(?>[^'\\]|\\.|'')*'|"(?>[^"\\]|\\.|"")*"|(\?{1,2})|(:{1,2})([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*))
</code>```

Example input:

```<code>INSERT INTO xyz WHERE
a=?
and b="what?"
and ??="cheese"
and `col?`='OK'
and ::col='another'
and last!=:least
</code>```

https://regex101.com/r/HnTVXx/6

It should match ?, ??, :xyz and ::xyz but not if they are inside of a backquoted-string, double-quoted string, or single-quoted string.

When I try running this in PHP with a very large input I get PREG_RECURSION_LIMIT_ERROR from preg_last_error().

How can I simplify this regex pattern so that it doesn't do so much recursion?

Here's some test code that shows the error in PHP using Niet's optimized regex: https://3v4l.org/GdtmP Error code 6 is PREG_JIT_STACKLIMIT_ERROR. The other one I've seen is 3=PREG_RECURSION_LIMIT_ERROR

答:
The general idea of "match this thing, but not in this condition" can be achieved with this pattern:

(don't match this(*SKIP)(*FAIL)|match this)
```

<p>In your case, you'd want something like...</p>

<pre class="lang-none prettyprint-override"><code>(
  (['"`]) # capture this quote character
  (?:\\.|(?!\1).)*+ # any escaped character, or
                    # any character that isn't the captured one
  \1      # the captured quote again
  (*SKIP)(*FAIL)   # ignore this
  |
  \?\??   # one or two question marks
  |
  ::?\w+  # word characters marked with one or two colons
)x
</code>```

https://regex101.com/r/HnTVXx/7

Body:
Regex:

(?|`(?>[^`\\]|\\.|``)*`|'(?>[^'\\]|\\.|'')*'|"(?>[^"\\]|\\.|"")*"|(\?{1,2})|(:{1,2})([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*))

Example input:

INSERT INTO xyz WHERE
a=?
and b="what?"
and ??="cheese"
and `col?`='OK'
and ::col='another'
and last!=:least

https://regex101.com/r/HnTVXx/6

It should match ?, ??, :xyz and ::xyz but not if they are inside of a backquoted-string, double-quoted string, or single-quoted string.

When I try running this in PHP with a very large input I get PREG_RECURSION_LIMIT_ERROR from preg_last_error().

How can I simplify this regex pattern so that it doesn't do so much recursion?

Here's some test code that shows the error in PHP using Niet's optimized regex: https://3v4l.org/GdtmP Error code 6 is PREG_JIT_STACKLIMIT_ERROR. The other one I've seen is 3=PREG_RECURSION_LIMIT_ERROR

Body:
The general idea of "match this thing, but not in this condition" can be achieved with this pattern:

(don't match this(*SKIP)(*FAIL)|match this)

In your case, you'd want something like...

(
  (['"`]) # capture this quote character
  (?:\\.|(?!\1).)*+ # any escaped character, or
                    # any character that isn't the captured one
  \1      # the captured quote again
  (*SKIP)(*FAIL)   # ignore this
  |
  \?\??   # one or two question marks
  |
  ::?\w+  # word characters marked with one or two colons
)x

https://regex101.com/r/HnTVXx/7


问:
ajax request on project 1 call project 2 symfony return Unexpected token <
I have 2 projects, let's call them backend and frontend. Backend is a Symfony3 project and Frontend is a simple html page with javascript in it.

I would like to call a peculiar url of the backend from the frontend so that it would return a string (a url).

So what I tried to do is a simple ajax get request with the backend url I would like to request but this returns

SyntaxError: Unexpected token "<"

(for html dataType) and

SyntaxError: Unexpected token.

(for json and jsonp dataType).

I tried with dataType json, jsonp, html adapting each time the controller response to answer respectively json, json, and html.

When I try this request from postman everything works just fine and i get either my json or html.

There is obviously something I don't understand.

Is there anybody that could explain me what I do wrong and how I could do it.

Below is my frontend project ajax request (for html in that case but I've let the commented json part I've jused for test in case of...)

```<code>$.ajax({
                url: 'http://sevignemiroir.local/display',
                type: 'GET',
                dataType:  "html",
                //dataType: "jsonp"
                success: function(response) {
                    console.log('success');
                    console.log(response);
                },
                error: function (response) {
                    console.log('error');
                    console.log(response);
                }
            })
</code>```

And this my response from my backend symfony controller

```<code>public function indexAction()
{
    //return $this->json('toto');
    return $this->render('display/test.html.twig', [
        'toto' => 'toto'
    ]);
}
</code>```

the test.html.twig file :

```<code><div>test</div>
</code>```

I am a bit confused :

Do I have to apply a specific format to the response to make it work?

Is there something I should configure in my controller to allow request from outside the project?

Does the problem come from a Cross-Domain issue?

I've heard about FOSRestBundle, is it mandatory to use such bundle to enable data send from outside the project?

What are the best practices for calling data from a project to another project?

These are the questions I'm getting confused with and if anyone would be kind enough to explain it, that would be greatly appreciated!

I don't know if that's important but I'm using MAMP and both project have virtualhosts configured

Many thanks to those that will take time to read this :)

答: It now works but... I don't know why. I was installing various bundle on symfony (FOSRest, NelmioCors, JMS) and tried a jquery cross-plugin plugins, nohing was working but when I removed  al of them, it now worked.. :/</p>

Body:
I have 2 projects, let's call them backend and frontend. Backend is a Symfony3 project and Frontend is a simple html page with javascript in it.

I would like to call a peculiar url of the backend from the frontend so that it would return a string (a url).

So what I tried to do is a simple ajax get request with the backend url I would like to request but this returns

SyntaxError: Unexpected token "<"

(for html dataType) and

SyntaxError: Unexpected token.

(for json and jsonp dataType).

I tried with dataType json, jsonp, html adapting each time the controller response to answer respectively json, json, and html.

When I try this request from postman everything works just fine and i get either my json or html.

There is obviously something I don't understand.

Is there anybody that could explain me what I do wrong and how I could do it.

Below is my frontend project ajax request (for html in that case but I've let the commented json part I've jused for test in case of...)

$.ajax({
                url: 'http://sevignemiroir.local/display',
                type: 'GET',
                dataType:  "html",
                //dataType: "jsonp"
                success: function(response) {
                    console.log('success');
                    console.log(response);
                },
                error: function (response) {
                    console.log('error');
                    console.log(response);
                }
            })

And this my response from my backend symfony controller

public function indexAction()
{
    //return $this->json('toto');
    return $this->render('display/test.html.twig', [
        'toto' => 'toto'
    ]);
}

the test.html.twig file :

test

I am a bit confused :

Do I have to apply a specific format to the response to make it work?

Is there something I should configure in my controller to allow request from outside the project?

Does the problem come from a Cross-Domain issue?

I've heard about FOSRestBundle, is it mandatory to use such bundle to enable data send from outside the project?

What are the best practices for calling data from a project to another project?

These are the questions I'm getting confused with and if anyone would be kind enough to explain it, that would be greatly appreciated!

I don't know if that's important but I'm using MAMP and both project have virtualhosts configured

Many thanks to those that will take time to read this :)


问:
Heroku always executes the dependancies check and slows down the push process
I am using the free version of heroku server. When ever i push to the heroku, I always get:

```<code>Gemfile detected, running Bundler version 1.0.0
</code>```

This happens even if I have not changed GemFile. Starting bundler on every push slows down the git push wasting effort. Any ideas on how to work around this are appreciated.

Thanks in advance !!!

答: There are no workaround. If you don't want that, don't use heroku or try to do a feature request to heroku.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am using the free version of heroku server. When ever i push to the heroku, I always get:

Gemfile detected, running Bundler version 1.0.0

This happens even if I have not changed GemFile. Starting bundler on every push slows down the git push wasting effort. Any ideas on how to work around this are appreciated.

Thanks in advance !!!


问:
JavaScript Nesting For Loops
I have the following code where I fail to understand some parts:

```<code>var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
 for (var j=0; j < arr[i].length; j++) {
  console.log(arr[i][j]);
  }
}
</code>```

What does arr[i] mean? I have been told that arr[i] itself is an array. How is that? And What is happening in the arr[i][j] part?

答:
i variable iterates over the arrays (nested arrays) inside the arr variable, so if it looks like e.g. arr[2], it returns the third array inside the arr (because the index starts with 0), which is - [5,6].

j stands for iterating over elements inside the nested arrays, so if it is like arr[2][1] - it returns 6, because 6 is the element inside the arr[2] array with 1 index.

Title: JavaScript Nesting For Loops

Body:
I have the following code where I fail to understand some parts:

var arr = [
[1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
 for (var j=0; j < arr[i].length; j++) {
  console.log(arr[i][j]);
  }
}

What does arr[i] mean? I have been told that arr[i] itself is an array. How is that? And What is happening in the arr[i][j] part?


问:
Uncaught SyntaxError: Unexpected token < on each js file that invoked in the index html
I am using mean stack to build a website, when testing, chrome returns the error like:

Uncaught SyntaxError: Unexpected token <   angular.js:1.

I don't know what's wrong and what should i do.

Here is the directory of my app:
E-study
  -client
   -app
   -components
    -all the libraries are here.
   -index.html
   -controllers.js
  -node_modules
  -server
   -config
    -server.js

And I run the server in E-study like :node server/config/server.js

The scripts in the index.html is

Just don't know why all the js files are changed to index.html when open in the browser.

答: In external js files, which you refer in some other files, don't use  tag.

Body: In external js files, which you refer in some other files, don't use <script>..</script> tag.


问:
Convert GET HTML response into document
I am developing a page that reads the source of another page and I need to extract certain information out of that page. I currently have the project snagging the live source with the data however I cannot for the life of me figure out how to convert this string into a document.

My rationale for using a document is that I need to use getElementById etc to get the value of these items.

What have I tried?

Assigning the HTML to an invisible div on my page. This kind of works though it doesn't render the entire HTML string and provides a "shorter" rendition of this page.

Manually finding the substrings. As you can imagine this is a crappy way to do things and provides very unreliable results.

DOM parser to convert the doc and then query it but that fails miserably.

Any assistance at all would be seriously appreciated.

pertinent code:

```<code>$.ajax({
  method: "GET",
  dataType: '',
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
  success: function(res) {
    //shows the entire source just fine.
    console.log("Value of RES: " + res);
    bootbox.hideAll();
    //shows a "truncated" copy of the source
    alert(res);
    $("#hiddendiv").html(x);
    var name = document.findElementById("myitem");
    alert(name);
  },
</code>```

答:
Another (probably better) option, is to use jQuery. jQuery allows you to create HTML, manipulate it, and query against it in memory. Querying DOM elements in jQuery is even easier than it is in pure javascript. See: http://jquery.com/.</p>

```<code>//Get a jQuery object representing your HTML
var $html = $( "<div><span id='label'></span></div>" );

//Query against it
var $label = $html.find( "#label" ); //finds the span with and id of 'label'
</code>```

Title: Convert GET HTML response into document

Body:
I am developing a page that reads the source of another page and I need to extract certain information out of that page. I currently have the project snagging the live source with the data however I cannot for the life of me figure out how to convert this string into a document.

My rationale for using a document is that I need to use getElementById etc to get the value of these items.

What have I tried?

Assigning the HTML to an invisible div on my page. This kind of works though it doesn't render the entire HTML string and provides a "shorter" rendition of this page.

Manually finding the substrings. As you can imagine this is a crappy way to do things and provides very unreliable results.

DOM parser to convert the doc and then query it but that fails miserably.

Any assistance at all would be seriously appreciated.

pertinent code:

$.ajax({
  method: "GET",
  dataType: '',
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
  success: function(res) {
    //shows the entire source just fine.
    console.log("Value of RES: " + res);
    bootbox.hideAll();
    //shows a "truncated" copy of the source
    alert(res);
    $("#hiddendiv").html(x);
    var name = document.findElementById("myitem");
    alert(name);
  },

Body:
Another (probably better) option, is to use jQuery. jQuery allows you to create HTML, manipulate it, and query against it in memory. Querying DOM elements in jQuery is even easier than it is in pure javascript. See: http://jquery.com/.

//Get a jQuery object representing your HTML
var $html = $( "<div><span id='label'></span></div>" );

//Query against it
var $label = $html.find( "#label" ); //finds the span with and id of 'label'


问:
I want to save text, numbers, and dates to a jdbc database error thrown "java.language.NumberFormatException: For input string: ""
```<code>private void btnAClientActionPerformed(java.awt.event.ActionEvent evt) {

    String s = new SimpleDateFormat("yyyy-MM-dd").format( 2017/03/26);

    try {
        String dateString = "2017-03-26";
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date myDate = formatter.parse(dateString); //changing date format

        String insert = "insert into Clients values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        //PrepareStatement to insert into database
        PreparedStatement ps = conn.prepareStatement(insert);
        ps.setInt(1, Integer.parseInt(textID.getText()));
        ps.setString(2, textFirstName.getText());
        ps.setString(3, textLastName.getText());
        ps.setInt(4, Integer.parseInt(textHmd.getText()));
        ps.setString(5, dateLpayment.getText());
        ps.setString(6, textPayment.getText());
        ps.setString(7, dateNpayment.getText());
        ps.setString(8, textSup.getText());
        ps.setInt(9, Integer.parseInt(textHmdpm.getText()));
        ps.setInt(10,Integer.parseInt(textWeight.getText()));
        ps.setInt(11,Integer.parseInt(textCweight.getText()));
        ps.setInt(12,Integer.parseInt(textBmi.getText()));
        ps.setInt(13,Integer.parseInt(textGbmi.getText()));
        ps.setInt(14,Integer.parseInt(textHeight.getText()));
        ps.setString(15,dateSD.getText());
        ps.setInt(16,Integer.parseInt(textGweight.getText()));
        ps.setString(17, dateBirth.getText());
        ps.setInt(18,Integer.parseInt(textBweight.getText()));

        //Trying to retrieve data from textfields and DateChooserCombo to
        //insert into jbdc database.
        ps.executeUpdate();

        JOptionPane.showMessageDialog(null, "Record Saved");
    }
    catch( HeadlessException | NumberFormatException | SQLException | ParseException e) {
        ///Trying to catch errors thrown especial the NumberFormatException.
        JOptionPane.showMessageDialog(null, e);
    }
}
</code>```

I am trying to save text, numbers, and dates to my database but I keep getting the same error no matter what I have tried. I have searched StackOverflow and the internet for the answer and again, nothing seems to work.

答:
You send a value as a parameter, which can't convert a number, to Integer.parseInt() method. The parameter of Integer.parseInt() must be able to convert to a number or else it throws NumberFormatException.

For Example:

```<code>ps.setInt(4, Integer.parseInt("1235"));
</code>```

this code will work.

```<code>ps.setInt(4, Integer.parseInt("abcd"));
</code>```

But this won't work. Because "abcd" cant convert a number.

Body:
private void btnAClientActionPerformed(java.awt.event.ActionEvent evt) {

    String s = new SimpleDateFormat("yyyy-MM-dd").format( 2017/03/26);

    try {
        String dateString = "2017-03-26";
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date myDate = formatter.parse(dateString); //changing date format

        String insert = "insert into Clients values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        //PrepareStatement to insert into database
        PreparedStatement ps = conn.prepareStatement(insert);
        ps.setInt(1, Integer.parseInt(textID.getText()));
        ps.setString(2, textFirstName.getText());
        ps.setString(3, textLastName.getText());
        ps.setInt(4, Integer.parseInt(textHmd.getText()));
        ps.setString(5, dateLpayment.getText());
        ps.setString(6, textPayment.getText());
        ps.setString(7, dateNpayment.getText());
        ps.setString(8, textSup.getText());
        ps.setInt(9, Integer.parseInt(textHmdpm.getText()));
        ps.setInt(10,Integer.parseInt(textWeight.getText()));
        ps.setInt(11,Integer.parseInt(textCweight.getText()));
        ps.setInt(12,Integer.parseInt(textBmi.getText()));
        ps.setInt(13,Integer.parseInt(textGbmi.getText()));
        ps.setInt(14,Integer.parseInt(textHeight.getText()));
        ps.setString(15,dateSD.getText());
        ps.setInt(16,Integer.parseInt(textGweight.getText()));
        ps.setString(17, dateBirth.getText());
        ps.setInt(18,Integer.parseInt(textBweight.getText()));

        //Trying to retrieve data from textfields and DateChooserCombo to
        //insert into jbdc database.
        ps.executeUpdate();

        JOptionPane.showMessageDialog(null, "Record Saved");
    }
    catch( HeadlessException | NumberFormatException | SQLException | ParseException e) {
        ///Trying to catch errors thrown especial the NumberFormatException.
        JOptionPane.showMessageDialog(null, e);
    }
}

I am trying to save text, numbers, and dates to my database but I keep getting the same error no matter what I have tried. I have searched StackOverflow and the internet for the answer and again, nothing seems to work.

Body:
You send a value as a parameter, which can't convert a number, to Integer.parseInt() method. The parameter of Integer.parseInt() must be able to convert to a number or else it throws NumberFormatException.

For Example:

ps.setInt(4, Integer.parseInt("1235"));

this code will work.

ps.setInt(4, Integer.parseInt("abcd"));

But this won't work. Because "abcd" cant convert a number.


问:
Double versus float
I have a constant for pi in my code:

const float PI = acos(-1);

Would it be better to declare it as a double?  An answer to another question on this site said floating point operations aren't exactly precise, and I'd like the constant to be accurate.

答:
For most applications, float would do just fine for PI.  Double is definitely has more precision, but it doesn't guarantee precision anymore than floats can.  By that I mean that the number 1.0 represented in binary is not a rational number.  Therefore, if you try to represent it, you'll only succeed to an nth digit where n is determined by how many bytes you use to represent that number.

Unfortunately to contain many digits of PI, you'd probably need to hold it in a string.  Though now we're talking about some impressive number crunching here that you might see in molecule simulations.  You're probably not going to need that level of precision.

Title: Double versus float


问:
How to use iOS 10.3 devices with Xcode 8.2.1
This iPad mini 2 (Model A1490) is running iOS 10.3 (14E277), which may not be supported by this version of Xcode.

my xcode version 8.2.1
my Device ios version 10.2

答:
In order to run your app on 10.3 device with Xcode 8.2.1 you'll need a new Developer Disk Image for 10.3.

You can follow this user's guide here that seems is working for me too. Use at your own risk.

Steps:

1.Download Zip file and extract.

2.Click on "Finder" in MAC OS

3.Click on "Go to Folder"

4.Paste
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport . Otherwise go to Applications > Right Click on Xcode > Show Package Contents and follow the directories above.

5.You'll notice that your versions ends at 10.2. So you need the new 10.3. Paste downloaded folder.

6.Reboot Device + Xcode + Mac


问:
how react programmatically focus input
I'm trying to implement a very simple use case, a UI feature, where:

There is a label with some content in it

If clicked, a text input replaces it with the content of label available

User can edit the content

When enter is pressed, the input hides and label is back with updated content

I could get finally all correct (in fact with a MongoBD backend, redux, etc.), and the only thing I couldn't ever do (paying a complete day in googling and reading S.O.F similar posts) was this:

When my text input appears, I can't transfer focus to it! First I tired this way:

```<code><div className={((this.state.toggleWordEdit) ? '' : 'hidden')}>
<input id={this.props.word._id} className="form-control"
        ref="updateTheWord"
        defaultValue={this.state.word}
        onChange={this.handleChange}
        onKeyPress={this.handleSubmit}
        autoFocus={this.state.toggleWordEdit}/></div>
    <div className={((this.state.toggleWordEdit) ? 'hidden' : '')}>
      <h3 onClick={this.updateWord}>
        {this.state.word}</h3>
    </div>
</code>```

but autoFocus sure didn't work (I "guess" because the form is rendered, but in hidden state, making autoFocus useless).

Next I tried in my this.updateWor, many of suggestions I found on google and S.O.F.:

```<code>this.refs.updateTheWord.focus();
</code>```

which together with similar suggestions all didn't work. Also I tried to fool React just to see if at all I can do something! I used real DOM:

```<code>    const x = document.getElementById(this.props.word._id);
    x.focus();
</code>```

and it didn't work either. One thing I even could not understand to put into word is a suggestion like this:
having ref as a method (I "guess")
I didn't even try it because I have multiples of these components and I need ref to further get value of, per component, and I couldn't imagine if my ref is not named, how I could get the value of!

So could you please give an idea, helping me to understand that in case I'm not using a Form (because I need a single input box replacing a label) how I could set its focus when it's CSS (Bootstrap) class is losing 'hidden' please?

答:
The way you have used refs is not the most preferred way or else its not the best practice anymore . try some thing like this

```<code>class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    this.textInput.current.focus();
  }

  render() {

    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Set Focus"
          onClick={this.focus}
        />
      </div>
    );
  }
}
</code>```

Update

From React 16.3 upwards you can use the React.createRef() API

```<code>class MyClass extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focus = this.focus.bind(this);
  }

  focus() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Set Focus"
          onClick={this.focus}
        />
      </div>
    );
  }
}
</code>```

From React 18.xx upwards you can use the useRef Hook

```<code>import React, { useRef } from "react";

export const Form = () => {
  const inputRef = useRef(null);

  const focus = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input type="text" ref={inputRef} />
      <input type="button" value="Set Focus" onClick={focus} />
    </div>
  );
};
</code>```

ContentLicense: CC BY-SA 4.0

Title: how react programmatically focus input

Body:
I'm trying to implement a very simple use case, a UI feature, where:

There is a label with some content in it

If clicked, a text input replaces it with the content of label available

User can edit the content

When enter is pressed, the input hides and label is back with updated content

I could get finally all correct (in fact with a MongoBD backend, redux, etc.), and the only thing I couldn't ever do (paying a complete day in googling and reading S.O.F similar posts) was this:

When my text input appears, I can't transfer focus to it! First I tired this way:

<input id={this.props.word._id} className="form-control"
        ref="updateTheWord"
        defaultValue={this.state.word}
        onChange={this.handleChange}
        onKeyPress={this.handleSubmit}
        autoFocus={this.state.toggleWordEdit}/>

        {this.state.word}

but autoFocus sure didn't work (I "guess" because the form is rendered, but in hidden state, making autoFocus useless).

Next I tried in my this.updateWor, many of suggestions I found on google and S.O.F.:

this.refs.updateTheWord.focus();

which together with similar suggestions all didn't work. Also I tried to fool React just to see if at all I can do something! I used real DOM:

    const x = document.getElementById(this.props.word._id);
    x.focus();

and it didn't work either. One thing I even could not understand to put into word is a suggestion like this:
having ref as a method (I "guess")
I didn't even try it because I have multiples of these components and I need ref to further get value of, per component, and I couldn't imagine if my ref is not named, how I could get the value of!

So could you please give an idea, helping me to understand that in case I'm not using a Form (because I need a single input box replacing a label) how I could set its focus when it's CSS (Bootstrap) class is losing 'hidden' please?

Body:
The way you have used refs is not the most preferred way or else its not the best practice anymore . try some thing like this

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    this.textInput.current.focus();
  }

  render() {

    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Set Focus"
          onClick={this.focus}
        />
      </div>
    );
  }
}

Update

From React 16.3 upwards you can use the React.createRef() API

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the textInput DOM element
    this.textInput = React.createRef();
    this.focus = this.focus.bind(this);
  }

  focus() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    this.textInput.current.focus();
  }

  render() {
    // tell React that we want to associate the <input> ref
    // with the `textInput` that we created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />
        <input
          type="button"
          value="Set Focus"
          onClick={this.focus}
        />
      </div>
    );
  }
}

From React 18.xx upwards you can use the useRef Hook

import React, { useRef } from "react";

export const Form = () => {
  const inputRef = useRef(null);

  const focus = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input type="text" ref={inputRef} />
      <input type="button" value="Set Focus" onClick={focus} />
    </div>
  );
};


问:
MariaDB server version for the right syntax to use near
I have a problem in ezSQL.

Code:

```<code>$dbo->query("INSERT INTO chart_logs (chart_id, uname, option_id) VALUES ('1', '1', '1'); INSERT INTO chart_logs (chart_id, uname, option_id) VALUES ('2', '2', '2'); ");
</code>```

Error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO chart_logs (chart_id, uname, option_id) VALUES ('2', '2', '2')' at line 1

But,

This Sql Query works phpmyadmin SQL Command successfully. I dont understand this. Why sql code doesnt work in ezsql query?

答:
ezSQL does not support running multiple statements in a single query. Each statement must be executed in a separate query.

Original answer:

Run just one SQL statement.

MariaDB supports multirow insert with VALUES clause...

```<code>  INSERT INTO chart_logs (chart_id, uname, option_id) VALUES
    ('1', '1', '1')
  , ('2', '2', '2')
</code>```

Body:
I have a problem in ezSQL.

Code:

$dbo->query("INSERT INTO chart_logs (chart_id, uname, option_id) VALUES ('1', '1', '1'); INSERT INTO chart_logs (chart_id, uname, option_id) VALUES ('2', '2', '2'); ");

Error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO chart_logs (chart_id, uname, option_id) VALUES ('2', '2', '2')' at line 1

But,

This Sql Query works phpmyadmin SQL Command successfully. I dont understand this. Why sql code doesnt work in ezsql query?

Body:
ezSQL does not support running multiple statements in a single query. Each statement must be executed in a separate query.

Original answer:

Run just one SQL statement.

MariaDB supports multirow insert with VALUES clause...

  INSERT INTO chart_logs (chart_id, uname, option_id) VALUES
    ('1', '1', '1')
  , ('2', '2', '2')


答:
```<code> var arr = [[1,2], [3,4], [5,6]];
//position   0       1       2
</code>```

//array[i]

array[0]-> return an array of [1,2]

//array[i][j]

array[0][0] ->return value of the first array in the first position -> 1

in your case you iterate for the length of the array, inside it you iterate for the length of the array[i], so in your console you must have the value from 1 to 6

Title: JavaScript Nesting For Loops

Body:
 var arr = [[1,2], [3,4], [5,6]];
//position   0       1       2

//array[i]

array[0]-> return an array of [1,2]

//array[i][j]

array[0][0] ->return value of the first array in the first position -> 1

in your case you iterate for the length of the array, inside it you iterate for the length of the array[i], so in your console you must have the value from 1 to 6


问:
Twitter typeahead not showing results where they start with the same word
I'm using twitter typeahead to provide a drop down of results being returned from a webservice . I'm finding that its only displaying a subset of these results; apparently its suppressing any one that starts with the same first word.

```<code>    var $termInput = $("#someId");
    var lookup = new Bloodhound({
        datumTokenizer:  Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
                url:/search/ + "%QUERY",
                wildcard: '%QUERY'
        }
    });

    lookup.initialize();

    $termInput.typeahead(
        { hint: true, highlight: true },
        {
            source: lookup,
            name: 'cases',
            displayKey: 'id',
            valueKey: 'id',
            templates: {
                empty: "<div class='omniboxresult nomatch'>No matching cases found</div>",
                suggestion: function(data) {
                    console.log(data);

                    return "<div class='omniboxresult'><div class='caseName'>" + "hi " +data.text + "</div></div>";
                }
            }
        }
    );
</code>```

Html is:

```<code><input type=text" class="form-control" id="someId" value="" data-provider="typeahead" autocomplete="off">
</code>```

Using the network tab I know that my webservice is returning (when I enter "Euro"):

```<code>[{"id":"1991003933","level":0,"text":"EUROPEAN COMMUNITY"},
{"id":"1971004125","level":0,"text":"EUROPEAN ECONOMIC COMMUNITY"},
{"id":"2011007673","level":0,"text":"EUROPEAN UNION"},
{"id":"2011000582","level":0,"text":"EUROPEAN UNION"}]
</code>```

But I only get the following in my output:

If I were to enter "e" I get more results, e.g. "English" which are not suppressed (but I still only get one result that starts with "EUROPEAN"

Why is this happening and how can I get it to display all results it receives?

答:
I was running into a similar problem in my project when I wanted to show autocomplete suggestions for names. I wanted to show autocomplete suggestions for first names, then first and last names. My implementation ends up looking like this:

Sar = Sara, Sarah, Saralou, Sarchenko, Sargent

Sarah[space] = Sarah, Sarah Majercik, Sarah Maddux, Sarah Zarek, Sarah Anderson

Not perfect, as I'd prefer once someone does a space Sarah is no longer shown, but I haven't figured that out yet. My solution was to prepend my data set with all the unique first and last names in alphabetical order. I was using the prefetch but I think remote also has the filter method available:

```<code>var lookup = new Bloodhound({
    datumTokenizer:  Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
            url:/search/ + "%QUERY",
            filter: function(list) {
                var uniques = [];
                // parse out unique names

                // my list was literally a list of first and last names so I concat them, you'll likely need to do a bit more work here
                return uniqes.concat(list);
            },
            wildcard: '%QUERY'
    }
});
</code>```

Using this your results will look like:

EURO = EUROPEAN, EUROPEAN COMMUNITY, EUROPEAN ECONOMIC COMMUNITY, EUROPEAN UNION

Hope this helps.

Body:
I'm using twitter typeahead to provide a drop down of results being returned from a webservice . I'm finding that its only displaying a subset of these results; apparently its suppressing any one that starts with the same first word.

    var $termInput = $("#someId");
    var lookup = new Bloodhound({
        datumTokenizer:  Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
                url:/search/ + "%QUERY",
                wildcard: '%QUERY'
        }
    });

    lookup.initialize();

    $termInput.typeahead(
        { hint: true, highlight: true },
        {
            source: lookup,
            name: 'cases',
            displayKey: 'id',
            valueKey: 'id',
            templates: {
                empty: "
No matching cases found
",
                suggestion: function(data) {
                    console.log(data);

                    return "

" + "hi " +data.text + "

";
                }
            }
        }
    );

Html is:

<input type=text" class="form-control" id="someId" value="" data-provider="typeahead" autocomplete="off">

Using the network tab I know that my webservice is returning (when I enter "Euro"):

[{"id":"1991003933","level":0,"text":"EUROPEAN COMMUNITY"},
{"id":"1971004125","level":0,"text":"EUROPEAN ECONOMIC COMMUNITY"},
{"id":"2011007673","level":0,"text":"EUROPEAN UNION"},
{"id":"2011000582","level":0,"text":"EUROPEAN UNION"}]

But I only get the following in my output:

If I were to enter "e" I get more results, e.g. "English" which are not suppressed (but I still only get one result that starts with "EUROPEAN"

Why is this happening and how can I get it to display all results it receives?

Body:
I was running into a similar problem in my project when I wanted to show autocomplete suggestions for names. I wanted to show autocomplete suggestions for first names, then first and last names. My implementation ends up looking like this:

Sar = Sara, Sarah, Saralou, Sarchenko, Sargent

Sarah[space] = Sarah, Sarah Majercik, Sarah Maddux, Sarah Zarek, Sarah Anderson

Not perfect, as I'd prefer once someone does a space Sarah is no longer shown, but I haven't figured that out yet. My solution was to prepend my data set with all the unique first and last names in alphabetical order. I was using the prefetch but I think remote also has the filter method available:

var lookup = new Bloodhound({
    datumTokenizer:  Bloodhound.tokenizers.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
            url:/search/ + "%QUERY",
            filter: function(list) {
                var uniques = [];
                // parse out unique names

                // my list was literally a list of first and last names so I concat them, you'll likely need to do a bit more work here
                return uniqes.concat(list);
            },
            wildcard: '%QUERY'
    }
});

Using this your results will look like:

EURO = EUROPEAN, EUROPEAN COMMUNITY, EUROPEAN ECONOMIC COMMUNITY, EUROPEAN UNION

Hope this helps.


问:
How to return a process id of a lengthy process started using Thread in python before the thread completes its execution
How can I return a process id of a lengthy process started using Thread in Python before the thread completes its execution?

I'm using Tkinter GUI so I can't start a lengthy process on the main thread so instead I start one on a separate thread.

The thread in turn calls subprocess.popen. This process should run for like 5 -6 hours.

But When I press stopbutton I need this process to stop but I am unable to return the process id of the process created using subprocess.popen.

Is there any solution to this?

答:
If you are using subprocess.Popen simply to spin off another process, there is no reason you need to do so from another thread. A sub-process created this way does not block your main thread. You can continue to do other things while the sub-process is running. You simply keep a reference to the Popen object returned.

The Popen object has all the facilities you need for monitoring / interacting with the sub-process. You can read and write to its standard input and output (via stdin and stdout members, if created with PIPE); you can monitor readability / writability of stdin and stdout (with select module); you can check whether the sub-process is still in existence with poll, reap its exit status with wait; you can stop it with terminate (or kill depending on how emphatic you wish to be).

There are certainly times when it might be advantageous to do this from another thread -- for example, if you need significant interaction with the sub-process and implementing that in the main thread would over-complicate your logic. In that case, it would be best to arrange a mechanism whereby you signal to your other "monitoring" thread that it's time to shutdown and allow the monitoring thread to execute terminate or kill on the sub-process.


答:
You could use zoo.  ?plot.zoo has several examples of how to create custom axis labels.

```<code>z <- zoo(d[,-1],as.Date(d[,1]))
plot(z)

# Example of custom axis labels
plot(z$Entry.Count, screen = 1, col = 1:2, xaxt = "n")
ix <- seq(1, length(time(z)), 3)
axis(1, at = time(z)[ix], labels = format(time(z)[ix],"%b-%d"), cex.axis = 0.7)
</code>```

Title: Plot with dates as X axis in R

Body:
I maintain my journal electronically and I'm trying to get an idea of how consistent I've been with my journal writing over the last few months. I have the following data file, which shows how many journal entries (Entry Count) and words (Word Count) I recorded over the preceding 30-day period.

Date    Entry Count Word Count
2010-08-25  22  4205
2010-08-26  21  4012
2010-08-27  20  3865
2010-08-28  20  4062
2010-08-29  19  3938
2010-08-30  18  3759
2010-08-31  17  3564
2010-09-01  17  3564
2010-09-02  16  3444
2010-09-03  17  3647
2010-09-04  17  3617
2010-09-05  16  3390
2010-09-06  15  3251
2010-09-07  15  3186
2010-09-08  15  3186
2010-09-09  16  3414
2010-09-10  15  3228
2010-09-11  14  3006
2010-09-12  13  2769
2010-09-13  13  2781
2010-09-14  12  2637
2010-09-15  13  2774
2010-09-16  13  2808
2010-09-17  12  2732
2010-09-18  12  2664
2010-09-19  13  2931
2010-09-20  13  2751
2010-09-21  13  2710
2010-09-22  14  2950
2010-09-23  14  2834
2010-09-24  14  2834
2010-09-25  14  2834
2010-09-26  14  2834
2010-09-27  14  2834
2010-09-28  14  2543
2010-09-29  14  2543
2010-09-30  15  2884
2010-10-01  16  3105
2010-10-02  16  3105
2010-10-03  16  3105
2010-10-04  15  2902
2010-10-05  14  2805
2010-10-06  14  2805
2010-10-07  14  2805
2010-10-08  14  2812
2010-10-09  15  2895
2010-10-10  14  2667
2010-10-11  15  2876
2010-10-12  16  2938
2010-10-13  17  3112
2010-10-14  16  2894
2010-10-15  16  2894
2010-10-16  16  2923
2010-10-17  15  2722
2010-10-18  15  2722
2010-10-19  14  2544
2010-10-20  13  2277
2010-10-21  13  2329
2010-10-22  12  2132
2010-10-23  11  1892
2010-10-24  10  1764
2010-10-25  10  1764
2010-10-26  10  1764
2010-10-27  10  1764
2010-10-28  10  1764
2010-10-29  9   1670
2010-10-30  10  1969
2010-10-31  10  1709
2010-11-01  10  1624
2010-11-02  11  1677
2010-11-03  11  1677
2010-11-04  11  1677
2010-11-05  11  1677
2010-11-06  12  1786
2010-11-07  12  1786
2010-11-08  11  1529
2010-11-09  10  1446
2010-11-10  11  1682
2010-11-11  11  1540
2010-11-12  11  1673
2010-11-13  11  1765
2010-11-14  12  1924
2010-11-15  13  2276
2010-11-16  12  2110
2010-11-17  13  2524
2010-11-18  14  2615
2010-11-19  14  2615
2010-11-20  15  2706
2010-11-21  14  2549
2010-11-22  15  2647
2010-11-23  16  2874
2010-11-24  16  2874
2010-11-25  16  2874
2010-11-26  17  3249
2010-11-27  18  3421
2010-11-28  18  3421
2010-11-29  19  3647

I'm trying to plot this data with R to get a graphical representation of my journal-writing consistency. I load it into R with the following command.

d <- read.table("journal.txt", header=T, sep="\t")

I can then graph the data with the following command.

plot(seq(from=1, to=length(d$Entry.Count), by=1), d$Entry.Count, type="o", ylim=c(0, max(d$Entry.Count)))

However, in this plot the X axis is just a number, not a date. I tried adjusting the command to show dates on the X axis like this.

plot(d$Date, d$Entry.Count, type="o", ylim=c(0, max(d$Entry.Count)))

However, not only does the plot look strange, but the labels on the X axis are not very helpful. What is the best way to plot this data so that I can clearly associate dates with points on the plotted curve?

Body:
You could use zoo.  ?plot.zoo has several examples of how to create custom axis labels.

z <- zoo(d[,-1],as.Date(d[,1]))
plot(z)

# Example of custom axis labels
plot(z$Entry.Count, screen = 1, col = 1:2, xaxt = "n")
ix <- seq(1, length(time(z)), 3)
axis(1, at = time(z)[ix], labels = format(time(z)[ix],"%b-%d"), cex.axis = 0.7)


问:
URL automatically routing to default port
I am new to WebSphere. I have deployed one application on the WebSphere but when I call the application URL, it automatically adds ":9443" (default HHTPs port) in the server name and tries to call URL but due to that application doesn't work.
If removed the port number then application starts working.
Any suggestions, how I can fix it from WAS UI?

Thanks
Nikhil

答:
For WebSphere Liberty, the IBM Knowledge Center covers this. In the server.xml, you will need to create a <httpEndpoint> element to open up a port and a <virtualHost> element specifying a <hostAlias>.

In either the <webApplication> element in your server.xml, or in your ibm-web-bnd.xml inside the application WAR, you will need to add a <web-bnd> element specifying the earlier virtualHost's name.

Example snippet inside server.xml

```<code>    <httpEndpoint id="appEndpoint" host="*" httpPort="3332" httpsPort="3333"/>
    <virtualHost id="someHost">
        <hostAlias>localhost:3333</hostAlias>
    </virtualHost>

    <webApplication name="app" location="{path.to.app.war}">
        <web-bnd>
            <virtual-host name="someHost" />
        </web-bnd>
    </webApplication>
</code>```

Body:
For WebSphere Liberty, the IBM Knowledge Center covers this. In the server.xml, you will need to create a <httpEndpoint> element to open up a port and a <virtualHost> element specifying a <hostAlias>.

In either the <webApplication> element in your server.xml, or in your ibm-web-bnd.xml inside the application WAR, you will need to add a <web-bnd> element specifying the earlier virtualHost's name.

Example snippet inside server.xml

    <httpEndpoint id="appEndpoint" host="*" httpPort="3332" httpsPort="3333"/>
    <virtualHost id="someHost">
        <hostAlias>localhost:3333</hostAlias>
    </virtualHost>

    <webApplication name="app" location="{path.to.app.war}">
        <web-bnd>
            <virtual-host name="someHost" />
        </web-bnd>
    </webApplication>


问:
Tensorflow: How to index a tensor using 2D-index like in numpy
I would like to do the following numpy code in Tensorflow:

```<code>input = np.array([[1,2,3]
                  [4,5,6]
                  [7,8,9]])
index1 = [0,1,2]
index2 = [2,2,0]
output = input[index1, index2]
>> output
[3,6,7]
</code>```

given an input such as:

```<code>input = tf.constant([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])
</code>```

I have tried the following, but seems like an overshooting:

```<code>index3 = tf.range(0, input.get_shape()[0])*input.get_shape()[1] + index2
output = tf.gather(tf.reshape(input, [-1]), index3)
sess = tf.Session()
sess.run(output)
>> [3,6,7]
</code>```

This works only because my first index is conveniently [0,1,2] but wouldn't be doable for [0,0,2] for example (besides looking really long and ugly).

Would you have any easier syntax, something more tensoric/pythonic?

答:
You can do it using tf.gather_nd(tf.gather_nd official doc) as follows:

```<code>import tensorflow as tf
inp = tf.constant([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])
res=tf.gather_nd(inp,list(zip([0,1,2],[2,2,0])))
sess = tf.Session()
sess.run(res)
</code>```

The result is array([3, 6, 7])

Body:
I would like to do the following numpy code in Tensorflow:

input = np.array([[1,2,3]
                  [4,5,6]
                  [7,8,9]])
index1 = [0,1,2]
index2 = [2,2,0]
output = input[index1, index2]
>> output
[3,6,7]

given an input such as:

input = tf.constant([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])

I have tried the following, but seems like an overshooting:

index3 = tf.range(0, input.get_shape()[0])*input.get_shape()[1] + index2
output = tf.gather(tf.reshape(input, [-1]), index3)
sess = tf.Session()
sess.run(output)
>> [3,6,7]

This works only because my first index is conveniently [0,1,2] but wouldn't be doable for [0,0,2] for example (besides looking really long and ugly).

Would you have any easier syntax, something more tensoric/pythonic?

Body:
You can do it using tf.gather_nd(tf.gather_nd official doc) as follows:

import tensorflow as tf
inp = tf.constant([[1, 2, 3],
                   [4, 5, 6],
                   [7, 8, 9]])
res=tf.gather_nd(inp,list(zip([0,1,2],[2,2,0])))
sess = tf.Session()
sess.run(res)

The result is array([3, 6, 7])


问:
I am getting error while finetuning fcn-alexnet for my single-channel dataset
I am running fcn-alexnet for semantic segmentation, I downloaded the pretrained model. Since my data is single channel,it is showing an error:

```<code> ERROR: Cannot copy param 0 weights from layer 'conv1'; shape mismatch. Source param shape is 96 3 11 11 (34848); target param shape is 96 1 11 11 (11616). To learn this layer's parameters from scratch rather than copying from a saved net, rename the layer.
</code>```

Could someone please guide me?
The shape is as follows:

```<code>Feature shape (1, 256, 256)
Label shape (1, 256, 256)
</code>```

答:
If you only needed to retrain the last layer, you could just rename it (see this answer: https://stackoverflow.com/a/39837047/2404152).

In your case, the problem is that 96x3x11x11 != 96x1x11x11. You're trying to apply a pretrained model that was intended for color images to a grayscale dataset (as you already discovered). The simplest fix is to just train on color images as well. One way to do this would be to add a Tile layer to copy the input three times.

Obviously, that wouldn't be very efficient. But that's the only way I can think of to use the pretrained model on grayscale data.

Body:
I am running fcn-alexnet for semantic segmentation, I downloaded the pretrained model. Since my data is single channel,it is showing an error:

 ERROR: Cannot copy param 0 weights from layer 'conv1'; shape mismatch. Source param shape is 96 3 11 11 (34848); target param shape is 96 1 11 11 (11616). To learn this layer's parameters from scratch rather than copying from a saved net, rename the layer.

Could someone please guide me?
The shape is as follows:

Feature shape (1, 256, 256)
Label shape (1, 256, 256)


答:
How about using tf.gather_nd?</p>

```<code>In [61]: input = tf.constant([[1, 2, 3],
    ...:                      [4, 5, 6],
    ...:                      [7, 8, 9]])

In [63]: row_idx = tf.constant([0, 1, 2])
In [64]: col_idx = tf.constant([2, 2, 0])
In [65]: coords = tf.transpose(tf.pack([row_idx, col_idx]))

In [67]: sess = tf.InteractiveSession()

In [68]: tf.gather_nd(input, coords).eval()
Out[68]: array([3, 6, 7], dtype=int32)
</code>```

Title: Tensorflow: How to index a tensor using 2D-index like in numpy

Body:
How about using tf.gather_nd?

In [61]: input = tf.constant([[1, 2, 3],
    ...:                      [4, 5, 6],
    ...:                      [7, 8, 9]])

In [63]: row_idx = tf.constant([0, 1, 2])
In [64]: col_idx = tf.constant([2, 2, 0])
In [65]: coords = tf.transpose(tf.pack([row_idx, col_idx]))

In [67]: sess = tf.InteractiveSession()

In [68]: tf.gather_nd(input, coords).eval()
Out[68]: array([3, 6, 7], dtype=int32)


问:
How to compare 2 objects that are created in different subclasses
I looked everywhere and haven't seen anything like this. I'm fairly new to java and have a homework assignment. The assignment is a Library. It has Books and dvd's, new and used. Im tying to compare an object to determine the correct fine.

Im basically asking the program, hey, is this a book or a dvd? and then hey, is this a new book or dvd, or is this an older one.

```<code>public double isLate(LocalDate argDateCheckedOut, LIBRARYMATERIALS argMaterial)
{
    LocalDate dateCheckedIn =  LocalDate.now();
    double diff=ChronoUnit.DAYS.between(argDateCheckedOut, dateCheckedIn);

    double fine = 0;

    if(argMaterial.equals(BOOK))
    {
        //calculate fine for book
        if(argMaterial.getisNew() == true)
        {
            if(diff > 21)
            {
                fine = 1 + .25*diff;
            }

        }
        else if(argMaterial.getisNew() == false)
        {
            if(diff > 28)
            {
                fine = .25 * diff;
            }
        }
    }

    else if(argMaterial.equals(DVD))
    {
        //calculate fine for dvd
        if(argMaterial.getisNew() == true)
        {
            if(diff > 3)
            {
                fine = 5 + diff;
            }

        }
        else if(argMaterial.getisNew() == false)
        {
            if(diff > 7)
            {
                fine = diff;
            }
        }

    }
    return fine;
}
</code>```

答:
I found an easy fix after talking to my professor over email. I'm sure your answer would've worked but I was looking for more of a... simpler fix.

Here it is. We used the instanceof to compare the objects, fines work accordingly.

```<code>double fine = 0;

if(argMaterial instanceof BOOK)
{
    //calculate fine for book
    if(argIsNew == true)
    {
        if(diff > 21)
        {
            fine = 1 + .25*diff;
        }

    }
    else if(argIsNew == false)
    {
        if(diff > 28)
        {
            fine = .25 * diff;
        }
    }
}

else if(argMaterial instanceof DVD)
{
    //calculate fine for dvd
    if(argIsNew == true)
    {
        if(diff > 3)
        {
            fine = 5 + diff;
        }

    }
    else if(argIsNew == false)
    {
        if(diff > 7)
        {
            fine = diff;
        }
    }

}
    return fine;
</code>```

Body:
I looked everywhere and haven't seen anything like this. I'm fairly new to java and have a homework assignment. The assignment is a Library. It has Books and dvd's, new and used. Im tying to compare an object to determine the correct fine.

Im basically asking the program, hey, is this a book or a dvd? and then hey, is this a new book or dvd, or is this an older one.

public double isLate(LocalDate argDateCheckedOut, LIBRARYMATERIALS argMaterial)
{
    LocalDate dateCheckedIn =  LocalDate.now();
    double diff=ChronoUnit.DAYS.between(argDateCheckedOut, dateCheckedIn);

    double fine = 0;

    if(argMaterial.equals(BOOK))
    {
        //calculate fine for book
        if(argMaterial.getisNew() == true)
        {
            if(diff > 21)
            {
                fine = 1 + .25*diff;
            }

        }
        else if(argMaterial.getisNew() == false)
        {
            if(diff > 28)
            {
                fine = .25 * diff;
            }
        }
    }

    else if(argMaterial.equals(DVD))
    {
        //calculate fine for dvd
        if(argMaterial.getisNew() == true)
        {
            if(diff > 3)
            {
                fine = 5 + diff;
            }

        }
        else if(argMaterial.getisNew() == false)
        {
            if(diff > 7)
            {
                fine = diff;
            }
        }

    }
    return fine;
}

Body:
I found an easy fix after talking to my professor over email. I'm sure your answer would've worked but I was looking for more of a... simpler fix.

Here it is. We used the instanceof to compare the objects, fines work accordingly.

double fine = 0;

if(argMaterial instanceof BOOK)
{
    //calculate fine for book
    if(argIsNew == true)
    {
        if(diff > 21)
        {
            fine = 1 + .25*diff;
        }

    }
    else if(argIsNew == false)
    {
        if(diff > 28)
        {
            fine = .25 * diff;
        }
    }
}

else if(argMaterial instanceof DVD)
{
    //calculate fine for dvd
    if(argIsNew == true)
    {
        if(diff > 3)
        {
            fine = 5 + diff;
        }

    }
    else if(argIsNew == false)
    {
        if(diff > 7)
        {
            fine = diff;
        }
    }

}
    return fine;


问:
Interrogation about jpa/hibernate subselect fetching
I have an interrogation about a code snippet (full source code) which is the accompanying code sample of a book about Hibernate/JPA.

Here  is the code listing:

```<code>public class Subselect extends JPATest {

    @Override
    public void configurePersistenceUnit() throws Exception {
        configurePersistenceUnit("FetchingSubselectPU");
    }

    public FetchTestData storeTestData() throws Exception {
        UserTransaction tx = TM.getUserTransaction();
        tx.begin();
        EntityManager em = JPA.createEntityManager();

        Long[] itemIds = new Long[3];
        Long[] userIds = new Long[3];

        User johndoe = new User("johndoe");
        em.persist(johndoe);
        userIds[0] = johndoe.getId();

        User janeroe = new User("janeroe");
        em.persist(janeroe);
        userIds[1] = janeroe.getId();

        User robertdoe = new User("robertdoe");
        em.persist(robertdoe);
        userIds[2] = robertdoe.getId();

        Item item = new Item("Item One", CalendarUtil.TOMORROW.getTime(), johndoe);
        em.persist(item);
        itemIds[0] = item.getId();
        for (int i = 1; i <= 3; i++) {
            Bid bid = new Bid(item, robertdoe, new BigDecimal(9 + i));
            item.getBids().add(bid);
            em.persist(bid);
        }

        item = new Item("Item Two", CalendarUtil.TOMORROW.getTime(), johndoe);
        em.persist(item);
        itemIds[1] = item.getId();
        for (int i = 1; i <= 1; i++) {
            Bid bid = new Bid(item, janeroe, new BigDecimal(2 + i));
            item.getBids().add(bid);
            em.persist(bid);
        }

        item = new Item("Item Three", CalendarUtil.AFTER_TOMORROW.getTime(), janeroe);
        em.persist(item);
        itemIds[2] = item.getId();
        for (int i = 1; i <= 1; i++) {
            Bid bid = new Bid(item, johndoe, new BigDecimal(3 + i));
            item.getBids().add(bid);
            em.persist(bid);
        }

        tx.commit();
        em.close();

        FetchTestData testData = new FetchTestData();
        testData.items = new TestData(itemIds);
        testData.users = new TestData(userIds);
        return testData;
    }

    @Test
    public void fetchCollectionSubselect() throws Exception {
        storeTestData();

        UserTransaction tx = TM.getUserTransaction();
        try {
            tx.begin();
            EntityManager em = JPA.createEntityManager();

            List<Item> items = em.createQuery("select i from Item i").getResultList();
            // select * from ITEM

            for (Item item : items) {
                assertTrue(item.getBids().size() > 0);
                // select * from BID where ITEM_ID in (
                //  select ID from ITEM
                // )
            }

            // The actual test
            em.clear();
            items = em.createQuery("select i from Item i").getResultList();
            // Access should load all collections
            assertTrue(items.iterator().next().getBids().size() > 0);
            em.clear(); // Detach all
            for (Item item : items) {
                assertTrue(item.getBids().size() > 0);
            }

            tx.commit();
            em.close();
        } finally {
            TM.rollback();
        }
    }

}
</code>```

The specific part I don't understand is this one:

```<code>for (Item item : items) {
    assertTrue(item.getBids().size() > 0);
    // select * from BID where ITEM_ID in (
    //  select ID from ITEM
    // )
}
</code>```

It is meant to demonstrate the use of prefetching with subselects feature of hibernate and the SQL query that is going to be executed.

The following comment:  // select ID from ITEM indicates that all items IDs are retrieved from DB. Is this what subselect prefetching is meant to work? Why retrieve all IDs from the ITEM table?

Here is the Item entity:

```<code>@Entity
public class Item {
 @OneToMany(mappedBy = "item")
 @org.hibernate.annotations.Fetch(
 org.hibernate.annotations.FetchMode.SUBSELECT
 )
 protected Set<Bid> bids = new HashSet<>();
 // ...
}
</code>```

答:
Subselect prefetching means that the original query used to load parents is used as a subquery when loading associated children, so that children in all loaded parents are initialized in one go. Your query to load parents is select i from Item i (you load all items), hence it is used as a subquery for bids (transformed to projecting only id of items).

If your original query were select i from Item i where i.someProperty = :something, the subquery when loading bids would be select ID from ITEM where SOME_PROPERTY_COLUMN = :something.

Body:
I have an interrogation about a code snippet (full source code) which is the accompanying code sample of a book about Hibernate/JPA.

Here  is the code listing:

public class Subselect extends JPATest {

    @Override
    public void configurePersistenceUnit() throws Exception {
        configurePersistenceUnit("FetchingSubselectPU");
    }

    public FetchTestData storeTestData() throws Exception {
        UserTransaction tx = TM.getUserTransaction();
        tx.begin();
        EntityManager em = JPA.createEntityManager();

        Long[] itemIds = new Long[3];
        Long[] userIds = new Long[3];

        User johndoe = new User("johndoe");
        em.persist(johndoe);
        userIds[0] = johndoe.getId();

        User janeroe = new User("janeroe");
        em.persist(janeroe);
        userIds[1] = janeroe.getId();

        User robertdoe = new User("robertdoe");
        em.persist(robertdoe);
        userIds[2] = robertdoe.getId();

        Item item = new Item("Item One", CalendarUtil.TOMORROW.getTime(), johndoe);
        em.persist(item);
        itemIds[0] = item.getId();
        for (int i = 1; i <= 3; i++) {
            Bid bid = new Bid(item, robertdoe, new BigDecimal(9 + i));
            item.getBids().add(bid);
            em.persist(bid);
        }

        item = new Item("Item Two", CalendarUtil.TOMORROW.getTime(), johndoe);
        em.persist(item);
        itemIds[1] = item.getId();
        for (int i = 1; i <= 1; i++) {
            Bid bid = new Bid(item, janeroe, new BigDecimal(2 + i));
            item.getBids().add(bid);
            em.persist(bid);
        }

        item = new Item("Item Three", CalendarUtil.AFTER_TOMORROW.getTime(), janeroe);
        em.persist(item);
        itemIds[2] = item.getId();
        for (int i = 1; i <= 1; i++) {
            Bid bid = new Bid(item, johndoe, new BigDecimal(3 + i));
            item.getBids().add(bid);
            em.persist(bid);
        }

        tx.commit();
        em.close();

        FetchTestData testData = new FetchTestData();
        testData.items = new TestData(itemIds);
        testData.users = new TestData(userIds);
        return testData;
    }

    @Test
    public void fetchCollectionSubselect() throws Exception {
        storeTestData();

        UserTransaction tx = TM.getUserTransaction();
        try {
            tx.begin();
            EntityManager em = JPA.createEntityManager();

            List<Item> items = em.createQuery("select i from Item i").getResultList();
            // select * from ITEM

            for (Item item : items) {
                assertTrue(item.getBids().size() > 0);
                // select * from BID where ITEM_ID in (
                //  select ID from ITEM
                // )
            }

            // The actual test
            em.clear();
            items = em.createQuery("select i from Item i").getResultList();
            // Access should load all collections
            assertTrue(items.iterator().next().getBids().size() > 0);
            em.clear(); // Detach all
            for (Item item : items) {
                assertTrue(item.getBids().size() > 0);
            }

            tx.commit();
            em.close();
        } finally {
            TM.rollback();
        }
    }

}

The specific part I don't understand is this one:

for (Item item : items) {
    assertTrue(item.getBids().size() > 0);
    // select * from BID where ITEM_ID in (
    //  select ID from ITEM
    // )
}

It is meant to demonstrate the use of prefetching with subselects feature of hibernate and the SQL query that is going to be executed.

The following comment:  // select ID from ITEM indicates that all items IDs are retrieved from DB. Is this what subselect prefetching is meant to work? Why retrieve all IDs from the ITEM table?

Here is the Item entity:

@Entity
public class Item {
 @OneToMany(mappedBy = "item")
 @org.hibernate.annotations.Fetch(
 org.hibernate.annotations.FetchMode.SUBSELECT
 )
 protected Set<Bid> bids = new HashSet<>();
 // ...
}


问:
Google Maps API '.pac-item:first' returns with bad formatting
I am working with grabbing the first item from the possible options on the pac list.  I am finding that the value is always improperly formatted.

For example when I click the down down I get this:

```<code>"Miami, FL, United States"
</code>```

When I grab it in code I get this:(i.e listen for enter key then select top option)

```<code>"MiamiFL, United States"
</code>```

I would like to keep the same format for easy user readability.

Here is the code I have tried, both options result in the same bad formatting.

```<code>//attempt one
var firstResult = $('.pac-item:first').text();

//attempt two
var firstResult = $('.pac-container .pac-item:first').text();
</code>```

答:
I have the same issue, which I sorted out using this fragment of code, I hope it helps you!</p>

```<code>    var itemFull = $(".pac-container .pac-item:first").text();
    var itemQuery = $(".pac-container .pac-item:first .pac-item-query").text();
    var firstResult = itemQuery + ' ' + itemFull.substring(itemQuery.length);
</code>```

Body:
I am working with grabbing the first item from the possible options on the pac list.  I am finding that the value is always improperly formatted.

For example when I click the down down I get this:

"Miami, FL, United States"

When I grab it in code I get this:(i.e listen for enter key then select top option)

"MiamiFL, United States"

I would like to keep the same format for easy user readability.

Here is the code I have tried, both options result in the same bad formatting.

//attempt one
var firstResult = $('.pac-item:first').text();

//attempt two
var firstResult = $('.pac-container .pac-item:first').text();

Body:
I have the same issue, which I sorted out using this fragment of code, I hope it helps you!

    var itemFull = $(".pac-container .pac-item:first").text();
    var itemQuery = $(".pac-container .pac-item:first .pac-item-query").text();
    var firstResult = itemQuery + ' ' + itemFull.substring(itemQuery.length);


问:
Windows and Token Auth for same WEB API
Ok, I have this scenario.

I have one WEB API which  will provide functionality to an intranet application, the idea is this application WILL not be visible to the outside world, so it wont have a login page.

However, the web api will also be consumed by mobile apps outside the organization, so the webapi WILL be exposed via a public url.

How can I make the authentication/authorization here to support both scenarios?
1. Internal users will be able to consume the web api via the angular backend app without an explicit login page.
2. External users via the mobile app will consume the web api with their active directory account.

I found this:
https://stormpath.com/blog/token-authentication-asp-net-core

where I could easily replace the GetIdentity Method to go to Active Directory and check if user exists with that user and password, but on the intranet, I wont have that info.

ideas please?

答:
The best way to handle such a scenario is to use HMAC Authentication as discussed here. This will allow easier access to the piblic endpoint without requirering some kind of a login from the mobile clients, while at the same time enabling you to know which mobile is acceessing your endpoint. This is the same workflow as implemented in External Auth services like login with google and facebook where you are given an apikey and a apisecret

YOU CAN FIND THE SOURCE CODE OF THE EXAMPLE USING ASP.NET HERE

Title: Windows and Token Auth for same WEB API


问:
Why was function overloading added to C++?
I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?

What went across the mind of the language designer at that time?

答: Using polymorphism , we can design a family of functions with same function name but with different argument list . The function would perform different operations depending on the arguments list in the function call. </p>


问:
Where to put oozie.launcher.* configuration?
While trying to use Oozie properly, I ended up setting a few parameters, namely:

oozie.launcher.mapreduce.map.memory.mb

oozie.launcher.mapreduce.map.java.opts

oozie.launcher.yarn.app.mapreduce.am.resource.mb

oozie.launcher.mapred.job..queue.name

If I set them in the worfklow configuration, they work as expected.

Is there a way/a place to set them globally, ie. not per workflow? I was expecting that custom-oozie-site.xml would be the right place but apparently not (they have no effect if put there). Is the workflow itself the only place where they can be configured?

If it is relevant, I am using hdp 2.5.

答:
In the Oozie Parameterization of Workflows section of the documentation, they state

Workflow applications may define default values for the workflow job parameters. They must be defined in a config-default.xml file bundled with the workflow application archive... Workflow job properties have precedence over the default values.

Another option I've seen done is defining a parent workflow definition and propagating to child workflows. Granted, this only works in specific instances and isn't always a good idea.

In addition the documentation notes in the Workflow Deployment section

The config-default.xml file defines, if any, default values for the workflow job parameters. This file must be in the Hadoop Configuration XML format. EL expressions are not supported and user.name property cannot be specified in this file. Any other resources like job.xml files referenced from a workflow action action node must be included under the corresponding path, relative paths always start from the root of the workflow application.

This is a problem my team is currently trying to fix across 12 different ETL loads.


问:
Laravel back button
I am trying to create a simple back button on a page. The user can arrive to this page from two different pages so I would like to know from which page he arrived. Is that possible?</p>

答:
Indeed using {{ URL:previous() }} do work, but if you're using a same named route to display multiple views, it will take you back to the first endpoint of this route.

In my case, I have a named route, which based on a parameter selected by the user, can render 3 different views. Of course, I have a default case for the first enter in this route, when the user doesn't selected any option yet.

When I use URL:previous(), Laravel take me back to the default view, even if the user has selected some other option. Only using javascript inside the button I accomplished to be returned to the correct view:

```<code><a href="javascript:history.back()" class="btn btn-default">Voltar</a>
</code>```

I'm tested this on Laravel 5.3, just for clarification.

Title: Laravel back button

Body:
Indeed using {{ URL:previous() }} do work, but if you're using a same named route to display multiple views, it will take you back to the first endpoint of this route.

In my case, I have a named route, which based on a parameter selected by the user, can render 3 different views. Of course, I have a default case for the first enter in this route, when the user doesn't selected any option yet.

When I use URL:previous(), Laravel take me back to the default view, even if the user has selected some other option. Only using javascript inside the button I accomplished to be returned to the correct view:

<a href="javascript:history.back()" class="btn btn-default">Voltar</a>

I'm tested this on Laravel 5.3, just for clarification.