问:
Mouse events on each <g> tag of svg loaded on the material in threejs
I am loading SVG images on to the mesh basic material of BoxBufferGeometry(cube) using SVGLoader. I want to trigger mouse events when user hovers/clicks on specific element of SVG which is loaded on the specific side of the cube.

I tried adding events into the .svg file before loading it but once it get loaded on the material it doesn\'t show any changes caused by the events.

Is there any other possible way to select the elements of loaded svg image and apply events on it?

For better understanding please refer http://plnkr.co/edit/YYN8aechHGTKXvPv6tOo?p=preview apart from this also tried to access the particular side using following code:

```<code>                raycaster.setFromCamera( mouse, camera );

                var intersects = raycaster.intersectObjects( scene.children );
                if ( intersects.length > 0 ) {
                    var index = Math.floor( intersects[0].faceIndex / 2 );
                    if ( INTERSECTED != intersects[ 0 ].object && (index == 4 || index == 5)) {
                        if ( INTERSECTED ) {
                            INTERSECTED.material[intersects[0].faceIndex].color.setHex( INTERSECTED.currentHex );
                        }

                        INTERSECTED = intersects[ 0 ].object;
                        INTERSECTED.currentHex = INTERSECTED.material[4].color.getHex();
                        INTERSECTED.material[index].color.setHex( 0xCACACA );
                        f = index;
                }
</code>```

答:
I have used threex.domevent.js to capture the mouseover event and created a plunker. I am finding the cube face which has the svg image.
Links:
detect mouse click / hover event on sides of cube in three js and
https://github.com/jeromeetienne/threex.domevents.

Attach the dom event using *threex.domevent.js**

domEvents  = new THREEx.DomEvents(camera, renderer.domElement)

Listen to mouse over event and find the face you require.

```<code>        domEvents.addEventListener(mesh, 'mouseover', function(event) {
        var vector = new THREE.Vector3(
            (event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, );
        vector.unproject(camera);
        raycaster.set(camera.position, vector.sub(camera.position).normalize());

        var intersects = raycaster.intersectObject(mesh);
        if (intersects.length > 0) {
            var index = Math.floor(intersects[0].faceIndex / 2);
            if (index === 4) {
                //index 4 is  cude face having the svg image,
                //you can load a new svg or do required things here
                console.log('##############');
                mesh.material[4].map = new THREE.TextureLoader().load('sample2.svg');
            }

        }
    }, false)
</code>```

Plunker: http://plnkr.co/edit/QXwqN3X70ex3EZmlKhRf?p=preview
Hope it helps.

Body:
I am loading SVG images on to the mesh basic material of BoxBufferGeometry(cube) using SVGLoader. I want to trigger mouse events when user hovers/clicks on specific element of SVG which is loaded on the specific side of the cube.

I tried adding events into the .svg file before loading it but once it get loaded on the material it doesn\'t show any changes caused by the events.

Is there any other possible way to select the elements of loaded svg image and apply events on it?

For better understanding please refer http://plnkr.co/edit/YYN8aechHGTKXvPv6tOo?p=preview apart from this also tried to access the particular side using following code:

                raycaster.setFromCamera( mouse, camera );

                var intersects = raycaster.intersectObjects( scene.children );
                if ( intersects.length > 0 ) {
                    var index = Math.floor( intersects[0].faceIndex / 2 );
                    if ( INTERSECTED != intersects[ 0 ].object && (index == 4 || index == 5)) {
                        if ( INTERSECTED ) {
                            INTERSECTED.material[intersects[0].faceIndex].color.setHex( INTERSECTED.currentHex );
                        }

                        INTERSECTED = intersects[ 0 ].object;
                        INTERSECTED.currentHex = INTERSECTED.material[4].color.getHex();
                        INTERSECTED.material[index].color.setHex( 0xCACACA );
                        f = index;
                }

Body:
I have used threex.domevent.js to capture the mouseover event and created a plunker. I am finding the cube face which has the svg image.
Links:
detect mouse click / hover event on sides of cube in three js and
https://github.com/jeromeetienne/threex.domevents.

Attach the dom event using *threex.domevent.js**

domEvents  = new THREEx.DomEvents(camera, renderer.domElement)

Listen to mouse over event and find the face you require.

        domEvents.addEventListener(mesh, 'mouseover', function(event) {
        var vector = new THREE.Vector3(
            (event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, );
        vector.unproject(camera);
        raycaster.set(camera.position, vector.sub(camera.position).normalize());

        var intersects = raycaster.intersectObject(mesh);
        if (intersects.length > 0) {
            var index = Math.floor(intersects[0].faceIndex / 2);
            if (index === 4) {
                //index 4 is  cude face having the svg image,
                //you can load a new svg or do required things here
                console.log('##############');
                mesh.material[4].map = new THREE.TextureLoader().load('sample2.svg');
            }

        }
    }, false)

Plunker: http://plnkr.co/edit/QXwqN3X70ex3EZmlKhRf?p=preview
Hope it helps.


来源: stackexchange

问:
Bash script assistance with find
I'm trying to write a bash script called by a daily cron schedule that will cycle all sub directories looking for a .git directory, run a git pull --all on that repository to update the repo and grab any new branches, track those branches, and then move on to the next repo. I'm a bash script beginner and familiar with some linux. My problem is the for loop which I found at How to clone all remote branches in Git? but doesn't seem to run properly now that I've introduced it into my script and the call to cd ${line}.. which doesn't seem to work as anticipated. I'm wondering what i've done wrong and some direction on how to fix it. Thank You.

My current script gitcron.sh:

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

find . -maxdepth 2 -name .git -type d -print > .gitrepos

while read -r line; do
  cd ${line}/..
  git pull --all
  for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
     git branch --track "${branch##*/}" "$branch"
  done
done < ".gitrepos"
</code>```

.gitrepos generated file:

```<code>./codeigniter/.git
./magento/.git
./magento2/.git
</code>```

My problem:

```<code>gitcron.sh: line 6: cd: ./magento2/.git/..: No such file or directory
fatal: it does not make sense to create 'HEAD' manually
error: unknown switch `>'
</code>```

答:
As other users have already posted, the problem seems to be not using absolute directories and cding twice.

You could simplify your script by getting rid of the temp file and using pushd and popd as opposed to cd some/path, cd -.

```<code>#!/usr/bin/env bash
set -uo pipefail

find . -maxdepth 2 -name ".git" -type d -print0 | while IFS= read -r -d '' repo; do
    # Use bash parameter substitution to remove .git from end of path
    pushd "${repo%.git}" >/dev/null
    # Could also use dirname to get the parent directory
    #pushd "$( dirname "$repo" )" >/dev/null
    # Now in correct directory; run all git commands"
    # git ...
    popd >/dev/null
done
</code>```

ContentLicense: CC BY-SA 3.0

Title: Bash script assistance with find

Body:
I'm trying to write a bash script called by a daily cron schedule that will cycle all sub directories looking for a .git directory, run a git pull --all on that repository to update the repo and grab any new branches, track those branches, and then move on to the next repo. I'm a bash script beginner and familiar with some linux. My problem is the for loop which I found at How to clone all remote branches in Git? but doesn't seem to run properly now that I've introduced it into my script and the call to cd ${line}.. which doesn't seem to work as anticipated. I'm wondering what i've done wrong and some direction on how to fix it. Thank You.

My current script gitcron.sh:

#!/bin/bash

find . -maxdepth 2 -name .git -type d -print > .gitrepos

while read -r line; do
  cd ${line}/..
  git pull --all
  for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
     git branch --track "${branch##*/}" "$branch"
  done
done < ".gitrepos"

.gitrepos generated file:

./codeigniter/.git
./magento/.git
./magento2/.git

My problem:

gitcron.sh: line 6: cd: ./magento2/.git/..: No such file or directory
fatal: it does not make sense to create 'HEAD' manually
error: unknown switch `>'

Body:
As other users have already posted, the problem seems to be not using absolute directories and cding twice.

You could simplify your script by getting rid of the temp file and using pushd and popd as opposed to cd some/path, cd -.

#!/usr/bin/env bash
set -uo pipefail

find . -maxdepth 2 -name ".git" -type d -print0 | while IFS= read -r -d '' repo; do
    # Use bash parameter substitution to remove .git from end of path
    pushd "${repo%.git}" >/dev/null
    # Could also use dirname to get the parent directory
    #pushd "$( dirname "$repo" )" >/dev/null
    # Now in correct directory; run all git commands"
    # git ...
    popd >/dev/null
done


问:
Jquery loop through selectors and click event handler
Think this is a chicken-or-egg or closure problem or something else I'm missing.  How do I loop through numerical selector values in JQuery when there is an onClick event handler?</p>

```<code>$("#q01").click(function() {
    clearIt();
    $("#item01").show();
});
$("#q02").click(function() {
    clearIt();
    $("#item02").show();
});
$("#q03").click(function() {
    clearIt();
    $("#item03").show();
});
</code>```

答:
You should try data- attributes. In this way, you don't need any string replacement. Just keep the target's id in a data attribute, in this example I use data-target. You can change to any name you like. data-show
, data-blah.

HTML

```<code><button type="button" class="clear-it" data-target="item01">Clear it and
show the target</button>
</code>```

JavaScript

```<code>$('.clear-it').each(function() {
  clearIt();
  $(this).click(function() {
    var whereToGo = this.getAttribute('data-target');
    // or var whereToGo = this.dataset.target;
    // or var whereToGo = $(this).data('target');

    $("#" + whereToGo).show();
  });
})
</code>```

Body:
Think this is a chicken-or-egg or closure problem or something else I'm missing.  How do I loop through numerical selector values in JQuery when there is an onClick event handler?

$("#q01").click(function() {
    clearIt();
    $("#item01").show();
});
$("#q02").click(function() {
    clearIt();
    $("#item02").show();
});
$("#q03").click(function() {
    clearIt();
    $("#item03").show();
});

Body:
You should try data- attributes. In this way, you don't need any string replacement. Just keep the target's id in a data attribute, in this example I use data-target. You can change to any name you like. data-show
, data-blah.

HTML

<button type="button" class="clear-it" data-target="item01">Clear it and
show the target</button>

JavaScript

$('.clear-it').each(function() {
  clearIt();
  $(this).click(function() {
    var whereToGo = this.getAttribute('data-target');
    // or var whereToGo = this.dataset.target;
    // or var whereToGo = $(this).data('target');

    $("#" + whereToGo).show();
  });
})


问:
How drag and drop of files is done?
as in winamp or vlc player, how to do a file drag and drop? i mean i want to know what sort of coding goes into application? i want to know for c++</p>

答:
In pure C/C++ on Windows, start reading about the DragAcceptFiles  function and the WM_DROPFILES message. If you're using a more powerful C++ library (Qt, Wx, etc) check their respective documentation. It would help to know what you use, more specifically.

Also, this discussion may answer your question. If it's what you meant, please close this question.

OwnerDisplayName: kasperasky

ContentLicense: CC BY-SA 2.5

Title: How drag and drop of files is done?

LastEditorDisplayName: PhiLho

OwnerDisplayName: eliben


问:
touches moved function affecting pressing a button
I have this character menu in my game that displays characters and is moved from side to side by the touches moved function.

I have a button in the skscene (the grey button)that changes to a certain button as the center character changes depending on if that certain character is unlocked or not determines what button will be displayed.

The problem I have is that when I try and press the button to select the character or press to unlock the character it takes multiple presses to make it work, I have the touches for the buttons in the touches ended function as seen below.

```<code>  override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch: UITouch = touches.first!
    let location: CGPoint = touch.location(in: self)
    let node: SKNode = self.atPoint(location)
    let duration = 0.25

    if node == selectButton {

        setNewPlayerSprite(nameOfPlayer: (centerPlayer?.name)!)

    } else if node == lockedButton || node == priceLabel {

        unlockPlayer(nameOfPlayer: (centerPlayer?.name)!)

    } else if node == otherButton {

        getSpecialUnlockData()

    } else if node == purchaseButton || node == purchasePriceLabe {

        purchaseCharacter(ID: characterProductID)

    } else if node == buyButton {

        giveItemAmount(itemName: "Item2", giveAmount: 1)

    }
</code>```

If I have them in the touches began method it works fine without any problems with needing to press it multiple times to get it to work. But if the player accidentally touches it even slightly then it unlocks the character which is a problem if they didn’t want to unlock the character or changed their mind.

The touches moved function that makes the menu move from side to side is affecting my ability to make button presses and therefore causes me to need to press the button multiple times to get it to work.

Is there someway of stopping the touches moved function from firing if one of the buttons is pressed? (or being pressed and held) here is my full touches functions code.

```<code>  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    //let duration = 0.01
    let touch: UITouch = touches.first!
    let newPosition = touch.location(in: self)
    let oldPosition = touch.previousLocation(in: self)
    let xTranslation = newPosition.x - oldPosition.x

    if centerPlayer!.frame.midX > size.width/2 {
        if (leftPlayer != nil) {
            let actualTranslation = leftPlayer!.frame.midX + xTranslation > leftGuide ? xTranslation : leftGuide - leftPlayer!.frame.midX
            movePlayerByX(player: leftPlayer!, x: actualTranslation)
        }
    } else {
        if (rightPlayer != nil) {
            let actualTranslation = rightPlayer!.frame.midX + xTranslation < rightGuide ? xTranslation : rightGuide - rightPlayer!.frame.midX
            movePlayerByX(player: rightPlayer!, x: actualTranslation)
        }
    }

    movePlayerByX(player: centerPlayer!, x: xTranslation)
    priceLabel.isHidden = true; selectButton.isHidden = true; lockedButton.isHidden = true; otherButton.isHidden = true
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch: UITouch = touches.first!
    let location: CGPoint = touch.location(in: self)
    let node: SKNode = self.atPoint(location)
    let duration = 0.25

    if node == selectButton {

        setNewPlayerSprite(nameOfPlayer: (centerPlayer?.name)!)

    } else if node == lockedButton || node == priceLabel {

        unlockPlayer(nameOfPlayer: (centerPlayer?.name)!)

    } else if node == otherButton {

        getSpecialUnlockData()

    } else if node == purchaseButton || node == purchasePriceLabe {

        purchaseCharacter(ID: characterProductID)

    } else if node == buyButton {

        giveItemAmount(itemName: "Item2", giveAmount: 1)

    }
</code>```

答:
I would check to see if the touch is in a certain view or not with an if statement.

Something like this:

```<code>override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

//let duration = 0.01
let touch: UITouch = touches.first!
if touch.view == self.view{
    let newPosition = touch.location(in: self)
    let oldPosition = touch.previousLocation(in: self)
    let xTranslation = newPosition.x - oldPosition.x

    if centerPlayer!.frame.midX > size.width/2 {
        if (leftPlayer != nil) {
            let actualTranslation = leftPlayer!.frame.midX + xTranslation > leftGuide ? xTranslation : leftGuide - leftPlayer!.frame.midX
            movePlayerByX(player: leftPlayer!, x: actualTranslation)
        }
    } else {
        if (rightPlayer != nil) {
            let actualTranslation = rightPlayer!.frame.midX + xTranslation < rightGuide ? xTranslation : rightGuide - rightPlayer!.frame.midX
            movePlayerByX(player: rightPlayer!, x: actualTranslation)
        }
    }

    movePlayerByX(player: centerPlayer!, x: xTranslation)
    priceLabel.isHidden = true; selectButton.isHidden = true;
    lockedButton.isHidden = true; otherButton.isHidden = true
}

}
</code>```

Body:
I have this character menu in my game that displays characters and is moved from side to side by the touches moved function.

I have a button in the skscene (the grey button)that changes to a certain button as the center character changes depending on if that certain character is unlocked or not determines what button will be displayed.

The problem I have is that when I try and press the button to select the character or press to unlock the character it takes multiple presses to make it work, I have the touches for the buttons in the touches ended function as seen below.

  override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch: UITouch = touches.first!
    let location: CGPoint = touch.location(in: self)
    let node: SKNode = self.atPoint(location)
    let duration = 0.25

    if node == selectButton {

        setNewPlayerSprite(nameOfPlayer: (centerPlayer?.name)!)

    } else if node == lockedButton || node == priceLabel {

        unlockPlayer(nameOfPlayer: (centerPlayer?.name)!)

    } else if node == otherButton {

        getSpecialUnlockData()

    } else if node == purchaseButton || node == purchasePriceLabe {

        purchaseCharacter(ID: characterProductID)

    } else if node == buyButton {

        giveItemAmount(itemName: "Item2", giveAmount: 1)

    }

If I have them in the touches began method it works fine without any problems with needing to press it multiple times to get it to work. But if the player accidentally touches it even slightly then it unlocks the character which is a problem if they didn’t want to unlock the character or changed their mind.

The touches moved function that makes the menu move from side to side is affecting my ability to make button presses and therefore causes me to need to press the button multiple times to get it to work.

Is there someway of stopping the touches moved function from firing if one of the buttons is pressed? (or being pressed and held) here is my full touches functions code.

  override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

    //let duration = 0.01
    let touch: UITouch = touches.first!
    let newPosition = touch.location(in: self)
    let oldPosition = touch.previousLocation(in: self)
    let xTranslation = newPosition.x - oldPosition.x

    if centerPlayer!.frame.midX > size.width/2 {
        if (leftPlayer != nil) {
            let actualTranslation = leftPlayer!.frame.midX + xTranslation > leftGuide ? xTranslation : leftGuide - leftPlayer!.frame.midX
            movePlayerByX(player: leftPlayer!, x: actualTranslation)
        }
    } else {
        if (rightPlayer != nil) {
            let actualTranslation = rightPlayer!.frame.midX + xTranslation < rightGuide ? xTranslation : rightGuide - rightPlayer!.frame.midX
            movePlayerByX(player: rightPlayer!, x: actualTranslation)
        }
    }

    movePlayerByX(player: centerPlayer!, x: xTranslation)
    priceLabel.isHidden = true; selectButton.isHidden = true; lockedButton.isHidden = true; otherButton.isHidden = true
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    let touch: UITouch = touches.first!
    let location: CGPoint = touch.location(in: self)
    let node: SKNode = self.atPoint(location)
    let duration = 0.25

    if node == selectButton {

        setNewPlayerSprite(nameOfPlayer: (centerPlayer?.name)!)

    } else if node == lockedButton || node == priceLabel {

        unlockPlayer(nameOfPlayer: (centerPlayer?.name)!)

    } else if node == otherButton {

        getSpecialUnlockData()

    } else if node == purchaseButton || node == purchasePriceLabe {

        purchaseCharacter(ID: characterProductID)

    } else if node == buyButton {

        giveItemAmount(itemName: "Item2", giveAmount: 1)

    }

Body:
I would check to see if the touch is in a certain view or not with an if statement.

Something like this:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

//let duration = 0.01
let touch: UITouch = touches.first!
if touch.view == self.view{
    let newPosition = touch.location(in: self)
    let oldPosition = touch.previousLocation(in: self)
    let xTranslation = newPosition.x - oldPosition.x

    if centerPlayer!.frame.midX > size.width/2 {
        if (leftPlayer != nil) {
            let actualTranslation = leftPlayer!.frame.midX + xTranslation > leftGuide ? xTranslation : leftGuide - leftPlayer!.frame.midX
            movePlayerByX(player: leftPlayer!, x: actualTranslation)
        }
    } else {
        if (rightPlayer != nil) {
            let actualTranslation = rightPlayer!.frame.midX + xTranslation < rightGuide ? xTranslation : rightGuide - rightPlayer!.frame.midX
            movePlayerByX(player: rightPlayer!, x: actualTranslation)
        }
    }

    movePlayerByX(player: centerPlayer!, x: xTranslation)
    priceLabel.isHidden = true; selectButton.isHidden = true;
    lockedButton.isHidden = true; otherButton.isHidden = true
}

}


问:
Google App Engine Error: Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager
App Engine gives the error:

```<code>com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfetch.Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager
</code>```

when I make call to Google Vision API inside Callable in async Servlet.
How to make it working?

servlet:

```<code>public class OcrForTextServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse response) {
            byte[] file = extractFile(req);
            String[] languages = req.getParameterValues("language");
            ExecutorService executor = Executors.newFixedThreadPool(2);
            Future<String> result = executor.submit(new OcrCallableTask(file, languages));
            executor.shutdown();
            response.getWriter().write(result.get()); //ERROR HERE
</code>```

Full stack trace:

```<code>[INFO] java.util.concurrent.ExecutionException: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfetch.Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager
[INFO]  at java.util.concurrent.FutureTask.report(FutureTask.java:122)
[INFO]  at java.util.concurrent.FutureTask.get(FutureTask.java:192)
[INFO]  at ocrme_backend.servlets.ocr.OcrForTextServlet.doPost(OcrForTextServlet.java:49)
[INFO]  at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
[INFO]  at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
[INFO]  at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1772)
[INFO]  at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.tools.development.jetty9.StaticFileFilter.doFilter(StaticFileFilter.java:122)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1751)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582)
[INFO]  at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
[INFO]  at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
[INFO]  at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
[INFO]  at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)
[INFO]  at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
[INFO]  at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
[INFO]  at com.google.appengine.tools.development.jetty9.DevAppEngineWebAppContext.doScope(DevAppEngineWebAppContext.java:112)
[INFO]  at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
[INFO]  at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
[INFO]  at com.google.appengine.tools.development.jetty9.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:596)
[INFO]  at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
[INFO]  at org.eclipse.jetty.server.Server.handle(Server.java:534)
[INFO]  at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
[INFO]  at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
[INFO]  at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)
[INFO]  at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)
[INFO]  at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
[INFO]  at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
[INFO]  at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
[INFO]  at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
[INFO]  at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
[INFO]  at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
[INFO]  at java.lang.Thread.run(Thread.java:745)
[INFO] Caused by: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfetch.Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager
[INFO]  at com.google.apphosting.api.ApiProxy$CallNotFoundException.foreignThread(ApiProxy.java:844)
[INFO]  at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:116)
[INFO]  at com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch(URLFetchServiceImpl.java:40)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.fetchResponse(URLFetchServiceStreamHandler.java:543)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getInputStream(URLFetchServiceStreamHandler.java:422)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getResponseCode(URLFetchServiceStreamHandler.java:275)
[INFO]  at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:37)
[INFO]  at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:94)
[INFO]  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:972)
[INFO]  at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:283)
[INFO]  at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
[INFO]  at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:362)
[INFO]  at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.fromStreamUser(GoogleCredential.java:772)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.fromStream(GoogleCredential.java:257)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getCredentialUsingWellKnownFile(DefaultCredentialProvider.java:249)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredentialUnsynchronized(DefaultCredentialProvider.java:117)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:91)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:213)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:191)
[INFO]  at ocrme_backend.ocr.OCRProcessorImpl.getVisionService(OCRProcessorImpl.java:40)
[INFO]  at ocrme_backend.ocr.OCRProcessorImpl.<init>(OCRProcessorImpl.java:32)
[INFO]  at ocrme_backend.servlets.ocr.OcrCallableTask.doStaff(OcrCallableTask.java:27)
[INFO]  at ocrme_backend.servlets.ocr.OcrCallableTask.call(OcrCallableTask.java:39)
[INFO]  at ocrme_backend.servlets.ocr.OcrCallableTask.call(OcrCallableTask.java:14)
[INFO]  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[INFO]  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[INFO]  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[INFO]  ... 1 more
</code>```

API call makes the error:

```<code>/**
 * Connects to the Vision API using Application Default Credentials.
 */
public static Vision getVisionService() throws IOException, GeneralSecurityException {
    GoogleCredential credential =
            GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
    com.google.api.client.json.JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}
</code>```

I am using the last version of javax.servlet-api (3.1.0), GAE (1.9.52) and Java 8. I need to obtain the result from the async part.
How can I do this?
Thank you for any help.

UPDATE:

I tried to use com.google.appengine.api.ThreadManager as mentioned in error message but it gives the same error. Here is my updated servlet:

```<code>@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) {

    try {
        byte[] file = extractFile(req);
        String[] languages = req.getParameterValues("language");

        ThreadFactory factory = ThreadManager.currentRequestThreadFactory();
        ExecutorService service = Executors.newCachedThreadPool(factory);
        Future<String> result =
                service.submit(new OcrCallableTask(file, languages));
        response.getWriter().write(result.get()); //ERROR HERE
</code>```

Next test passed OK:

```<code>public class OcrCallableTaskTest {
    @Test
    public void testCall() throws Exception {
        ExecutorService service = Executors.newFixedThreadPool(2);
        Future<String> result = service.submit(new OcrCallableTask(FileProvider.getFile(), null));
        Assert.assertTrue(result.get() != null);
        Assert.assertTrue(result.get().length() > 0);
    }
}
</code>```

UPDATE 2:

(Reply to the proposing do staff in request's thread.)

Realy I don't need extra thread for my servlet. It is only the attempt to fix the error.
I have the same error if I don't use multithreading in my app:

```<code>[INFO] com.google.api.gax.grpc.ApiException: io.grpc.StatusRuntimeException: UNAUTHENTICATED
[INFO]  at com.google.api.gax.grpc.ExceptionTransformingCallable$ExceptionTransformingFuture.onFailure(ExceptionTransformingCallable.java:108)
[INFO]  at com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:52)
[INFO]  at com.google.common.util.concurrent.Futures$6.run(Futures.java:1310)
[INFO]  at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:457)
[INFO]  at com.google.common.util.concurrent.ExecutionList.executeListener(ExecutionList.java:156)
[INFO]  at com.google.common.util.concurrent.ExecutionList.execute(ExecutionList.java:145)
[INFO]  at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:202)
[INFO]  at io.grpc.stub.ClientCalls$GrpcFuture.setException(ClientCalls.java:463)
[INFO]  at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:439)
[INFO]  at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:428)
[INFO]  at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:76)
[INFO]  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:514)
[INFO]  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$700(ClientCallImpl.java:431)
[INFO]  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:546)
[INFO]  at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
[INFO]  at io.grpc.internal.SerializingExecutor$TaskRunner.run(SerializingExecutor.java:152)
[INFO]  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
[INFO]  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[INFO]  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
[INFO]  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
[INFO]  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[INFO]  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[INFO]  at java.lang.Thread.run(Thread.java:745)
[INFO] Caused by: io.grpc.StatusRuntimeException: UNAUTHENTICATED
[INFO]  at io.grpc.Status.asRuntimeException(Status.java:540)
[INFO]  ... 15 more
[INFO] Caused by: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfetch.Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager
[INFO]  at com.google.apphosting.api.ApiProxy$CallNotFoundException.foreignThread(ApiProxy.java:844)
[INFO]  at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:116)
[INFO]  at com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch(URLFetchServiceImpl.java:40)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.fetchResponse(URLFetchServiceStreamHandler.java:543)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getInputStream(URLFetchServiceStreamHandler.java:422)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getResponseCode(URLFetchServiceStreamHandler.java:275)
[INFO]  at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:37)
[INFO]  at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:94)
[INFO]  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:972)
[INFO]  at com.google.auth.oauth2.UserCredentials.refreshAccessToken(UserCredentials.java:207)
[INFO]  at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:149)
[INFO]  at com.google.auth.oauth2.OAuth2Credentials.getRequestMetadata(OAuth2Credentials.java:135)
[INFO]  at io.grpc.auth.GoogleAuthLibraryCallCredentials$1.run(GoogleAuthLibraryCallCredentials.java:110)
[INFO]  ... 7 more
</code>```

code of servlet - no multithreading:

```<code> @Override
    public void doPost(HttpServletRequest req, HttpServletResponse response) {
        try {
            byte[] file = extractFile(req);
            String[] languages = req.getParameterValues("language");

            OCRProcessor processor = new OCRProcessorImpl();
            String jsonResult;

            if (languages == null || languages.length <= 0) {
                jsonResult = processor.ocrForText(file);
</code>```

next test passed ok:

```<code>@Test
public void doOCR() throws Exception {
    byte[] file = FileProvider.getImageFile().getFile();
    String result = ocrProcessor.ocrForText(file);
    assertNotNull(result);
    assertTrue(result.length() > 0);
}
</code>```

It seams (GAE + API calls) not compatible with Servlet architecture. Thank you for any advices.

答:
Async?

Maybe I misunderstand you, but your servlet seems not async:

```<code>    Future<String> result =
            service.submit(new OcrCallableTask(file, languages));
    response.getWriter().write(result.get()); //ERROR HERE
</code>```

You servlet thread will block until this url fetch finish because Future#get() will wait until task complete.

And, as your stacktrace shows, the ApiProxy also invoked the snyc method:

```<code>at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:116)
</code>```

Suggestions

It seems that Google App Engine still not open sourced, so I can just give your some possible directions:

From the doc of ApiProxy, this class may using some variable like ThreadLocal to store data, so creating new thread using Executors may confused App Engine;

It also stores an Environment for each thread, which contains additional user-visible information about the request

In your case, I didn't see the necessity of using multiple thread, you may would like to try fetch info using request thread;

If you indeed need async call, you may need using background thread, then notify user when call is finished;

More

I try to run your example, but your Vision class fails to compile. So I write up another example, here, which runs fine.

The following is the source code decompiled from sdk where exception happends:

```<code>    ApiProxy.Environment threadLocalEnvironment = (ApiProxy.Environment)environmentThreadLocal.get();
    if(threadLocalEnvironment != null) {
        return threadLocalEnvironment;
    } else {
        ApiProxy.EnvironmentFactory envFactory = getEnvironmentFactory();
        if(envFactory != null) {
            ApiProxy.Environment environment = envFactory.newEnvironment();
            environmentThreadLocal.set(environment);
            return environment;
        } else {
            return null;
        }
    }
</code>```

In your case, because it fails to get the environment factory, then it fails to get the environment, which leads to your exception.

When it comes to why it lack environment factory, I guess you made wrong configuration (do you run your war with GAE's server? if you test locally, it is necessary.)

Body:
App Engine gives the error:

com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfetch.Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager

when I make call to Google Vision API inside Callable in async Servlet.
How to make it working?

servlet:

public class OcrForTextServlet extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse response) {
            byte[] file = extractFile(req);
            String[] languages = req.getParameterValues("language");
            ExecutorService executor = Executors.newFixedThreadPool(2);
            Future<String> result = executor.submit(new OcrCallableTask(file, languages));
            executor.shutdown();
            response.getWriter().write(result.get()); //ERROR HERE

Full stack trace:

[INFO] java.util.concurrent.ExecutionException: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfetch.Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager
[INFO]  at java.util.concurrent.FutureTask.report(FutureTask.java:122)
[INFO]  at java.util.concurrent.FutureTask.get(FutureTask.java:192)
[INFO]  at ocrme_backend.servlets.ocr.OcrForTextServlet.doPost(OcrForTextServlet.java:49)
[INFO]  at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
[INFO]  at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
[INFO]  at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1772)
[INFO]  at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:134)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:48)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.tools.development.jetty9.StaticFileFilter.doFilter(StaticFileFilter.java:122)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1759)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
[INFO]  at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1751)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582)
[INFO]  at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
[INFO]  at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:524)
[INFO]  at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
[INFO]  at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180)
[INFO]  at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)
[INFO]  at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
[INFO]  at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
[INFO]  at com.google.appengine.tools.development.jetty9.DevAppEngineWebAppContext.doScope(DevAppEngineWebAppContext.java:112)
[INFO]  at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
[INFO]  at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
[INFO]  at com.google.appengine.tools.development.jetty9.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:596)
[INFO]  at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
[INFO]  at org.eclipse.jetty.server.Server.handle(Server.java:534)
[INFO]  at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
[INFO]  at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
[INFO]  at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:283)
[INFO]  at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:108)
[INFO]  at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93)
[INFO]  at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303)
[INFO]  at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148)
[INFO]  at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136)
[INFO]  at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
[INFO]  at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
[INFO]  at java.lang.Thread.run(Thread.java:745)
[INFO] Caused by: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfetch.Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager
[INFO]  at com.google.apphosting.api.ApiProxy$CallNotFoundException.foreignThread(ApiProxy.java:844)
[INFO]  at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:116)
[INFO]  at com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch(URLFetchServiceImpl.java:40)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.fetchResponse(URLFetchServiceStreamHandler.java:543)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getInputStream(URLFetchServiceStreamHandler.java:422)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getResponseCode(URLFetchServiceStreamHandler.java:275)
[INFO]  at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:37)
[INFO]  at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:94)
[INFO]  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:972)
[INFO]  at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:283)
[INFO]  at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
[INFO]  at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:570)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:362)
[INFO]  at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.fromStreamUser(GoogleCredential.java:772)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.fromStream(GoogleCredential.java:257)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getCredentialUsingWellKnownFile(DefaultCredentialProvider.java:249)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredentialUnsynchronized(DefaultCredentialProvider.java:117)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:91)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:213)
[INFO]  at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:191)
[INFO]  at ocrme_backend.ocr.OCRProcessorImpl.getVisionService(OCRProcessorImpl.java:40)
[INFO]  at ocrme_backend.ocr.OCRProcessorImpl.<init>(OCRProcessorImpl.java:32)
[INFO]  at ocrme_backend.servlets.ocr.OcrCallableTask.doStaff(OcrCallableTask.java:27)
[INFO]  at ocrme_backend.servlets.ocr.OcrCallableTask.call(OcrCallableTask.java:39)
[INFO]  at ocrme_backend.servlets.ocr.OcrCallableTask.call(OcrCallableTask.java:14)
[INFO]  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[INFO]  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[INFO]  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[INFO]  ... 1 more

API call makes the error:

/**
 * Connects to the Vision API using Application Default Credentials.
 */
public static Vision getVisionService() throws IOException, GeneralSecurityException {
    GoogleCredential credential =
            GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
    com.google.api.client.json.JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}

I am using the last version of javax.servlet-api (3.1.0), GAE (1.9.52) and Java 8. I need to obtain the result from the async part.
How can I do this?
Thank you for any help.

UPDATE:

I tried to use com.google.appengine.api.ThreadManager as mentioned in error message but it gives the same error. Here is my updated servlet:

@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) {

    try {
        byte[] file = extractFile(req);
        String[] languages = req.getParameterValues("language");

        ThreadFactory factory = ThreadManager.currentRequestThreadFactory();
        ExecutorService service = Executors.newCachedThreadPool(factory);
        Future<String> result =
                service.submit(new OcrCallableTask(file, languages));
        response.getWriter().write(result.get()); //ERROR HERE

Next test passed OK:

public class OcrCallableTaskTest {
    @Test
    public void testCall() throws Exception {
        ExecutorService service = Executors.newFixedThreadPool(2);
        Future<String> result = service.submit(new OcrCallableTask(FileProvider.getFile(), null));
        Assert.assertTrue(result.get() != null);
        Assert.assertTrue(result.get().length() > 0);
    }
}

UPDATE 2:

(Reply to the proposing do staff in request's thread.)

Realy I don't need extra thread for my servlet. It is only the attempt to fix the error.
I have the same error if I don't use multithreading in my app:

[INFO] com.google.api.gax.grpc.ApiException: io.grpc.StatusRuntimeException: UNAUTHENTICATED
[INFO]  at com.google.api.gax.grpc.ExceptionTransformingCallable$ExceptionTransformingFuture.onFailure(ExceptionTransformingCallable.java:108)
[INFO]  at com.google.api.core.ApiFutures$1.onFailure(ApiFutures.java:52)
[INFO]  at com.google.common.util.concurrent.Futures$6.run(Futures.java:1310)
[INFO]  at com.google.common.util.concurrent.MoreExecutors$DirectExecutor.execute(MoreExecutors.java:457)
[INFO]  at com.google.common.util.concurrent.ExecutionList.executeListener(ExecutionList.java:156)
[INFO]  at com.google.common.util.concurrent.ExecutionList.execute(ExecutionList.java:145)
[INFO]  at com.google.common.util.concurrent.AbstractFuture.setException(AbstractFuture.java:202)
[INFO]  at io.grpc.stub.ClientCalls$GrpcFuture.setException(ClientCalls.java:463)
[INFO]  at io.grpc.stub.ClientCalls$UnaryStreamToFuture.onClose(ClientCalls.java:439)
[INFO]  at io.grpc.internal.ClientCallImpl.closeObserver(ClientCallImpl.java:428)
[INFO]  at io.grpc.internal.ClientCallImpl.access$100(ClientCallImpl.java:76)
[INFO]  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.close(ClientCallImpl.java:514)
[INFO]  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl.access$700(ClientCallImpl.java:431)
[INFO]  at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$1StreamClosed.runInContext(ClientCallImpl.java:546)
[INFO]  at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:52)
[INFO]  at io.grpc.internal.SerializingExecutor$TaskRunner.run(SerializingExecutor.java:152)
[INFO]  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
[INFO]  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[INFO]  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
[INFO]  at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
[INFO]  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[INFO]  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[INFO]  at java.lang.Thread.run(Thread.java:745)
[INFO] Caused by: io.grpc.StatusRuntimeException: UNAUTHENTICATED
[INFO]  at io.grpc.Status.asRuntimeException(Status.java:540)
[INFO]  ... 15 more
[INFO] Caused by: com.google.apphosting.api.ApiProxy$CallNotFoundException: Can't make API call urlfetch.Fetch in a thread that is neither the original request thread nor a thread created by ThreadManager
[INFO]  at com.google.apphosting.api.ApiProxy$CallNotFoundException.foreignThread(ApiProxy.java:844)
[INFO]  at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:116)
[INFO]  at com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch(URLFetchServiceImpl.java:40)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.fetchResponse(URLFetchServiceStreamHandler.java:543)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getInputStream(URLFetchServiceStreamHandler.java:422)
[INFO]  at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getResponseCode(URLFetchServiceStreamHandler.java:275)
[INFO]  at com.google.api.client.http.javanet.NetHttpResponse.<init>(NetHttpResponse.java:37)
[INFO]  at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:94)
[INFO]  at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:972)
[INFO]  at com.google.auth.oauth2.UserCredentials.refreshAccessToken(UserCredentials.java:207)
[INFO]  at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:149)
[INFO]  at com.google.auth.oauth2.OAuth2Credentials.getRequestMetadata(OAuth2Credentials.java:135)
[INFO]  at io.grpc.auth.GoogleAuthLibraryCallCredentials$1.run(GoogleAuthLibraryCallCredentials.java:110)
[INFO]  ... 7 more

code of servlet - no multithreading:

 @Override
    public void doPost(HttpServletRequest req, HttpServletResponse response) {
        try {
            byte[] file = extractFile(req);
            String[] languages = req.getParameterValues("language");

            OCRProcessor processor = new OCRProcessorImpl();
            String jsonResult;

            if (languages == null || languages.length <= 0) {
                jsonResult = processor.ocrForText(file);

next test passed ok:

@Test
public void doOCR() throws Exception {
    byte[] file = FileProvider.getImageFile().getFile();
    String result = ocrProcessor.ocrForText(file);
    assertNotNull(result);
    assertTrue(result.length() > 0);
}

It seams (GAE + API calls) not compatible with Servlet architecture. Thank you for any advices.

Body:
Async?

Maybe I misunderstand you, but your servlet seems not async:

    Future<String> result =
            service.submit(new OcrCallableTask(file, languages));
    response.getWriter().write(result.get()); //ERROR HERE

You servlet thread will block until this url fetch finish because Future#get() will wait until task complete.

And, as your stacktrace shows, the ApiProxy also invoked the snyc method:

at com.google.apphosting.api.ApiProxy.makeSyncCall(ApiProxy.java:116)

Suggestions

It seems that Google App Engine still not open sourced, so I can just give your some possible directions:

From the doc of ApiProxy, this class may using some variable like ThreadLocal to store data, so creating new thread using Executors may confused App Engine;

It also stores an Environment for each thread, which contains additional user-visible information about the request

In your case, I didn't see the necessity of using multiple thread, you may would like to try fetch info using request thread;

If you indeed need async call, you may need using background thread, then notify user when call is finished;

More

I try to run your example, but your Vision class fails to compile. So I write up another example, here, which runs fine.

The following is the source code decompiled from sdk where exception happends:

    ApiProxy.Environment threadLocalEnvironment = (ApiProxy.Environment)environmentThreadLocal.get();
    if(threadLocalEnvironment != null) {
        return threadLocalEnvironment;
    } else {
        ApiProxy.EnvironmentFactory envFactory = getEnvironmentFactory();
        if(envFactory != null) {
            ApiProxy.Environment environment = envFactory.newEnvironment();
            environmentThreadLocal.set(environment);
            return environment;
        } else {
            return null;
        }
    }

In your case, because it fails to get the environment factory, then it fails to get the environment, which leads to your exception.

When it comes to why it lack environment factory, I guess you made wrong configuration (do you run your war with GAE's server? if you test locally, it is necessary.)


问:
How do I parse a string to a float or int?

How can I convert a str to float?
```<code>"545.2222"  →  545.2222
</code>```

How can I convert a str to int?
```<code>"31"        →  31
</code>```

For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it.

Please instead use How can I read inputs as numbers? to close duplicate questions where OP received a string from user input and immediately wants to convert it, or was hoping for input (in 3.x) to convert the type automatically.

答:
I use this function for that

```<code>import ast

def parse_str(s):
   try:
      return ast.literal_eval(str(s))
   except:
      return
</code>```

It will convert the string to its type

```<code>value = parse_str('1')  # Returns Integer
value = parse_str('1.5')  # Returns Float
</code>```

OwnerDisplayName: DrFredEdison

ContentLicense: CC BY-SA 4.0

Body:
How can I convert a str to float?

"545.2222"  →  545.2222

How can I convert a str to int?

"31"        →  31

For the reverse, see Convert integer to string in Python and Converting a float to a string without rounding it.

Please instead use How can I read inputs as numbers? to close duplicate questions where OP received a string from user input and immediately wants to convert it, or was hoping for input (in 3.x) to convert the type automatically.

LastEditorDisplayName: DrFredEdison

Body:
I use this function for that

import ast

def parse_str(s):
   try:
      return ast.literal_eval(str(s))
   except:
      return

It will convert the string to its type

value = parse_str('1')  # Returns Integer
value = parse_str('1.5')  # Returns Float


问:
SQL statement to select join multiple fields from different table?
I'm trying to create a sql statement that joins attribute from different tables but I am having confusion on how to call it. I'll explain the tables first.

First table is machine with some machine
The second table contain some meter reading description.

In third table, ID column of table Machine and MeterReading are used as foreign key to indicate the types of meter readings available to machines. One machines can have multiple meter reading descriptions.

Table 4 use the ID of table meterreadingMachine and store the reading for particular machine and its meterreading description.

Now I want to select all Machines using ID (for example select * from meterreadingMachine WHERE MachineID = 1) and list the actualreading for all the machine ID= 1  from table actual reading.

答:
Just use the pretty awesome possibility called JOIN:

```<code>    SELECT M.*
          ,mR.*
          ,AR.actualreading
      FROM Maschine M
INNER JOIN meterReadingMachine  mRM
        ON mRM.machineid            = M.maschineID
INNER JOIN meterReading mR
        ON mR.meterreadingid        = mRM.meterreadingid
INNER JOIN ActualReading AR
        ON AR.meterreadingmachineid = mRM.meterreadingmachineid
     WHERE M.MachineID = 1
</code>```

Body:
Just use the pretty awesome possibility called JOIN:

    SELECT M.*
          ,mR.*
          ,AR.actualreading
      FROM Maschine M
INNER JOIN meterReadingMachine  mRM
        ON mRM.machineid            = M.maschineID
INNER JOIN meterReading mR
        ON mR.meterreadingid        = mRM.meterreadingid
INNER JOIN ActualReading AR
        ON AR.meterreadingmachineid = mRM.meterreadingmachineid
     WHERE M.MachineID = 1


问:
Turbo C++ compile error "too many types in declaration"
whenever I compile this program, I get an error saying "Too many types in decleration on line 13". I do not see any possible syntax errors but still I am facing this issue.

```<code>#include<iostream.h>
#include<conio.h>

class currency
{
    private:
    int rupee,paise;
    int total;
    public:
    void getdata(int r,int p);
    void display();

}
void currency::getdata(int r, int p){

    rupee=r;
    paise=p;
    total=r*100+p;

}
void currency::display(){

cout<<rupee<<" Rupees"<<" and "<<paise<<"Paise"<<endl;
cout<<"Converted value="<<total;

}

int main(){

    currency c;
        c.getdata(5,25);
        c.display();
        getch();
        return 0;

}
</code>```

答:
If you'll put a semicolon ";" after ending class currency{ } your program will be compiled and you'll get the correct output.

```<code>class abc
{
   ...
};
</code>```

Body:
whenever I compile this program, I get an error saying "Too many types in decleration on line 13". I do not see any possible syntax errors but still I am facing this issue.

#include<iostream.h>
#include<conio.h>

class currency
{
    private:
    int rupee,paise;
    int total;
    public:
    void getdata(int r,int p);
    void display();

}
void currency::getdata(int r, int p){

    rupee=r;
    paise=p;
    total=r*100+p;

}
void currency::display(){

cout<<rupee<<" Rupees"<<" and "<<paise<<"Paise"<<endl;
cout<<"Converted value="<<total;

}

int main(){

    currency c;
        c.getdata(5,25);
        c.display();
        getch();
        return 0;

}

Body:
If you'll put a semicolon ";" after ending class currency{ } your program will be compiled and you'll get the correct output.

class abc
{
   ...
};


问:
angular-cli what is the difference between version of package.json and ng -v
I have in my package.json this versions of dependencies

```<code>"dependencies": {
  "@angular/animations": "^4.1.3",
  "@angular/common": "^4.0.0",
  "@angular/compiler": "^4.0.0",
  "@angular/core": "^4.0.0",
  "@angular/forms": "^4.0.0",
  "@angular/http": "^4.0.0",
  "@angular/platform-browser": "^4.0.0",
  "@angular/platform-browser-dynamic": "^4.0.0",
  "@angular/router": "^4.0.0",

"devDependencies": {
   "@angular/cli": "1.0.6",
   "@angular/compiler-cli": "^4.0.0",
</code>```

and in the project when execute ng -v

```<code>$ ng -v
@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
@angular/cli: 1.0.6
@angular/compiler-cli: 4.2.4
</code>```

what is the current version of @angular in the project 4.0.0 or 4.2.4?

答:
The versions in package.json are version ranges.

For example, if the version of @angular/core there is ^4.0.0, this is like 4.x.x, so depending on the last time you ran npm install (with no arguments), the actual version of @angular/core you might have in node_modules might be 4.0.1 or 4.2.5 etc.

Another example is typescript. It might show in package.json as ~2.3.0, which is like 2.3.x, you actual version might be 2.3.4.

You can check the version truly installed of a package by running npm ls, for example npm ls typescript will show all versions of typescript package either called directly from package.json, or coming as a dependency of another package.

The Angular/cli version is very specific in your provided package.json, and set to 1.0.6.

You would also have a global install (not specific to the project that has the package.json file) of @angular/cli. You can check its version by running npm ls -g @angular/cli.

This is very close to ng -v. What ng -v tells you is:

What's the globally installed version of @angular/cli

What's the locally installed version of @angular/cli (the one in node_modules, not the range specific in package.json).

This is important in case you have both, as having different versions of both might causes issues.

What are the locally installed versions (not the ranges) of other Angular packages that you need to ensure are in sync

Body:
I have in my package.json this versions of dependencies

"dependencies": {
  "@angular/animations": "^4.1.3",
  "@angular/common": "^4.0.0",
  "@angular/compiler": "^4.0.0",
  "@angular/core": "^4.0.0",
  "@angular/forms": "^4.0.0",
  "@angular/http": "^4.0.0",
  "@angular/platform-browser": "^4.0.0",
  "@angular/platform-browser-dynamic": "^4.0.0",
  "@angular/router": "^4.0.0",

"devDependencies": {
   "@angular/cli": "1.0.6",
   "@angular/compiler-cli": "^4.0.0",

and in the project when execute ng -v

$ ng -v
@angular/animations: 4.2.4
@angular/common: 4.2.4
@angular/compiler: 4.2.4
@angular/core: 4.2.4
@angular/forms: 4.2.4
@angular/http: 4.2.4
@angular/platform-browser: 4.2.4
@angular/platform-browser-dynamic: 4.2.4
@angular/router: 4.2.4
@angular/cli: 1.0.6
@angular/compiler-cli: 4.2.4

what is the current version of @angular in the project 4.0.0 or 4.2.4?


问:
How to make an if statement if your pointer is getting garbage
Hi everyone I have a problem taking care of a malfunction, I'm building a dynamic linked list which connects structures with *next and *previous,
now if the structures are unable to connect (long story) I need to print "the way does not exist" now I've made an if statement

```<code>    temp = point_start; // point_start is the head of the list
condition = 2;
for(i=0;i<gagnum;i++) //gagnum is the number of structures
{
    temp=point_start->previous; // previous is the pointer of the previous structure.

    if (temp != 0xcdcdcdcd) // ------> is this legal?
        condition = 1;
    else
    {
        printf("no route found ")
        condition = 2;
        break;
    }

}
</code>```

I have an if statement which says "if (temp != 0xcdcdcdcd)" so when it gets garbage I put out the message and stop the program, is this legal to use? is there a better way to do this? thank you so much for your help!

答:
Instead of using 0xcdcdcdcd, you should be using 0x0 to indicate a NULL pointer.

Here's a function which does what I think you're trying to do:

```<code>// checks to see if the given list is the "first" structure
bool is_first_structure(void* head)
{
    return head->previous != NULL;
}
</code>```

And here's how to use it:

```<code>if(!is_first_structure(head))
{
    printf("no route found");
}
</code>```

Body:
Hi everyone I have a problem taking care of a malfunction, I'm building a dynamic linked list which connects structures with *next and *previous,
now if the structures are unable to connect (long story) I need to print "the way does not exist" now I've made an if statement

    temp = point_start; // point_start is the head of the list
condition = 2;
for(i=0;i<gagnum;i++) //gagnum is the number of structures
{
    temp=point_start->previous; // previous is the pointer of the previous structure.

    if (temp != 0xcdcdcdcd) // ------> is this legal?
        condition = 1;
    else
    {
        printf("no route found ")
        condition = 2;
        break;
    }

}

I have an if statement which says "if (temp != 0xcdcdcdcd)" so when it gets garbage I put out the message and stop the program, is this legal to use? is there a better way to do this? thank you so much for your help!

Body:
Instead of using 0xcdcdcdcd, you should be using 0x0 to indicate a NULL pointer.

Here's a function which does what I think you're trying to do:

// checks to see if the given list is the "first" structure
bool is_first_structure(void* head)
{
    return head->previous != NULL;
}

And here's how to use it:

if(!is_first_structure(head))
{
    printf("no route found");
}


问:
Help with strange memory behavior. Looking for leaks both in my brain and in my code
I spent the last few days trying to find memory leaks in a program we are developing.

First of all, I tried using some leak detectors. After fixing a few issues, they do not find any leaks any more. However, I am also monitoring my application using perfmon.exe. Performance Monitor reports that 'Private Bytes' and 'Working Set - Private' are steadily rising when the app is used. To me, this suggests that the program is using more and more memory the longer it runs. Internal resources seem to be stable however, so this sounds like leaking to me.

The program is loading a DLL at runtime. I suspect that these leaks or whatever they are occur in that library and get purged when the library is unloaded, hence they won't get picked up by the leak detectors. I used both DevPartner BoundsChecker and Virtual Leak Detector to look for memory leaks. Both supposedly catch leaks in DLLs.

Also, the memory consumption is increasing in steps and those steps roughly, but not exactly, coincide with certain GUI actions I perform in the application. If these were errors in our code, they should get triggered every single time the actions are performed and not just most of the time.

Whenever I am confronted with so much strangeness, I begin to question my basic assumptions. So I turn to you, who know everything, for suggestions. Is there a flaw in my assumptions? Do you have an idea of how to go about troubleshooting a problem like this?

Edit:

I am currently using Microsoft Visual C++ (x86) on Windows 7 64.

Edit2:

I just used IBM Purify to hunt for leaks. First of all, it lists a full 30% of the program as leaked memory. This can not be true. I guess it is identifying the whole DLL as leaked or something like that. However, if I search for new leaks every few actions, it reports leaks that correspond with the size increase reported by Performance Monitor. This could be a lead to a leak. Sadly, I am only using the trial version of Purify, so it won't show me the actual location of those leaks. (These leaks only show up at runtime. When the program exits, there are no leaks whatsoever reported by any tool.)

答: Perfmon looks at the number of (4K) pages allocated to your program. Those will typically managed by the heap manager. For instance, if your button press requires 3 allocations of 1 KB each, the heap manager will have to request a new page the first three times. The fourth time, it still has 3KB left. Therefore, you cannot conclude that your button press must have an externally visible effect every time.</p>


问:
How to retrieve session value stored in one aspx page to Generic Handler file
I have an aspx page in which I stored textbox value in a session as Session["uname"]=txtUserName.Text. now i want to get that session value in ashx file. In ashx file I wrote string str=context.Session["uname"].ToString() bt it gives me nullReference error.Any other method to do this??

答:
Make sure your handler (.ashx file) is implementing this interface:

```<code>System.Web.SessionState.IRequiresSessionState
</code>```

If you only need read only access to session then use:

```<code>System.Web.SessionState.IReadOnlySessionState
</code>```

They are both marker interfaces.

From MSDN on IRequiresSessionState:

Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.

Body:
Make sure your handler (.ashx file) is implementing this interface:

System.Web.SessionState.IRequiresSessionState

If you only need read only access to session then use:

System.Web.SessionState.IReadOnlySessionState

They are both marker interfaces.

From MSDN on IRequiresSessionState:

Specifies that the target HTTP handler requires read and write access to session-state values. This is a marker interface and has no methods.


问:
Printing *s as triangles in Java?
My assignment in my Java course is to make 3 triangles. One left aligned, one right aligned, and one centered. I have to make a menu for what type of triangle and then input how many rows is wanted. The triangles have to look like this

```<code>*
**
***
****

   *
  **
 ***
****

  *
 ***
*****
</code>```

So far I was able to do the left aligned triangle but I can't seem to get the other two. I tried googling but nothing turned up. Can anyone help? I have this so far.

```<code>import java.util.*;
public class Prog673A
{
    public static void leftTriangle()
    {
        Scanner input = new Scanner (System.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i <= x; i++)
            {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
    public static void rightTriangle()
    {
        Scanner input = new Scanner (System.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i >= x; i--)
            {
                System.out.print(" ");
            }
            System.out.println("*");
        }
    }
    public static void centerTriangle()
    {

    }
    public static void main (String args [])
    {
        Scanner input = new Scanner (System.in);
        System.out.println("Types of Triangles");
        System.out.println("\t1. Left");
        System.out.println("\t2. Right");
        System.out.println("\t3. Center");
        System.out.print("Enter a number: ");
        int menu = input.nextInt();
        if (menu == 1)
            leftTriangle();
        if (menu == 2)
            rightTriangle();
        if (menu == 3)
            centerTriangle();
    }
}
</code>```

Sample Output:

```<code>Types of Triangles
1.  Left
2.  Right
3.  Center
Enter a number (1-3):  3
How many rows?: 6

     *
    ***
   *****
  *******
 *********
***********
</code>```

答:
For center triangle

```<code>      Scanner sc = new Scanner(System.in);
      int n=sc.nextInt();
      int b=(n-1)*2;
      for(int i=1;i<=n;i++){
      int t= i;
      for(int k=1;k<=b;k++){
      System.out.print(" ");
       }
       if(i!=1){
        t=i*2-1;
       }
       for(int j=1;j<=t;j++){
       System.out.print("*");
       if(j!=t){
       System.out.print(" ");
       }
        }
        System.out.println();
            b=b-2;
        }
</code>```

output:

```<code>            *
          * * *
</code>```

Title: Printing *s as triangles in Java?

Body:
My assignment in my Java course is to make 3 triangles. One left aligned, one right aligned, and one centered. I have to make a menu for what type of triangle and then input how many rows is wanted. The triangles have to look like this

*
**
***
****

   *
  **
 ***
****

  *
 ***
*****

So far I was able to do the left aligned triangle but I can't seem to get the other two. I tried googling but nothing turned up. Can anyone help? I have this so far.

import java.util.*;
public class Prog673A
{
    public static void leftTriangle()
    {
        Scanner input = new Scanner (System.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i <= x; i++)
            {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
    public static void rightTriangle()
    {
        Scanner input = new Scanner (System.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i >= x; i--)
            {
                System.out.print(" ");
            }
            System.out.println("*");
        }
    }
    public static void centerTriangle()
    {

    }
    public static void main (String args [])
    {
        Scanner input = new Scanner (System.in);
        System.out.println("Types of Triangles");
        System.out.println("\t1. Left");
        System.out.println("\t2. Right");
        System.out.println("\t3. Center");
        System.out.print("Enter a number: ");
        int menu = input.nextInt();
        if (menu == 1)
            leftTriangle();
        if (menu == 2)
            rightTriangle();
        if (menu == 3)
            centerTriangle();
    }
}

Sample Output:

Types of Triangles
1.  Left
2.  Right
3.  Center
Enter a number (1-3):  3
How many rows?: 6

     *
    ***
   *****
  *******
 *********
***********

Body:
For center triangle

      Scanner sc = new Scanner(System.in);
      int n=sc.nextInt();
      int b=(n-1)*2;
      for(int i=1;i<=n;i++){
      int t= i;
      for(int k=1;k<=b;k++){
      System.out.print(" ");
       }
       if(i!=1){
        t=i*2-1;
       }
       for(int j=1;j<=t;j++){
       System.out.print("*");
       if(j!=t){
       System.out.print(" ");
       }
        }
        System.out.println();
            b=b-2;
        }

output:

            *
          * * *


问:
Possible to return an image in the Google Actions webhook response?
From the docs it seems like SpeechResponse is the only documented type of response you can return:

https://developers.google.com/actions/reference/conversation#SpeechResponse

Is it be possible to load an image or some other type of media in the assistant conversation via API.AI or the Actions SDK? Seems like this is supported with api.ai for FB, other messengers:

https://docs.api.ai/docs/rich-messages#image

Thanks!

答:
That feature seems to be present now. You can look it up in the docs at https://developers.google.com/actions/assistant/responses

Note: But images would be supported only on devices with a visual output. So Google Home would obviously not be able to do it. But the devices with screen do support a card with an image.


问:
Connection has been already closed for Spring Boot and MySQL
We are migrating our system from MS SQL Server to MySQL and we are using spring boot for our application. Our application facing "Connection has been already closed" SQLException for some days and we use to restart our application and it started working fine but here is the catch after some hours it start giving same connection closed SQLException.

Here is the configs properties xfor connection:

```<code>database.jndiName=jdbc/SmartData
database.driverClassName=com.mysql.jdbc.Driver
database.url=XXXXXX
database.username=XXXXXXXXXXX
database.password=XXXXXX
database.factory=org.apache.tomcat.jdbc.pool.DataSourceFactory
database.initialSize=2
database.logAbandoned=false
database.maxIdle=4
database.maxWaitMillis=29998
database.minEvictableIdleTimeMillis=3000
database.minIdle=2
database.removeAbandonedTimeout=6
database.removeAbandoned=true
database.testOnBorrow=true
database.testOnReturn=false
database.testWhileIdle=false
database.timeBetweenEvictionRunsMillis=3000
database.validationQuery=SELECT 2+2
database.maxActive=10
database.validationInterval=3000
</code>```

答:
Try to add below properties in your application.properties or configuration file in case external configuration.

database.test-on-borrow=true

database.validation-query=SELECT 1

Body:
We are migrating our system from MS SQL Server to MySQL and we are using spring boot for our application. Our application facing "Connection has been already closed" SQLException for some days and we use to restart our application and it started working fine but here is the catch after some hours it start giving same connection closed SQLException.

Here is the configs properties xfor connection:

database.jndiName=jdbc/SmartData
database.driverClassName=com.mysql.jdbc.Driver
database.url=XXXXXX
database.username=XXXXXXXXXXX
database.password=XXXXXX
database.factory=org.apache.tomcat.jdbc.pool.DataSourceFactory
database.initialSize=2
database.logAbandoned=false
database.maxIdle=4
database.maxWaitMillis=29998
database.minEvictableIdleTimeMillis=3000
database.minIdle=2
database.removeAbandonedTimeout=6
database.removeAbandoned=true
database.testOnBorrow=true
database.testOnReturn=false
database.testWhileIdle=false
database.timeBetweenEvictionRunsMillis=3000
database.validationQuery=SELECT 2+2
database.maxActive=10
database.validationInterval=3000


问:
TFS 2012 : The working folder is already in use after Hard Disk Format
I have referred to a lot of forums and also this so question but my problem is that I have formatted my machine. So I'm not able to overcome this issue. I have tried deleting workspaces from visual studio command prompt and also clearing cache, but I feel this mapping is more on the server-side than local cache, because my machine was formatted. I don't know which file has this old working path saved.

Also I have tried downloading the project into a new working path. I was able to download, but then I don't get the TFS icon against each file. i.e.it's like working offline (disjoint from TFS database). On right click we generally have an option to return online or go online. In this case on right click I get TEAM -> Apply Patch & TEAM -> Share Project

Please help me with this.I had the same problem in my asp.net projects, when I simply downloaded them onto a new working path it worked fine. But this java project in eclipse just doesn't seem to connect to tfs when downloaded into a new path nor does it allow to download in the old path.

Please not I have formatted the machine.So my case is different, so this may not be a possible duplicate of other SO questions.

I did not disconnect or delete workspace before a format(due to lack of knowledge) at that point. May be doing that would never cause this.
All I did is check in all files and re-formatted my windows.

答:
logout from previous user and login by new user.
Copy Project Folder to Another path.
In team Explorer Right click on project and Remove mapping.
Remap Project</p>