问:
d.ts files cannot find module 'rxjs/Observable'
I am pretty new to Angular2/4 and i am trying to build a WebAPI that updates a SQL table. The Issue is that when I run the Build function in Visual Studio 2015, I get error code TS2307 "Cannot find module 'rxjs/Observable'" for every one of the "d.ts" files. When I click on the error, it sends me to the Import statement in the Specified file, with the error under the "@rxjs/Observable" portion.

I have looked for a couple hours trying to find a solution and haven't found one that matches the situation, so if I duplicated something please drop a link in the comments so I can check it out.

If there are any other files you would need to help please let me know. Thank you in advance.

Here are some(as many as I could get in the screenshot)of the errors from VS15:

Here is my Package.json file:

```<code>   {
     "version": "1.0.0",
     "name": "asp.net",
     "private": true,
     "scripts": {
           "build": "webpack",
           "start": "static ."
           },
     "dependencies": {
           "@angular/core": "2.4.0",
           "@angular/common": "2.4.0",
           "@angular/compiler": "2.4.0",
           "@angular/platform-browser": "2.4.0",
           "@angular/platform-browser-dynamic": "2.4.0",
           "core-js": "^2.4.1",
           "zone.js": "^0.8.4",
           "rxjs": "^5.2.0",
           "reflect-metadata": "^0.1.10"
           },
     "devDependencies": {
          "gulp": "^3.9.1",
          "gulp-exec": "^2.1.3",
          "awesome-typescript-loader": "^3.1.2",
          "typings": "^2.1.0",
          "webpack": "^3.8.1",
          "ng2-bs3-modal": "0.10.4"
          }
      }
</code>```

Here is my tsconfig.json

```<code>  {
   "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es2015", "dom" ],
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true
        }
   }
</code>```

UPDATE:1
I went through and lowered the angular version number in the package.json file as shown above. Then deleted the node_module from the project and restarted VS15. then I restored the packages to find a bunch more errors waiting.

So I am hoping the new batch of errors helps figure something out...

答:
On the advice of @yms, I found the Quickstart file for the Angular2.4 and copied the package.json, tsconfig.jason and systemjs.config.js  into the solution. then i read the ReadMe file which points out that you have to use the angular/cli from now on.. so i tried installing that with the command:

```<code>npm install -g @angular/cli
</code>```

my errors i was getting reduced to "incorrectly extends" error, which was fixed by pushing the typescript version to "^2.4.0" and the rxjs version to "5.4.2" in the package.json file then restoring the packages.

So here is my working Package.json:

```<code>{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented
with testing support",
"scripts": {
  "build": "tsc -p src/",
  "build:watch": "tsc -p src/ -w",
  "build:e2e": "tsc -p e2e/",
  "serve": "lite-server -c=bs-config.json",
  "serve:e2e": "lite-server -c=bs-config.e2e.json",
  "prestart": "npm run build",
  "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
  "pree2e": "npm run build:e2e",
  "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-
   others --success first",
  "preprotractor": "webdriver-manager update",
  "protractor": "protractor protractor.config.js",
  "pretest": "npm run build",
  "test": "concurrently \"npm run build:watch\" \"karma start
  karma.conf.js\"",
  "pretest:once": "npm run build",
  "test:once": "karma start karma.conf.js --single-run",
  "lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
  "@angular/common": "~2.4.0",
  "@angular/compiler": "~2.4.0",
  "@angular/core": "~2.4.0",
  "@angular/forms": "~2.4.0",
  "@angular/http": "~2.4.0",
  "@angular/platform-browser": "~2.4.0",
  "@angular/platform-browser-dynamic": "~2.4.0",
  "@angular/router": "~3.4.0",
  "angular-in-memory-web-api": "~0.2.4",
  "systemjs": "0.19.40",
  "core-js": "^2.4.1",
  "rxjs": "5.4.2",
  "zone.js": "^0.7.4"
},
"devDependencies": {
  "concurrently": "^3.2.0",
  "lite-server": "^2.2.2",
  "typescript": "^2.4.0",
  "canonical-path": "0.0.2",
  "tslint": "^3.15.1",
  "lodash": "^4.16.4",
  "jasmine-core": "~2.4.1",
  "karma": "^1.3.0",
  "karma-chrome-launcher": "^2.0.0",
  "karma-cli": "^1.0.1",
  "karma-jasmine": "^1.0.2",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~4.0.14",
  "rimraf": "^2.5.4",
  "@types/node": "^6.0.46",
  "@types/jasmine": "2.5.36"
},
"repository": {}
}
</code>```

Body:
I am pretty new to Angular2/4 and i am trying to build a WebAPI that updates a SQL table. The Issue is that when I run the Build function in Visual Studio 2015, I get error code TS2307 "Cannot find module 'rxjs/Observable'" for every one of the "d.ts" files. When I click on the error, it sends me to the Import statement in the Specified file, with the error under the "@rxjs/Observable" portion.

I have looked for a couple hours trying to find a solution and haven't found one that matches the situation, so if I duplicated something please drop a link in the comments so I can check it out.

If there are any other files you would need to help please let me know. Thank you in advance.

Here are some(as many as I could get in the screenshot)of the errors from VS15:

Here is my Package.json file:

   {
     "version": "1.0.0",
     "name": "asp.net",
     "private": true,
     "scripts": {
           "build": "webpack",
           "start": "static ."
           },
     "dependencies": {
           "@angular/core": "2.4.0",
           "@angular/common": "2.4.0",
           "@angular/compiler": "2.4.0",
           "@angular/platform-browser": "2.4.0",
           "@angular/platform-browser-dynamic": "2.4.0",
           "core-js": "^2.4.1",
           "zone.js": "^0.8.4",
           "rxjs": "^5.2.0",
           "reflect-metadata": "^0.1.10"
           },
     "devDependencies": {
          "gulp": "^3.9.1",
          "gulp-exec": "^2.1.3",
          "awesome-typescript-loader": "^3.1.2",
          "typings": "^2.1.0",
          "webpack": "^3.8.1",
          "ng2-bs3-modal": "0.10.4"
          }
      }

Here is my tsconfig.json

  {
   "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [ "es2015", "dom" ],
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true
        }
   }

UPDATE:1
I went through and lowered the angular version number in the package.json file as shown above. Then deleted the node_module from the project and restarted VS15. then I restored the packages to find a bunch more errors waiting.

So I am hoping the new batch of errors helps figure something out...

Body:
On the advice of @yms, I found the Quickstart file for the Angular2.4 and copied the package.json, tsconfig.jason and systemjs.config.js  into the solution. then i read the ReadMe file which points out that you have to use the angular/cli from now on.. so i tried installing that with the command:

npm install -g @angular/cli

my errors i was getting reduced to "incorrectly extends" error, which was fixed by pushing the typescript version to "^2.4.0" and the rxjs version to "5.4.2" in the package.json file then restoring the packages.

So here is my working Package.json:

{
"name": "angular-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented
with testing support",
"scripts": {
  "build": "tsc -p src/",
  "build:watch": "tsc -p src/ -w",
  "build:e2e": "tsc -p e2e/",
  "serve": "lite-server -c=bs-config.json",
  "serve:e2e": "lite-server -c=bs-config.e2e.json",
  "prestart": "npm run build",
  "start": "concurrently \"npm run build:watch\" \"npm run serve\"",
  "pree2e": "npm run build:e2e",
  "e2e": "concurrently \"npm run serve:e2e\" \"npm run protractor\" --kill-
   others --success first",
  "preprotractor": "webdriver-manager update",
  "protractor": "protractor protractor.config.js",
  "pretest": "npm run build",
  "test": "concurrently \"npm run build:watch\" \"karma start
  karma.conf.js\"",
  "pretest:once": "npm run build",
  "test:once": "karma start karma.conf.js --single-run",
  "lint": "tslint ./src/**/*.ts -t verbose"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
  "@angular/common": "~2.4.0",
  "@angular/compiler": "~2.4.0",
  "@angular/core": "~2.4.0",
  "@angular/forms": "~2.4.0",
  "@angular/http": "~2.4.0",
  "@angular/platform-browser": "~2.4.0",
  "@angular/platform-browser-dynamic": "~2.4.0",
  "@angular/router": "~3.4.0",
  "angular-in-memory-web-api": "~0.2.4",
  "systemjs": "0.19.40",
  "core-js": "^2.4.1",
  "rxjs": "5.4.2",
  "zone.js": "^0.7.4"
},
"devDependencies": {
  "concurrently": "^3.2.0",
  "lite-server": "^2.2.2",
  "typescript": "^2.4.0",
  "canonical-path": "0.0.2",
  "tslint": "^3.15.1",
  "lodash": "^4.16.4",
  "jasmine-core": "~2.4.1",
  "karma": "^1.3.0",
  "karma-chrome-launcher": "^2.0.0",
  "karma-cli": "^1.0.1",
  "karma-jasmine": "^1.0.2",
  "karma-jasmine-html-reporter": "^0.2.2",
  "protractor": "~4.0.14",
  "rimraf": "^2.5.4",
  "@types/node": "^6.0.46",
  "@types/jasmine": "2.5.36"
},
"repository": {}
}


来源: stackexchange

问:
Foreach loop for children skipping to last child in XML file
Okay, my script is supposed to open an XML file, recursively loop through all the tags, children, children of children, and so forth spitting out information as we go. Today I noticed an interesting bug in that my foreach loop that is supposed to loop through the children is skipping directly to the last child and I really have no clue as to why.

```<code>function theHunt($node)
{
    $tagName = '';
    print 'I am starting with ' . $node->getName() . ' It should have ' . $node->count() . ' children. The first child should be: ' . $node->children()->getName() . '<br>';

    foreach ($node->children() as $child);
    {
        print $child->getName() . '<br>';
        if (isset($child))
        {
            print 'I found: ' . $child->getName() . ' I\'ll see if it has kids' . '<br>';
            $this->theHunt($child);
        }
        else
        {
            print 'No kids here, I\'m going to stop digging.<br>';
        }
        //Now that I am all the way down or working my way back up. I start gathering my information.
        $tagName = $node -> getName();
        if($this->rootNode->$tagName[0] !== NULL)
        {
            foreach ($this->rootNode->$tagName[0]->attributes() as $a => $b) ;
            {
                //echo $a, '="', $b, "<br>";
            }
        }
        //print_r($node);
        print'<br> I kicked out <br>';

    }
}
</code>```

The really weird part is that the line:

```<code>print 'I am starting with ' . $node->getName() . ' It should have ' . $node->count() . ' children. The first child should be: ' . $node->children()->getName() . '<br>';
</code>```

Is outputting all the correct information, but the moment I drop into the foreach loop I skip right to the very last child.

答: Okay, I figured it out. Really rookie mistake. I put a semicolon after my foreach. Took it out, I'm running beautifully. </p>

ContentLicense: CC BY-SA 3.0

Body:
Okay, my script is supposed to open an XML file, recursively loop through all the tags, children, children of children, and so forth spitting out information as we go. Today I noticed an interesting bug in that my foreach loop that is supposed to loop through the children is skipping directly to the last child and I really have no clue as to why.

function theHunt($node)
{
    $tagName = '';
    print 'I am starting with ' . $node->getName() . ' It should have ' . $node->count() . ' children. The first child should be: ' . $node->children()->getName() . '
';

    foreach ($node->children() as $child);
    {
        print $child->getName() . '
';
        if (isset($child))
        {
            print 'I found: ' . $child->getName() . ' I\'ll see if it has kids' . '
';
            $this->theHunt($child);
        }
        else
        {
            print 'No kids here, I\'m going to stop digging.
';
        }
        //Now that I am all the way down or working my way back up. I start gathering my information.
        $tagName = $node -> getName();
        if($this->rootNode->$tagName[0] !== NULL)
        {
            foreach ($this->rootNode->$tagName[0]->attributes() as $a => $b) ;
            {
                //echo $a, '="', $b, "
";
            }
        }
        //print_r($node);
        print'
 I kicked out
';

    }
}

The really weird part is that the line:

print 'I am starting with ' . $node->getName() . ' It should have ' . $node->count() . ' children. The first child should be: ' . $node->children()->getName() . '
';

Is outputting all the correct information, but the moment I drop into the foreach loop I skip right to the very last child.


问:
Google sheets, if statement multiple conditions
Trying to make an if statement that will return 4 outcomes based on the contents of the cell

If the cell is "Yes", "No", "NA", "Unknown", to return 0, 1, 2, 3 respectively.

I can use  If(A1="Yes", 0,1)  but not sure how to handle the other conditions

答:
Please try:

```<code>=IF(A1="Yes",0,IF(A1="No",1,IF(A1="Unknown",3,2)))
</code>```

Anything other than the given selection in A1 (and not an error) and the formula would return 2.

Body:
Please try:

=IF(A1="Yes",0,IF(A1="No",1,IF(A1="Unknown",3,2)))

Anything other than the given selection in A1 (and not an error) and the formula would return 2.


问:
CSS and Safari/Chrome
I've been trying to modify the following menu to make it look indentical in IE, Firefox, and Safari/Chrome but I can't seem to get it to look right in Safari/Chrome.

Could anyone tell me how to fix it?  When viewed in Safari or Chrome, notice that the menu is ignoring the padding.

View flickr-like menu

Thanks in advance!

答: Try making the inline elements inline-block in order to get the padding working properly.

OwnerDisplayName: Astralis

LastEditorDisplayName: moocha

ContentLicense: CC BY-SA 2.5

Title: CSS and Safari/Chrome

OwnerDisplayName: bjeanes


问:
JS compare the order of SOME elements in two different arrays
I'm trying to figure out how to compare if certain elements in two arrays compare in the same order.

var compare = function (arr1, arr2) {
//........
}

compare ([f,t,r,m], [s,f,t,r,q,p,m]); //should return true

compare ([f,t,r,m], [f,a,t,,m,r]); //should return false```
</div>
</div>
</p>

<p>I proceeded with a for loop and then identifying when the values match, then I'm pretty sure you should compare the arrays but I feel I'm missing something.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var compare = function (a, b) {
  a.forEach(function(letter){
    for (i=0; i<b.length; i++) {
      if (letter===b[i]) {}
    }
  })
}</code>```

答:
Remove all letters from the 2nd array that don't appear in 1st array using Array#filter and Array#indexOf. Then iterate the result with Array#every, and check if every character appears in the same place in the 1st array:

function compare(a, b) {
  var arr = b.filter(function(c) {
    return a.indexOf(c) !== -1; // use a hash object instead of indexOf if the arrays are large
  });

  return arr.every(function(c, i) {
    return c === a[i];
  });
}

console.log(compare(['f','t','r','m'], ['s','f','t','r','q','p','m'])); //should return true

console.log(compare(['f','t','r','m'], ['f','a','t','m','r'])); //should return false```

Body:
I'm trying to figure out how to compare if certain elements in two arrays compare in the same order.

var compare = function (arr1, arr2) {
//........
}

compare ([f,t,r,m], [s,f,t,r,q,p,m]); //should return true

compare ([f,t,r,m], [f,a,t,,m,r]); //should return false

I proceeded with a for loop and then identifying when the values match, then I'm pretty sure you should compare the arrays but I feel I'm missing something.

var compare = function (a, b) {
  a.forEach(function(letter){
    for (i=0; i<b.length; i++) {
      if (letter===b[i]) {}
    }
  })
}


问:
ValidationError in Django Rest Framework JWT does not use custom exception handler
I am using Django Rest Framework 3.2.3 (DRF) and Django Rest Framework JWT 1.7.2 (DRF-JWT, https://github.com/GetBlimp/django-rest-framework-jwt) to create Login tokens.

I need to change the Status Code for invalid credentials when issuing a JWT from 400 to 202 (FYI: my client can't read the body of non-200 responses). I use a custom exception handler as described by Django Rest Framework to achieve it: http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

restapi/custom_exception.py

```<code>from rest_framework.views import exception_handler
from rest_framework import status

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    print ('Exception raised: ' + str(response.status_code))

    # Now add the HTTP status code to the response.
    if response is not None:
        if response.status_code != status.HTTP_403_FORBIDDEN:
            response.status_code = status.HTTP_202_ACCEPTED

    return response
</code>```

And in the config:

```<code>'EXCEPTION_HANDLER': 'restapi.custom_exception.custom_exception_handler',
</code>```

The DRF-JWT should raise ValidationError, when invalid credentials are used. I still get a 400 Bad Request response code, when posting invalid credentials to JWT token-auth interface.

With every other DRF interface I am getting the 202 status code as expected.

How can I get DRF-JWT to use the custom exception handler for their ValidationErrors?

答:
I think maybe a cleaner way to do it that doesn't involve overriding the post method is

serializers.py

```<code>from rest_framework_jwt import serializers as jwt_serializers

class JSONWebTokenSerializer(jwt_serializers.JSONWebTokenSerializer):
    """
    Override rest_framework_jwt's ObtainJSONWebToken serializer to
    force it to raise ValidationError exception if validation fails.
    """
    def is_valid(self, raise_exception=None):
        """
        If raise_exception is unset, set it to True by default
        """
        return super().is_valid(
            raise_exception=raise_exception if raise_exception is not
None else True)
</code>```

views.py

```<code>from rest_framework_jwt import views as jwt_views
from .serializers import JSONWebTokenSerializer

class ObtainJSONWebToken(jwt_views.ObtainJSONWebToken):
    """
    Override the default JWT ObtainJSONWebToken view to use the custom serializer
    """
    serializer_class = JSONWebTokenSerializer
</code>```

urls.py

```<code>from django.conf.urls import url
from .views import ObtainJSONWebToken

urlpatterns = [
    ...
    url(r'^api-token-auth/', ObtainJSONWebToken.as_view(), name='jwt-create'),
]
</code>```

Body:
I am using Django Rest Framework 3.2.3 (DRF) and Django Rest Framework JWT 1.7.2 (DRF-JWT, https://github.com/GetBlimp/django-rest-framework-jwt) to create Login tokens.

I need to change the Status Code for invalid credentials when issuing a JWT from 400 to 202 (FYI: my client can't read the body of non-200 responses). I use a custom exception handler as described by Django Rest Framework to achieve it: http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

restapi/custom_exception.py

from rest_framework.views import exception_handler
from rest_framework import status

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    print ('Exception raised: ' + str(response.status_code))

    # Now add the HTTP status code to the response.
    if response is not None:
        if response.status_code != status.HTTP_403_FORBIDDEN:
            response.status_code = status.HTTP_202_ACCEPTED

    return response

And in the config:

'EXCEPTION_HANDLER': 'restapi.custom_exception.custom_exception_handler',

The DRF-JWT should raise ValidationError, when invalid credentials are used. I still get a 400 Bad Request response code, when posting invalid credentials to JWT token-auth interface.

With every other DRF interface I am getting the 202 status code as expected.

How can I get DRF-JWT to use the custom exception handler for their ValidationErrors?

Body:
I think maybe a cleaner way to do it that doesn't involve overriding the post method is

serializers.py

from rest_framework_jwt import serializers as jwt_serializers

class JSONWebTokenSerializer(jwt_serializers.JSONWebTokenSerializer):
    """
    Override rest_framework_jwt's ObtainJSONWebToken serializer to
    force it to raise ValidationError exception if validation fails.
    """
    def is_valid(self, raise_exception=None):
        """
        If raise_exception is unset, set it to True by default
        """
        return super().is_valid(
            raise_exception=raise_exception if raise_exception is not
None else True)

views.py

from rest_framework_jwt import views as jwt_views
from .serializers import JSONWebTokenSerializer

class ObtainJSONWebToken(jwt_views.ObtainJSONWebToken):
    """
    Override the default JWT ObtainJSONWebToken view to use the custom serializer
    """
    serializer_class = JSONWebTokenSerializer

urls.py

from django.conf.urls import url
from .views import ObtainJSONWebToken

urlpatterns = [
    ...
    url(r'^api-token-auth/', ObtainJSONWebToken.as_view(), name='jwt-create'),
]


问:
flask jwt extended how to pass audience
I am trying to pass audience as a parameter in flask jwt extended for decoding jwt token, My code is like this,

```<code>@app.route('/api')
@jwt_required
def my_api():
    return json.dumps('Welcome ')
</code>```

when i call my api i am getting

```<code>{
    "msg": "Invalid audience"
}
</code>```

I know, we have to provide audience value. However i am not sure how to pass audience in jwt_required in flask_jwt_extended. Can someone help me?

答: Flask-JWT-Extended is very opinionated about that claims need to be in a token for all of the extra features to work. If you are getting your JWTs from a different provider, chances are very high that you should be using Flask-JWT-Simple instead. You can view some discussions about it here: https://github.com/vimalloc/flask-jwt-extended/issues/85</p>

Title: flask jwt extended how to pass audience

Body:
I am trying to pass audience as a parameter in flask jwt extended for decoding jwt token, My code is like this,

@app.route('/api')
@jwt_required
def my_api():
    return json.dumps('Welcome ')

when i call my api i am getting

{
    "msg": "Invalid audience"
}

I know, we have to provide audience value. However i am not sure how to pass audience in jwt_required in flask_jwt_extended. Can someone help me?


问:
How to write a bash script to give another program response
I have a bash script that does several tasks, including python manage.py syncdb on a fresh database. This command asks for input, like the login info for the admin. Currently, I just type this into the command line every time. Is there a way I can automatically provide these replies as part of the bash script?

Thanks, I don't really know anything about bash.

I'm using Ubuntu 10.10.

答:
You can do it like this, given an example login.py script:

```<code>if __name__ == '__main__':
    import sys
    user = sys.stdin.readline().strip()
    passwd = sys.stdin.readline().strip()

    if user == 'root' and passwd == 'password':
        print 'Login successful'
        sys.exit(0)

    sys.stderr.write('error: invalid username or password\n')
    sys.exit(1)
</code>```

good-credentials.txt

```<code>root
password
</code>```

bad-credentials.txt

```<code>user
foo
</code>```

Then you can do the login automatically using:

```<code>$cat good-credentials.txt | python login.py
Login successful

$cat bad-credentials.txt | python login.py
error: invalid username or password
</code>```

The down-side of this approach is you're storing your password in plain text, which isn't great practice.

Body:
You can do it like this, given an example login.py script:

if __name__ == '__main__':
    import sys
    user = sys.stdin.readline().strip()
    passwd = sys.stdin.readline().strip()

    if user == 'root' and passwd == 'password':
        print 'Login successful'
        sys.exit(0)

    sys.stderr.write('error: invalid username or password\n')
    sys.exit(1)

good-credentials.txt

root
password

bad-credentials.txt

user
foo

Then you can do the login automatically using:

$cat good-credentials.txt | python login.py
Login successful

$cat bad-credentials.txt | python login.py
error: invalid username or password

The down-side of this approach is you're storing your password in plain text, which isn't great practice.


问:
How to limit an else statement? - Javascript game
I'm looking for an explanation on how I would properly implement a 'button' (square) that you would stand on, which would change the background color. I've successfully implemented the if statement, which changes the background, but when I add an else statement to change it back to normal when you are not on the button, it runs repeatedly without stopping.

The same goes for another obstacle I have that makes you move slower when standing on it. When you're not on the obstacle, it's constantly changing the variable rather than changing it back once.

var gravity = 30;
var jumpSpeed = 17;
var playerYSpeed = 7;

Player.prototype.moveY = function(step, level, keys, pos) {
  this.speed.y += step * gravity;
  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);
  var lastObstacle = null;

  if (obstacle) {
      if (keys.up && this.speed.y > 0)
        this.speed.y = -jumpSpeed;
      else
        this.speed.y = 0;
    } else {
      this.pos = newPos;
    }
  if (obstacle === "lava") {
    this.pos = new Vector(6.5, 18.5);
  }
  if (obstacle === "bouncer") {
    this.pos = newPos + 20;
    console.log('bounce');
  }
  else {
    gravity = 30;
  }
  if (obstacle === "ice") {
    playerXSpeed = 0.5;
    console.log('slow speed');
  }
  else if (obstacle !== lastObstacle){
    playerXSpeed = 7;
    console.log('norm speed');
  }
  var changeBackground = document.getElementsByClassName('background');
  if (obstacle === "blind") {
      changeBackground[0].style.background = 'white';
      console.log('purple');
    }
  else if (obstacle !== lastObstacle){
      changeBackground[0].style.background = 'blue';
      console.log('blue');
  }
};```

The 'blind' obstacle is supposed to change the background only when you are standing on it, and when you are off it's supposed to revert to normal. Same for the ice.

So how would you make this more like a 'switch on' - 'switch off' scenario?

答:
if I understand your code correctly it is in some loop function.

You could add a variable "lastObstacle" and check whether the current obstacle is different. (else if (lastObstacle !== obstacle)

var gravity = 30;
var jumpSpeed = 17;
var playerYSpeed = 7;
var lastObstacle = null;

Player.prototype.moveY = function(step, level, keys, pos) {
  this.speed.y += step * gravity;
  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);

  if (obstacle) {
      if (keys.up && this.speed.y > 0)
        this.speed.y = -jumpSpeed;
      else
        this.speed.y = 0;
    } else {
      this.pos = newPos;
    }
  if (obstacle === "lava") {
    this.pos = new Vector(6.5, 18.5);
  }
  if (obstacle === "bouncer") {
    this.pos = newPos + 20;
    console.log('bounce');
  }
  else {
    gravity = 30;
  }
  if (obstacle === "ice") {
    playerXSpeed = 0.5;
    console.log('slow speed');
  }
  else if (obstacle !== lastObstacle){
    playerXSpeed = 7;
    console.log('norm speed');
  }
  var changeBackground = document.getElementsByClassName('background');
  if (obstacle === "blind") {
      changeBackground[0].style.background = 'white';
      console.log('purple');
    }
  else if (obstacle !== lastObstacle){
      changeBackground[0].style.background = 'blue';
      console.log('blue');
  }
  lastObstacle = obstacle;
};```
</div>
</div>
</p>

<p>(comment: snippet will probaby not work.)</p>

<p>PS: I made a little mistake that i corrected now:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var gravity = 30;
var jumpSpeed = 17;
var playerYSpeed = 7;
var lastObstacle = null;

Player.prototype.moveY = function(step, level, keys, pos) {
  this.speed.y += step * gravity;
  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);

  if (obstacle) {
      if (keys.up && this.speed.y > 0)
        this.speed.y = -jumpSpeed;
      else
        this.speed.y = 0;
    } else {
      this.pos = newPos;
    }
  if (obstacle === "lava") {
    this.pos = new Vector(6.5, 18.5);
  }
  if (obstacle === "bouncer") {
    this.pos = newPos + 20;
    console.log('bounce');
  }
  else {
    gravity = 30;
  }
  if (obstacle === "ice") {
    playerXSpeed = 0.5;
    console.log('slow speed');
  }
  else if (lastObstacle === "ice"){
    playerXSpeed = 7;
    console.log('norm speed');
  }
  var changeBackground = document.getElementsByClassName('background');
  if (obstacle === "blind") {
      changeBackground[0].style.background = 'white';
      console.log('purple');
    }
  else if (lastObstacle === "blind"){
      changeBackground[0].style.background = 'blue';
      console.log('blue');
  }
  lastObstacle = obstacle;
};</code>```

I changed the two occurences of lastObstacle !== obstacle.

Edit 2: This works that way: It executes the else-if block only if you are now not on an ice/blind block and your were on an ice/blind block before.

Body:
I'm looking for an explanation on how I would properly implement a 'button' (square) that you would stand on, which would change the background color. I've successfully implemented the if statement, which changes the background, but when I add an else statement to change it back to normal when you are not on the button, it runs repeatedly without stopping.

The same goes for another obstacle I have that makes you move slower when standing on it. When you're not on the obstacle, it's constantly changing the variable rather than changing it back once.

var gravity = 30;
var jumpSpeed = 17;
var playerYSpeed = 7;

Player.prototype.moveY = function(step, level, keys, pos) {
  this.speed.y += step * gravity;
  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);
  var lastObstacle = null;

  if (obstacle) {
      if (keys.up && this.speed.y > 0)
        this.speed.y = -jumpSpeed;
      else
        this.speed.y = 0;
    } else {
      this.pos = newPos;
    }
  if (obstacle === "lava") {
    this.pos = new Vector(6.5, 18.5);
  }
  if (obstacle === "bouncer") {
    this.pos = newPos + 20;
    console.log('bounce');
  }
  else {
    gravity = 30;
  }
  if (obstacle === "ice") {
    playerXSpeed = 0.5;
    console.log('slow speed');
  }
  else if (obstacle !== lastObstacle){
    playerXSpeed = 7;
    console.log('norm speed');
  }
  var changeBackground = document.getElementsByClassName('background');
  if (obstacle === "blind") {
      changeBackground[0].style.background = 'white';
      console.log('purple');
    }
  else if (obstacle !== lastObstacle){
      changeBackground[0].style.background = 'blue';
      console.log('blue');
  }
};

The 'blind' obstacle is supposed to change the background only when you are standing on it, and when you are off it's supposed to revert to normal. Same for the ice.

So how would you make this more like a 'switch on' - 'switch off' scenario?

Body:
if I understand your code correctly it is in some loop function.

You could add a variable "lastObstacle" and check whether the current obstacle is different. (else if (lastObstacle !== obstacle)

var gravity = 30;
var jumpSpeed = 17;
var playerYSpeed = 7;
var lastObstacle = null;

Player.prototype.moveY = function(step, level, keys, pos) {
  this.speed.y += step * gravity;
  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);

  if (obstacle) {
      if (keys.up && this.speed.y > 0)
        this.speed.y = -jumpSpeed;
      else
        this.speed.y = 0;
    } else {
      this.pos = newPos;
    }
  if (obstacle === "lava") {
    this.pos = new Vector(6.5, 18.5);
  }
  if (obstacle === "bouncer") {
    this.pos = newPos + 20;
    console.log('bounce');
  }
  else {
    gravity = 30;
  }
  if (obstacle === "ice") {
    playerXSpeed = 0.5;
    console.log('slow speed');
  }
  else if (obstacle !== lastObstacle){
    playerXSpeed = 7;
    console.log('norm speed');
  }
  var changeBackground = document.getElementsByClassName('background');
  if (obstacle === "blind") {
      changeBackground[0].style.background = 'white';
      console.log('purple');
    }
  else if (obstacle !== lastObstacle){
      changeBackground[0].style.background = 'blue';
      console.log('blue');
  }
  lastObstacle = obstacle;
};

(comment: snippet will probaby not work.)

PS: I made a little mistake that i corrected now:

var gravity = 30;
var jumpSpeed = 17;
var playerYSpeed = 7;
var lastObstacle = null;

Player.prototype.moveY = function(step, level, keys, pos) {
  this.speed.y += step * gravity;
  var motion = new Vector(0, this.speed.y * step);
  var newPos = this.pos.plus(motion);
  var obstacle = level.obstacleAt(newPos, this.size);

  if (obstacle) {
      if (keys.up && this.speed.y > 0)
        this.speed.y = -jumpSpeed;
      else
        this.speed.y = 0;
    } else {
      this.pos = newPos;
    }
  if (obstacle === "lava") {
    this.pos = new Vector(6.5, 18.5);
  }
  if (obstacle === "bouncer") {
    this.pos = newPos + 20;
    console.log('bounce');
  }
  else {
    gravity = 30;
  }
  if (obstacle === "ice") {
    playerXSpeed = 0.5;
    console.log('slow speed');
  }
  else if (lastObstacle === "ice"){
    playerXSpeed = 7;
    console.log('norm speed');
  }
  var changeBackground = document.getElementsByClassName('background');
  if (obstacle === "blind") {
      changeBackground[0].style.background = 'white';
      console.log('purple');
    }
  else if (lastObstacle === "blind"){
      changeBackground[0].style.background = 'blue';
      console.log('blue');
  }
  lastObstacle = obstacle;
};

I changed the two occurences of lastObstacle !== obstacle.

Edit 2: This works that way: It executes the else-if block only if you are now not on an ice/blind block and your were on an ice/blind block before.


问:
Filtering Json with .map
I'm trying to filter this .json in order not to show private videos.
It's for a app of a youtube channel.
There are some videos that are private and I don't want to show them in the app.
I need help filtering the .json

Currently it's returning an empty json. if I remove the .map it returns the complete list of videos with the privete ones.

```<code>getPlayListVideos(listId: string) {
    return this.http.get('https://www.googleapis.com/youtube/v3/playlistItems?key=' + this.apiKey + '&fields=items/snippet/resourceId/videoId,items/snippet/publishedAt,items/snippet/title,items/snippet/thumbnails/high/url&playlistId=' + listId +'&part=snippet,id&maxResults=25')
    .map((res) => {
      return res.json()['items'].filter(item => {
        if(item.snippet.title === 'Private video'){
          return false;
        }
       });
    })
}
</code>```

答:
You need to return true if you don't want to filter the current item. Currently you're returning either false or undefined implicitly since you don't return anything in that case. So you need to do this:

```<code>if(item.snippet.title === 'Private video'){
    return false;
} else {
    return true;
}
</code>```

or better yet return item.snippet.title !== 'Private video'.

Bonus formatting - I'd write the whole thing like this personally:

```<code>  getPlayListVideos(listId: string): any[] {
       return this.http.get('https://www.googleapis.com/youtube/v3/playlistItems?key=' + this.apiKey + '&fields=items/snippet/resourceId/videoId,items/snippet/publishedAt,items/snippet/title,items/snippet/thumbnails/high/url&playlistId=' + listId + '&part=snippet,id&maxResults=25')
              .map(res => res.json()['Items'])
              .map((items: any[]) => items.filter(item => item.snippet.title !== 'Private video'))
  }
</code>```

Title: Filtering Json with .map

Body:
I'm trying to filter this .json in order not to show private videos.
It's for a app of a youtube channel.
There are some videos that are private and I don't want to show them in the app.
I need help filtering the .json

Currently it's returning an empty json. if I remove the .map it returns the complete list of videos with the privete ones.

getPlayListVideos(listId: string) {
    return this.http.get('https://www.googleapis.com/youtube/v3/playlistItems?key=' + this.apiKey + '&fields=items/snippet/resourceId/videoId,items/snippet/publishedAt,items/snippet/title,items/snippet/thumbnails/high/url&playlistId=' + listId +'&part=snippet,id&maxResults=25')
    .map((res) => {
      return res.json()['items'].filter(item => {
        if(item.snippet.title === 'Private video'){
          return false;
        }
       });
    })
}

Body:
You need to return true if you don't want to filter the current item. Currently you're returning either false or undefined implicitly since you don't return anything in that case. So you need to do this:

if(item.snippet.title === 'Private video'){
    return false;
} else {
    return true;
}

or better yet return item.snippet.title !== 'Private video'.

Bonus formatting - I'd write the whole thing like this personally:

  getPlayListVideos(listId: string): any[] {
       return this.http.get('https://www.googleapis.com/youtube/v3/playlistItems?key=' + this.apiKey + '&fields=items/snippet/resourceId/videoId,items/snippet/publishedAt,items/snippet/title,items/snippet/thumbnails/high/url&playlistId=' + listId + '&part=snippet,id&maxResults=25')
              .map(res => res.json()['Items'])
              .map((items: any[]) => items.filter(item => item.snippet.title !== 'Private video'))
  }


问:
Is it a good idea to change behavior of back button in browser?
I have a web form with multiple steps/pages (I'm using django-formwizard) that is dependent on POST requests like the typical web form. If the user presses the back button, things break.

I in this Stackoverflow post that you can stop the default behavior of the back button while it's on your own domain before it unloads the page.

I am thinking about, if the form step is greater than 1, I assume the user is trying to go back to step 1. Therefor, I ask the user to confirm, telling them of the great sin they're about to commit.

If they say yes, call a GET request to the form with step 1 (which would undo all of their input as a side effect. I would tell them about this in the confirmation).

If they say no, I would block the event they were just trying to do (go back) and stay on the current page (my form at the current step).

Is this a good idea?

I do have a "previous" and "first step" button.

This form is more of an event registration with 4 steps, all of which are self contained (you shouldn't need context of previous steps) and those that I think may possibly need it have that information displayed on the appropriate steps' pages.

答:
It may be necessary to allow a user to go back and forth between pages/tabs in an interface where you're gathering information that's to voluminous to grab on one screen.  A classic example is demographic information on a registration screen (name and address on one screen, security questions on another, next-of-kin on another).

In this case, going back one screen isn't a "sin"--it could be a UI requirement.  I do this all the time.  I have to retain the information from screen-to-screen and allow the user to review it to make sure it's correct.  Not allowing to to go back and review/correct would be a questionable design decision.  Altering the behavior of your UI in this case could be confusing to them.

Just something to think about as you go along :-)


问:
Python 2.X : Regex to find all company names ending in ".inc"
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

```<code>aa = re.findall('inc\.,? (.*?inc\.)', text)
</code>```

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

答:
In this case, you can avoid using a regex, instead try:

```<code>text.split(“,”)
</code>```

and then iterate through the list created and look for ".inc".

Body:
I'm trying to extract the company names from press releases. As an example, below there is a snippet (in French) of a press release containing a list of seven companies ending in .inc.

En effet, Revenu Québec avait des motifs raisonnables de croire que ces entreprises avaient utilisé de fausses factures provenant de plusieurs sociétés, dont Asphalte Vrac Transport inc., 9163-6704 Québec inc., Entreprise Denis Dupré inc., Gestion Jean M. Machado inc., Impact Technologie Environnementale inc., Les entreprises Luc Clément inc. et Transport Vrac Globe International inc.

I'm trying to extract all the names using the following code:

aa = re.findall('inc\.,? (.*?inc\.)', text)

I do manage to capture quite a few, but for some reason I can't figure, I can't extract them all. It seems trivial but it has stomped me for a few hours....

Any help is appreciated !

Body:
In this case, you can avoid using a regex, instead try:

text.split(“,”)

and then iterate through the list created and look for ".inc".


问:
Adding Two Numbers using Two Threads

I want to add just two numbers using two threads,but i didn't understand where i am wrong.

   My output is wrong.And i know problem is with synchronized but not able solve.

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

class GFG {
public static void main (String[] args) throws InterruptedException {
    final Addition a=new Addition();

    Thread t1 = new Thread(new Runnable()
    {
        public void run(){
            try {
               a.add(1,10);
            } catch(Exception e) {
            }
        }
    });

    Thread t2 = new Thread(new Runnable()
    {
        public void run(){
            try {
                a.add(1,4);
            } catch(Exception e) {
            }
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
}

public static class Addition{
    int a, b;
    int sum=0;
    public void add(int a, int b) throws InterruptedException{
        synchronized(this){
            for (int i=a;i<=b;i++){
                sum=sum+i;
                Thread.sleep(1000);
            }
            System.out.println("Sum="+sum);
        }
     }
  }
}
</code>```

Output:

```<code> Sum=55
 Sum=65
</code>```

And by seeing output I can say that... After completing the task of THREAD t1, THREAD t2 is adding its result to the t1...??

答:
The actual problem - beside that the code is obviously misleading on purpose - is that sum is a class member of Addition. As you're using the same instance of Addition in both threads, the state of sum is shared between the threads. That is the second thread will not start summing up with 0 but with the result of the previous addition 55. This leads to the observed output.

If you change Addition to the following the program will behave as expected.

```<code>public static class Addition {
  int a, b;

  public void add(int a, int b) throws InterruptedException {
    int sum = 0;
    synchronized (this) {
      for (int i = a; i <= b; i++) {
        sum = sum + i;
        Thread.sleep(1000);
      }
      System.out.println("Sum=" + sum);
    }
  }
}
</code>```

Title: Adding Two Numbers using Two Threads

Body:
I want to add just two numbers using two threads,but i didn't understand where i am wrong.

   My output is wrong.And i know problem is with synchronized but not able solve.

import java.io.*;

class GFG {
public static void main (String[] args) throws InterruptedException {
    final Addition a=new Addition();

    Thread t1 = new Thread(new Runnable()
    {
        public void run(){
            try {
               a.add(1,10);
            } catch(Exception e) {
            }
        }
    });

    Thread t2 = new Thread(new Runnable()
    {
        public void run(){
            try {
                a.add(1,4);
            } catch(Exception e) {
            }
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
}

public static class Addition{
    int a, b;
    int sum=0;
    public void add(int a, int b) throws InterruptedException{
        synchronized(this){
            for (int i=a;i<=b;i++){
                sum=sum+i;
                Thread.sleep(1000);
            }
            System.out.println("Sum="+sum);
        }
     }
  }
}

Output:

 Sum=55
 Sum=65

And by seeing output I can say that... After completing the task of THREAD t1, THREAD t2 is adding its result to the t1...??

Body:
The actual problem - beside that the code is obviously misleading on purpose - is that sum is a class member of Addition. As you're using the same instance of Addition in both threads, the state of sum is shared between the threads. That is the second thread will not start summing up with 0 but with the result of the previous addition 55. This leads to the observed output.

If you change Addition to the following the program will behave as expected.

public static class Addition {
  int a, b;

  public void add(int a, int b) throws InterruptedException {
    int sum = 0;
    synchronized (this) {
      for (int i = a; i <= b; i++) {
        sum = sum + i;
        Thread.sleep(1000);
      }
      System.out.println("Sum=" + sum);
    }
  }
}


问:
DJI SDK 3.3 - Create multiple threads
I want to create threads using the DJI OSDK 3.3. I located the definition of PosixThread in the file posix_thread.cpp, but since I am rather new to C++, could anyone provide me with some hints/links on how to properly create a custom thread ?

答:
You're not gated to use the posix thread apis.
You can easily use the std::thread.

Here is a small runloop-style sample.

```<code>void
RunLoop::start()
{
  this->asyncThread = std::thread(&RunLoop::asyncStart, this);
}

void
RunLoop::asyncStart()
{
  while (this->shouldRun)
  {
    // Timer's executions
    this->evaluateTimers();

    std::this_thread::sleep_for(std::chrono::milliseconds(10));
  }
}
</code>```

Title: DJI SDK 3.3 - Create multiple threads

Body:
You're not gated to use the posix thread apis.
You can easily use the std::thread.

Here is a small runloop-style sample.

void
RunLoop::start()
{
  this->asyncThread = std::thread(&RunLoop::asyncStart, this);
}

void
RunLoop::asyncStart()
{
  while (this->shouldRun)
  {
    // Timer's executions
    this->evaluateTimers();

    std::this_thread::sleep_for(std::chrono::milliseconds(10));
  }
}


问:
Divide values by lists of three and comparing elements in it
I have some values coming from sensor. My task is to divide them into lists of three elements.  If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

```<code>values = [1,3,6,8,9,11,15,17,28,29]
</code>```

I should get:

```<code>[1,3,6]
[8,9,11]
[15,17]
</code>```

I've managed to divide values by list of three:

```<code>list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)
</code>```

But I can't figure out how to compare previous and next value like the task says.

答:
You can use zip and slicing to pair consecutive elements of a list:</p>

```<code>import itertools
diff_less_than_10 = ((a - b < 10)
                     for a, b in zip(list_of_values[1:], list_of_values))
end = 1 + sum(itertools.takewhile(bool, diff_less_than_10))
groups = divide(list_of_values[:end], size)
</code>```

Body:
I have some values coming from sensor. My task is to divide them into lists of three elements.  If two consecutive elements differ by at least 10, I should ignore the rest of the list.

From this:

values = [1,3,6,8,9,11,15,17,28,29]

I should get:

[1,3,6]
[8,9,11]
[15,17]

I've managed to divide values by list of three:

list_of_values = [1,3,6,8,9,11,15,17,28,29]
def divide(values, size):
    return (values[pos:pos + size] for pos in range(0, len(values), size))
for group in divide(list_of_values, 3):
    print(group)

But I can't figure out how to compare previous and next value like the task says.

Body:
You can use zip and slicing to pair consecutive elements of a list:

import itertools
diff_less_than_10 = ((a - b < 10)
                     for a, b in zip(list_of_values[1:], list_of_values))
end = 1 + sum(itertools.takewhile(bool, diff_less_than_10))
groups = divide(list_of_values[:end], size)


问:
Google map info window blocking click events
I have implemented a InfoWindowAdapter that returns this inflated XML

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/layoutRoot"
    android:clickable="true">

    <TextView
        android:id="@+id/titleText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Medium Text"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/snippetText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>
</code>```

Which is inflated by

```<code>public class MarkerWindowProvider implements InfoWindowAdapter {
    private LayoutInflater lInflater;
    private InfoWindowClickListener onClick;

    public MarkerWindowProvider(Context parent, InfoWindowClickListener onClick) {
        lInflater = (LayoutInflater) parent.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.onClick = onClick;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public View getInfoWindow(final Marker marker) {
        View contents = lInflater.inflate(R.layout.custom_infowindow, null);
        ((TextView)contents.findViewById(R.id.titleText)).setText(marker.getTitle());
        ((TextView)contents.findViewById(R.id.snippetText)).setText(marker.getTitle());
        contents.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onClick.onClick(marker);
            }
        });
        return contents;
    }

    public interface InfoWindowClickListener {
        public void onClick(Marker marker);
    }
}
</code>```

The inflated layout is displayed instead of the stock info window but the OnClick method never fires regardless of which method i choose to inflate the XML into.

I really need this functionality. Any ideas on why this is not working? Any alternatives?
Thanks.

答:
It's said, that you can NOT handle any events from views inside your info window. This popup is not a "live" view, you even can't disable default background selector (to block blinking). Unfortunately.
So it's not recommended to put buttons and text views for input.</p>

Body:
I have implemented a InfoWindowAdapter that returns this inflated XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/layoutRoot"
    android:clickable="true">

    <TextView
        android:id="@+id/titleText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Medium Text"
        android:textStyle="bold"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/snippetText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Medium Text"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Which is inflated by

public class MarkerWindowProvider implements InfoWindowAdapter {
    private LayoutInflater lInflater;
    private InfoWindowClickListener onClick;

    public MarkerWindowProvider(Context parent, InfoWindowClickListener onClick) {
        lInflater = (LayoutInflater) parent.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.onClick = onClick;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    @Override
    public View getInfoWindow(final Marker marker) {
        View contents = lInflater.inflate(R.layout.custom_infowindow, null);
        ((TextView)contents.findViewById(R.id.titleText)).setText(marker.getTitle());
        ((TextView)contents.findViewById(R.id.snippetText)).setText(marker.getTitle());
        contents.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onClick.onClick(marker);
            }
        });
        return contents;
    }

    public interface InfoWindowClickListener {
        public void onClick(Marker marker);
    }
}

The inflated layout is displayed instead of the stock info window but the OnClick method never fires regardless of which method i choose to inflate the XML into.

I really need this functionality. Any ideas on why this is not working? Any alternatives?
Thanks.


问:
Can I join the same 2 dataframe twice using PySpark?
I am using pySpark right now. I have 2 table right now. I want to join them twice as shown below.

```
Table 1 (df1)

<b>sell_product   sell_amount    buy_product   buy_amount</b>

apple              2            pineapple        3
pear               1            apple            4
orange             5            apple            2
```

```
Table 2 (df2)

<b>product   price    </b>

apple           $1
pear            $2
orange          $3
pineapple       $4
```

```
Result Table

<b>sell_product   sell_amount    sell_price        buy_product   buy_amount    buy_price</b>

apple              2                 $1               pineapple        3       $4
pear               1                 $2               apple            4       $1
orange             5                 $3               apple            2       $1
```

```<code>df_firstjoin= df1.join(df2.select(col('price').alias('sell_price')),'sell_product'=='product','inner')

df_twice= df1.firstjoin(df2.select(col('price').alias('buy_price')),'buy_product'=='product','inner')
</code>```

I am wondering if there is any way that I can join them at the same time. Thanks.

答:
If you want to add two 'price' columns I see no way to do that with one join, because you are using different keys in df1 (sell_product and buy_product). The only solution I can think of is not creating a new df, but do this in a single pipeline.</p>

```<code>result = df1\
.join(df2.select(col('price').alias('sell_price')),'sell_product'=='product','inner')
.join(df2.select(col('price').alias('buy_price')),'buy_product'=='product','inner')
</code>```

Body:
I am using pySpark right now. I have 2 table right now. I want to join them twice as shown below.

Table 1 (df1)

sell_product   sell_amount    buy_product   buy_amount

apple              2            pineapple        3
pear               1            apple            4
orange             5            apple            2

Table 2 (df2)

product   price

apple           $1
pear            $2
orange          $3
pineapple       $4

Result Table

sell_product   sell_amount    sell_price        buy_product   buy_amount    buy_price

apple              2                 $1               pineapple        3       $4
pear               1                 $2               apple            4       $1
orange             5                 $3               apple            2       $1

df_firstjoin= df1.join(df2.select(col('price').alias('sell_price')),'sell_product'=='product','inner')

df_twice= df1.firstjoin(df2.select(col('price').alias('buy_price')),'buy_product'=='product','inner')

I am wondering if there is any way that I can join them at the same time. Thanks.

Body:
If you want to add two 'price' columns I see no way to do that with one join, because you are using different keys in df1 (sell_product and buy_product). The only solution I can think of is not creating a new df, but do this in a single pipeline.

result = df1\
.join(df2.select(col('price').alias('sell_price')),'sell_product'=='product','inner')
.join(df2.select(col('price').alias('buy_price')),'buy_product'=='product','inner')


问:
php remove from array if property value is in another array
I want to remove all elements from arr2 that have a type contained in arr1:

```<code>    arr1 = ['A', 'B', 'C']

    arr2 = [
        [
        'name' => 'jane',
        'type' => 'X'
        ],
        [
        'name' => 'jon',
        'type' => 'B'
        ]
    ]
</code>```

So jon should be removed. Is there some built in function like array_diff?

答:
Foreach the 2nd array and check if the type is in arr1. If so then simply delete(unset) it.</p>

```<code>foreach(array_keys(arr2) as $Key) {
   if (in_array(arr2[$Key]['type'],arr1)) { unset(arr2[$Key]); }
}
</code>```

Body:
I want to remove all elements from arr2 that have a type contained in arr1:

    arr1 = ['A', 'B', 'C']

    arr2 = [
        [
        'name' => 'jane',
        'type' => 'X'
        ],
        [
        'name' => 'jon',
        'type' => 'B'
        ]
    ]

So jon should be removed. Is there some built in function like array_diff?

Body:
Foreach the 2nd array and check if the type is in arr1. If so then simply delete(unset) it.

foreach(array_keys(arr2) as $Key) {
   if (in_array(arr2[$Key]['type'],arr1)) { unset(arr2[$Key]); }
}


问:
What Happens to Non-Awaited Tasks In Try/Catch Block
What happens when a method returns a Task that is contained in a try/catch block? If that non-awaited Task throws an exception, is the exception caught/handled?

For example, if DoSomethingAsync() throws an exception, can I handle it in the try/catch block in TryCatchMethod()?

```<code>Task TryCatchMethod()
{
    try
    {
        return DoSomethingAsync();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}

async Task DoSomethingAsync()
{
   await Task.Delay(10000);
   throw new System.Exception();
}
</code>```

答:
Exception will be thrown when you access result of task execution with await task, task.Result or task Wait().

In your case, if exception is thrown inside a task within DoSomethingAsync(), it will not be caught by TryCatchMethod() but will be caught by an outer method that awaits on the task returned by TryCatchMethod().

Check for more details: Exception Handling (Task Parallel Library)

ContentLicense: CC BY-SA 4.0

Body:
What happens when a method returns a Task that is contained in a try/catch block? If that non-awaited Task throws an exception, is the exception caught/handled?

For example, if DoSomethingAsync() throws an exception, can I handle it in the try/catch block in TryCatchMethod()?

Task TryCatchMethod()
{
    try
    {
        return DoSomethingAsync();
    }
    catch(Exception e)
    {
        //Handle Exception
    }
}

async Task DoSomethingAsync()
{
   await Task.Delay(10000);
   throw new System.Exception();
}


答:
Both of these functions will do this comparison with a O(n) runtime, where Ori Drori's solution runs in O(n^2)

var a = [1,2,3];
var b = [0,1,4,3,9,10,2,5,6]; // 1,2,3 in wrong order
var c = [0,4,1,5,6,2,8,3,5];  // 1,2,3 in right order

// using foreach
function compare(a,b){
  var i = 0;
  b.forEach(function(el){
    if(el == a[i]) i++;
  })
  return i == a.length;
}

// using reduce
function compare2(a,b){
  return b.reduce(function(i, el){
    return el == a[i] ? i + 1 : i;
  }, 0) == a.length;
}

console.log(compare(a,b)  ==  false);  // should be false
console.log(compare(a,c)  ==  true);   // should be true
console.log(compare2(a,b) ==  false);  // should be false
console.log(compare2(a,c) ==  true);   // should be true```

Title: JS compare the order of SOME elements in two different arrays

Body:
I'm trying to figure out how to compare if certain elements in two arrays compare in the same order.

var compare = function (arr1, arr2) {
//........
}

compare ([f,t,r,m], [s,f,t,r,q,p,m]); //should return true

compare ([f,t,r,m], [f,a,t,,m,r]); //should return false

I proceeded with a for loop and then identifying when the values match, then I'm pretty sure you should compare the arrays but I feel I'm missing something.

var compare = function (a, b) {
  a.forEach(function(letter){
    for (i=0; i<b.length; i++) {
      if (letter===b[i]) {}
    }
  })
}


问:
Use strings in .resw File directly in XAML
I know the usual way to reference localized strings from a .resw file would be like this:

XAML:

```<code><Button x:Uid="ButtonUid" />
</code>```

Resources.resw:

```<code>ButtonUid.Content = "Hello World"
</code>```

But is it also possible to kind of do it like this:

XAML (pseudo code):

```<code><Button Content = "$buttonLabel" />
</code>```

Resources.resw:

```<code>buttonLabel = "Hello World"
</code>```

The reason why I want to do it like in the second exapmle is because this is an app that I'm porting from iOS and Android to WP. I'd like to convert the iOS or Android strings file to .resw syntax but without going over every single string and adding .Content or .Text or whatever it is used for. Is there an easy solution for that?

答:
You can use a CustomXamlResourceLoader:

```<code>public class XamlResourceLoader : CustomXamlResourceLoader
{
    private readonly ResourceLoader _loader;

    public XamlResourceLoader()
    {
        _loader = ResourceLoader.GetForViewIndependentUse();
    }

    protected override object GetResource(string resourceId, string objectType, string propertyName, string propertyType)
    {
        return _loader.GetString(resourceId) ?? resourceId;
    }
}
</code>```

Then in your App.xaml.cs constructor:

CustomXamlResourceLoader.Current = new XamlResourceLoader();

And finally in your xaml:

<Button Content = "{CustomResource buttonLabel}" />

Body:
I know the usual way to reference localized strings from a .resw file would be like this:

XAML:

<Button x:Uid="ButtonUid" />

Resources.resw:

ButtonUid.Content = "Hello World"

But is it also possible to kind of do it like this:

XAML (pseudo code):

<Button Content = "$buttonLabel" />

Resources.resw:

buttonLabel = "Hello World"

The reason why I want to do it like in the second exapmle is because this is an app that I'm porting from iOS and Android to WP. I'd like to convert the iOS or Android strings file to .resw syntax but without going over every single string and adding .Content or .Text or whatever it is used for. Is there an easy solution for that?

Body:
You can use a CustomXamlResourceLoader:

public class XamlResourceLoader : CustomXamlResourceLoader
{
    private readonly ResourceLoader _loader;

    public XamlResourceLoader()
    {
        _loader = ResourceLoader.GetForViewIndependentUse();
    }

    protected override object GetResource(string resourceId, string objectType, string propertyName, string propertyType)
    {
        return _loader.GetString(resourceId) ?? resourceId;
    }
}

Then in your App.xaml.cs constructor:

CustomXamlResourceLoader.Current = new XamlResourceLoader();

And finally in your xaml:

<Button Content = "{CustomResource buttonLabel}" />


问:
How do I view Transaction Assistant entries with the Kronos API?
I want to use the Kronos Workforce Central API to view and edit queries in the Kronos Transaction Assistant.

I can login to Kronos by submitting an XML login request to /wfc/XmlService, but I haven't found any documentation for accessing the Transaction Assistant.

<Kronos_WFC version = '1.0'>
    <Request
        Object = 'System'
        Action = 'Logon'
        Username = 'SomeUsername'
        Password = 'SomePassword'
     />
</Kronos_WFC>
```

How do I retrieve Transaction Manager entries in Kronos WFC v6.3 with the Kronos API?

答:
According to the Workforce Central v6.3 Timekeeping Developer's Guide (login required), you can retrieved failed XML transactions from the Transaction Assistant with <FailedXMLTransaction>.

FailedXMLTransaction Tag

The FailedXMLTransaction tag provides information about an XML transaction
  that has failed an attempt to process an XML request. It is used to retrieve or modify failed XML transaction information.

Note: This tag provides information for the Transaction Assistant.

You can use the Load action to view entries from the Transaction manager.

Load

Returns all failed transactions for the specified SourceName and
  TransactionType. You must specify at least one of these properties
  with the Load action; if you do not, an error is returned.

Return Value Type: Zero or more FailedXMLTransaction tags

Optional Properties: SourceName, TransactionType

The XML request below retrieves failed Pay Code Edits that were submitted by the Workforce Integration Manager.

```<code><Kronos_WFC version='1.0'>
    <Request Action='Load'>
        <FailedXMLTransaction SourceName='WIM' TransactionType='Pay Code Edits'/>
    <Request>
</Kronos_WFC>
</code>```

As for editing transactions, I unfortunately couldn't find any way to do this with the XML API in v6.3.

Body:
I want to use the Kronos Workforce Central API to view and edit queries in the Kronos Transaction Assistant.

I can login to Kronos by submitting an XML login request to /wfc/XmlService, but I haven't found any documentation for accessing the Transaction Assistant.

<Kronos_WFC version = '1.0'>
    <Request
        Object = 'System'
        Action = 'Logon'
        Username = 'SomeUsername'
        Password = 'SomePassword'
     />
</Kronos_WFC>

How do I retrieve Transaction Manager entries in Kronos WFC v6.3 with the Kronos API?

Body:
According to the Workforce Central v6.3 Timekeeping Developer's Guide (login required), you can retrieved failed XML transactions from the Transaction Assistant with <FailedXMLTransaction>.

FailedXMLTransaction Tag

The FailedXMLTransaction tag provides information about an XML transaction
  that has failed an attempt to process an XML request. It is used to retrieve or modify failed XML transaction information.

Note: This tag provides information for the Transaction Assistant.

You can use the Load action to view entries from the Transaction manager.

Load

Returns all failed transactions for the specified SourceName and
  TransactionType. You must specify at least one of these properties
  with the Load action; if you do not, an error is returned.

Return Value Type: Zero or more FailedXMLTransaction tags

Optional Properties: SourceName, TransactionType

The XML request below retrieves failed Pay Code Edits that were submitted by the Workforce Integration Manager.

<Kronos_WFC version='1.0'>
    <Request Action='Load'>
        <FailedXMLTransaction SourceName='WIM' TransactionType='Pay Code Edits'/>
    <Request>
</Kronos_WFC>

As for editing transactions, I unfortunately couldn't find any way to do this with the XML API in v6.3.


问:
Useful Binary Diff Tool (other than msdn[apatch and mpatch], xdelta, bsdiff, vbindiff and winmerge)
I need a binary diff tool that can produce a patch file from compared 8MB files (.dat compressed files) and can merge produced said patch file to the older .dat file (size 8MB).

I tried using msdn's apatch and mpatch, but mpatch produces 7MB diff or patch file when differentiating two 8MB files, when supposedly, the said patch file should be of size 1MB. Another issue is that, when merging said patch file to another .dat file (35MB), it takes above an hour or so but the apatch exe still won't produce a new .dat file.

I used xdelta but issues concerning file size also came up.

Can't use WinMerga as because I'm using .dat files and can't also use vbindiff coz it's just to display difference between files.

anyone knows other binary patch tools?

Thanks very much.

答:
StackOverflow: "Best Diff Tool?" mentions a bunch of binary patch utilities.

StackOverflow: "Binary diff and patch utility" mentions a few more binary patch utilities.

StackOverflow: "Binary diff tool?" mentions yet more binary patch utilities.

But I think you will have the same problem with all of them:

With most compression tools, the "first part" of the two compressed files will be identical, up to the point where the first change occurred.
The "last part" of the two compressed files will be completely different.
Any diff tool (that doesn't cheat by recognizing the files as a compressed file and decompress them) will create a patch file that is more-or-less a bulk copy of the "last part" of the new file.
In your case, the "last part" of the new file is apparently about 7 MB long.

"supposedly, the said patch file should be of size 1MB." How could you possibly know that?

Given two compressed files, a diff utility will generate a patch file that is not much smaller than those files.

As Liam said, you need to diff the original versions of these files before compressing.
Or equivalently, you need to decompress your .dat files into temporary files, and diff those temporary files.

(Optionally, you could use any arbitrary data compression utility to compress your patch files).

I can't tell you how to decompress your .dat files, because I don't know which one of the many kinds of .dat files you have.


问:
Deploy Rails app using capstrano from inside a docker container
I managed to dockerize my rails application for development and it works great. Before this I had a deploy setup using Capistrano. Now I would like to try and deploy using the same Capistrano but executed from within the docker container. My question is can i use the same ssh key from my host machine or should I generate a new key inside the container? The last option does not sound good to me since it would have to be recreated when the container gets destroyed. I am aware that in the long run I would probably be better off setting the production server to run docker and install through docker machine but so far I just like to keep the setup I have already on production.

Anyone else have tried this?

答: I think you should link your devices ssh key into the container (as long as the container is not accessible from network). Additionally to your argument, you can more easily share your image with others as they are able to just link their key themselves.</p>


问:
Python3, how to install numpy on CentOS 7?
I'm working with Python 3.5.1 on a computer having CentOS Linux release 7.3.1611 (Core) operating system.

I have to install the numpy package.

I tried to follow these instructions, by running the command:

```<code>sudo yum -y install python34-setuptools
</code>```

Unfortunately, I got the following error:

```<code>Transaction check error:
  file /usr/lib64/libpython3.so from install of python34-libs-3.4.5-4.el7.x86_64 conflicts with file from package python3-libs-3.3.2-12.el7.nux.x86_64
</code>```

Any idea on how to solve this problem? Thanks

EDIT: On my machine, I have both Python2.7 and Python3.5, and I want to keep them both

答:
They should come pre-compiled with Centos OS, so try with:

sudo yum install numpy scipy.

So you have two option fist one is installing it system wide, like I mentioned they are pre-compiled with Centos OS, so you can Install the complete scipy packages with numpy like this:

sudo yum install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose

Or you can use pip for the installation, like this:

python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose

Please read the official docs from scipy organization on how to install all the packages on you system.

NOTE:

You are right that system wide installation will install it only for python2.7, so to use it for python3.5 you will install via pip, so do this:

sudo python3 -m pip install --upgrade pip

sudo python3 -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose

and I suggest that you install all of this packages, after the installation I've opened my terminal and I've did this:

```<code>copser@copser-LIFEBOOK-S751:~$ python3.5
Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> import numpy as np
>>> import numpy.f2py as myf2py
>>>
</code>```

as you can see I've imported numpy inside python3.5.2 and it is working, I'm using Ubuntu 16.04 it should be the same on Centos OS.

Body:
I'm working with Python 3.5.1 on a computer having CentOS Linux release 7.3.1611 (Core) operating system.

I have to install the numpy package.

I tried to follow these instructions, by running the command:

sudo yum -y install python34-setuptools

Unfortunately, I got the following error:

Transaction check error:
  file /usr/lib64/libpython3.so from install of python34-libs-3.4.5-4.el7.x86_64 conflicts with file from package python3-libs-3.3.2-12.el7.nux.x86_64

Any idea on how to solve this problem? Thanks

EDIT: On my machine, I have both Python2.7 and Python3.5, and I want to keep them both

Body:
They should come pre-compiled with Centos OS, so try with:

sudo yum install numpy scipy.

So you have two option fist one is installing it system wide, like I mentioned they are pre-compiled with Centos OS, so you can Install the complete scipy packages with numpy like this:

sudo yum install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose

Or you can use pip for the installation, like this:

python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose

Please read the official docs from scipy organization on how to install all the packages on you system.

NOTE:

You are right that system wide installation will install it only for python2.7, so to use it for python3.5 you will install via pip, so do this:

sudo python3 -m pip install --upgrade pip

sudo python3 -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose

and I suggest that you install all of this packages, after the installation I've opened my terminal and I've did this:

copser@copser-LIFEBOOK-S751:~$ python3.5
Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> import numpy as np
>>> import numpy.f2py as myf2py
>>>

as you can see I've imported numpy inside python3.5.2 and it is working, I'm using Ubuntu 16.04 it should be the same on Centos OS.


答: The exception is thrown when the task is awaited. The compiler generated code when a task is awaited with the await key word cleverly unwraps the exceptions and throws them how you would expect with a reasonably sensible stack trace. It is also thrown if you access the result of the task or call wait but it's then thrown as an aggregate exception and this isn't the best practice. If you never await the task the exception eventually becomes an unoberserved  task exception and can be fatal to your program and also has a rubbish stack trace </p>

Title: What Happens to Non-Awaited Tasks In Try/Catch Block


问:
Choose two different years joined employees from table
In oracle for informatica, I am using the condition to_char(hiredate, 'YYYY')=1981 and it is showing me all 1981 employees, if I want to see 1981 and 1982 employees together, which code is required?

答:
Querying for a Set of Years on Date Column

One could create a condition where you could cast the hiredate as a char and look for a set of years as follows:

```<code>SELECT
    *
FROM
    emp
WHERE
    TO_CHAR(hiredate,'YYYY') in ('1981', '1982')
    ;
</code>```

This works for a small set of records fairly well.

For a larger, non-trivial set of records, especially when there maybe an index on the DATE column, I personally would choose a condition on the DATE itself:

```<code>SELECT
    *
FROM
    emp
WHERE
    hiredate >= TO_DATE('01-JAN-1981','DD-MON-YYYY')
    AND   hiredate < TO_DATE('01-JAN-1983','DD-MON-YYYY')
    ;
</code>```

Here, I make sure I capture all hiredate values in 1981 by using the >= operator and I get all 1982 records by indicating that the hiredate be less than the first date in 1983.

Body:
Querying for a Set of Years on Date Column

One could create a condition where you could cast the hiredate as a char and look for a set of years as follows:

SELECT
    *
FROM
    emp
WHERE
    TO_CHAR(hiredate,'YYYY') in ('1981', '1982')
    ;

This works for a small set of records fairly well.

For a larger, non-trivial set of records, especially when there maybe an index on the DATE column, I personally would choose a condition on the DATE itself:

SELECT
    *
FROM
    emp
WHERE
    hiredate >= TO_DATE('01-JAN-1981','DD-MON-YYYY')
    AND   hiredate < TO_DATE('01-JAN-1983','DD-MON-YYYY')
    ;

Here, I make sure I capture all hiredate values in 1981 by using the >= operator and I get all 1982 records by indicating that the hiredate be less than the first date in 1983.


问:
Efficiently convert an unsigned short to a char*
What would be an efficient, portable way to convert a unsigned short to a char* (i.e. convert 25 to '25').

I'd like to avoid things such as getting (std::string) strings involved.  Performance is important in this case since this conversion will need to happen quickly and often.

I was looking into things such as using sprintf but would like to explorer any and all ideas.

答:
I hacked together a test of various functions here, and this is what I came up with:

write_ushort: 7.81 s

uShortToStr: 8.16 s

convert: 6.71 s

use_sprintf: 49.66 s

(Write_ushort is my version, which I tried to write as clearly as possible, rather than micro-optimize, to format into a given character buffer; use_sprintf is the obvious sprintf(buf, "%d", x) and nothing else; the other two are taken from other answers here.)

This is a pretty amazing difference between them, isn't it?  Who would ever think to use sprintf faced with almost an order of magnitude difference?  Oh, yeah, how many times did I iterate each tested function?

```<code>// Taken directly from my hacked up test, but should be clear.
// Compiled with gcc 4.4.3 and -O2.  This test is interesting, but not authoritative.
int main() {
  using namespace std;
  char buf[100];

#define G2(NAME,STMT) \
  { \
    clock_t begin = clock(); \
    for (int count = 0; count < 3000; ++count) { \
      for (unsigned x = 0; x <= USHRT_MAX; ++x) { \
        NAME(x, buf, sizeof buf); \
      } \
    } \
    clock_t end = clock(); \
    STMT \
  }
#define G(NAME) G2(NAME,) G2(NAME,cout << #NAME ": " << double(end - begin) / CLOCKS_PER_SEC << " s\n";)
  G(write_ushort)
  G(uShortToStr)
  G(convert)
  G(use_sprintf)
#undef G
#undef G2

  return 0;
}
</code>```

Sprintf converted the entire possible range of unsigned shorts, then did the whole range again 2,999 more times at about 0.25 µs per conversion, on average, on my ~5 year old laptop.

Sprintf is portable; is it also efficient enough for your requirements?

My version:

```<code>// Returns number of non-null bytes written, or would be written.
// If ret is null, does not write anything; otherwise retlen is the length of
// ret, and must include space for the number plus a terminating null.
int write_ushort(unsigned short x, char *ret, int retlen) {
  assert(!ret || retlen >= 1);

  char s[uint_width_10<USHRT_MAX>::value];  // easy implementation agnosticism
  char *n = s;
  if (x == 0) {
    *n++ = '0';
  }
  else while (x != 0) {
    *n++ = '0' + x % 10;
    x /= 10;
  }

  int const digits = n - s;
  if (ret) {
    // not needed by checking retlen and only writing to available space
    //assert(retlen >= digits + 1);

    while (--retlen && n != s) {
      *ret++ = *--n;
    }
    *ret = '\0';
  }
  return digits;
}
</code>```

Compile-time log TMP functions are nothing new, but including this complete example because it's what I used:

```<code>template<unsigned N>
struct uint_width_10_nonzero {
  enum { value = uint_width_10_nonzero<N/10>::value + 1 };
};
template<>
struct uint_width_10_nonzero<0> {
  enum { value = 0 };
};
template<unsigned N>
struct uint_width_10 {
  enum { value = uint_width_10_nonzero<N>::value };
};
template<>
struct uint_width_10<0> {
  enum { value = 1 };
};
</code>```

Body:
I hacked together a test of various functions here, and this is what I came up with:

write_ushort: 7.81 s

uShortToStr: 8.16 s

convert: 6.71 s

use_sprintf: 49.66 s

(Write_ushort is my version, which I tried to write as clearly as possible, rather than micro-optimize, to format into a given character buffer; use_sprintf is the obvious sprintf(buf, "%d", x) and nothing else; the other two are taken from other answers here.)

This is a pretty amazing difference between them, isn't it?  Who would ever think to use sprintf faced with almost an order of magnitude difference?  Oh, yeah, how many times did I iterate each tested function?

// Taken directly from my hacked up test, but should be clear.
// Compiled with gcc 4.4.3 and -O2.  This test is interesting, but not authoritative.
int main() {
  using namespace std;
  char buf[100];

#define G2(NAME,STMT) \
  { \
    clock_t begin = clock(); \
    for (int count = 0; count < 3000; ++count) { \
      for (unsigned x = 0; x <= USHRT_MAX; ++x) { \
        NAME(x, buf, sizeof buf); \
      } \
    } \
    clock_t end = clock(); \
    STMT \
  }
#define G(NAME) G2(NAME,) G2(NAME,cout << #NAME ": " << double(end - begin) / CLOCKS_PER_SEC << " s\n";)
  G(write_ushort)
  G(uShortToStr)
  G(convert)
  G(use_sprintf)
#undef G
#undef G2

  return 0;
}

Sprintf converted the entire possible range of unsigned shorts, then did the whole range again 2,999 more times at about 0.25 µs per conversion, on average, on my ~5 year old laptop.

Sprintf is portable; is it also efficient enough for your requirements?

My version:

// Returns number of non-null bytes written, or would be written.
// If ret is null, does not write anything; otherwise retlen is the length of
// ret, and must include space for the number plus a terminating null.
int write_ushort(unsigned short x, char *ret, int retlen) {
  assert(!ret || retlen >= 1);

  char s[uint_width_10<USHRT_MAX>::value];  // easy implementation agnosticism
  char *n = s;
  if (x == 0) {
    *n++ = '0';
  }
  else while (x != 0) {
    *n++ = '0' + x % 10;
    x /= 10;
  }

  int const digits = n - s;
  if (ret) {
    // not needed by checking retlen and only writing to available space
    //assert(retlen >= digits + 1);

    while (--retlen && n != s) {
      *ret++ = *--n;
    }
    *ret = '\0';
  }
  return digits;
}

Compile-time log TMP functions are nothing new, but including this complete example because it's what I used:

template<unsigned N>
struct uint_width_10_nonzero {
  enum { value = uint_width_10_nonzero<N/10>::value + 1 };
};
template<>
struct uint_width_10_nonzero<0> {
  enum { value = 0 };
};
template<unsigned N>
struct uint_width_10 {
  enum { value = uint_width_10_nonzero<N>::value };
};
template<>
struct uint_width_10<0> {
  enum { value = 1 };
};


答: You are using the same instance of Addition: "a" and although the Addition's global variables "a" and "b" are hidden but "sum" is not.

Title: Adding Two Numbers using Two Threads

Body:
I want to add just two numbers using two threads,but i didn't understand where i am wrong.

   My output is wrong.And i know problem is with synchronized but not able solve.

import java.io.*;

class GFG {
public static void main (String[] args) throws InterruptedException {
    final Addition a=new Addition();

    Thread t1 = new Thread(new Runnable()
    {
        public void run(){
            try {
               a.add(1,10);
            } catch(Exception e) {
            }
        }
    });

    Thread t2 = new Thread(new Runnable()
    {
        public void run(){
            try {
                a.add(1,4);
            } catch(Exception e) {
            }
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();
}

public static class Addition{
    int a, b;
    int sum=0;
    public void add(int a, int b) throws InterruptedException{
        synchronized(this){
            for (int i=a;i<=b;i++){
                sum=sum+i;
                Thread.sleep(1000);
            }
            System.out.println("Sum="+sum);
        }
     }
  }
}

Output:

 Sum=55
 Sum=65

And by seeing output I can say that... After completing the task of THREAD t1, THREAD t2 is adding its result to the t1...??


问:
How to specify table for inserting data using peewee?
I use the following code to inserting data in DB:

```<code>db = dbConnection("localhost", "root", "")

class Products(peewee.Model):
    article = peewee.TextField()
    name = peewee.TextField()
    price = peewee.TextField()
    price_distributor = peewee.TextField()
    price_discount = peewee.TextField()

    class Meta:
        database = db

Products.create_table()
book = Products(article="1", name="2", price="3", price_distributor="4", price_discount="5")
book.save()
</code>```

And connection function:

```<code>def dbConnection(host, user, password):
    return peewee.MySQLDatabase("test", host=host, port=3306, user=user, passwd=password)
</code>```

How to set table name in which I insert data?

答:
If you take a look at the docs on peewee model options

There is an option you can specify in class Meta called db_table which is the name of the table to store data.

Body:
I use the following code to inserting data in DB:

db = dbConnection("localhost", "root", "")

class Products(peewee.Model):
    article = peewee.TextField()
    name = peewee.TextField()
    price = peewee.TextField()
    price_distributor = peewee.TextField()
    price_discount = peewee.TextField()

    class Meta:
        database = db

Products.create_table()
book = Products(article="1", name="2", price="3", price_distributor="4", price_discount="5")
book.save()

And connection function:

def dbConnection(host, user, password):
    return peewee.MySQLDatabase("test", host=host, port=3306, user=user, passwd=password)

How to set table name in which I insert data?


问:
Is there any way to deploy only one project in tomcat leaving the other projects
I have multiple projects on my tomcat web-apps directory. When I start the tomcat then all the projects are deploying and it is taking time to deploy all the projects. Is there any way to deploy only one project and rest of the projects should not be deployed. I dont want to remove all files expect the file which needs to be deployed because all the files are connected to eclipse. Is there any way like commenting the projects so they will not deploy. </p>

答:
If you are working on eclipse:

Export all your applications as .war and drop them on
<TOMCAT_DIR>/webapps

Start Tomcat with <TOMCAT_DIR>/bin/startup and let it deploy your applications.

Remove the .war files of the applications you are not
changing so the server will not redeploy all your applications.

Use Eclipse to deploy the application you are working on, from the Tomcat add and remove option you should only add the application you are working on.


问:
Django counter in loop to index list
I'm passing two lists to a template.  Normally if I was iterating over a list I would do something like this

```<code>{% for i in list %}
</code>```

but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list.  My thought was to loop over one list and access an item in the other list using forloop.counter0 but I can't figure out the syntax to get that to work.

Thanks

答:
Sounds like you're looking for my django-multiforloop. From the README:

Rendering this template

```<code>{% load multifor %}
{% for x in x_list; y in y_list %}
  {{ x }}:{{ y }}
{% endfor %}
</code>```

with this context

```<code>context = {
    "x_list": ('one', 1, 'carrot'),
    "y_list": ('two', 2, 'orange')
}
</code>```

will output

```<code>one:two
1:2
carrot:orange
</code>```

Title: Django counter in loop to index list

Body:
I'm passing two lists to a template.  Normally if I was iterating over a list I would do something like this

{% for i in list %}

but I have two lists that I need to access in parallel, ie. the nth item in one list corresponds to the nth item in the other list.  My thought was to loop over one list and access an item in the other list using forloop.counter0 but I can't figure out the syntax to get that to work.

Thanks

Body:
Sounds like you're looking for my django-multiforloop. From the README:

Rendering this template

{% load multifor %}
{% for x in x_list; y in y_list %}
  {{ x }}:{{ y }}
{% endfor %}

with this context

context = {
    "x_list": ('one', 1, 'carrot'),
    "y_list": ('two', 2, 'orange')
}

will output

one:two
1:2
carrot:orange


问:
AttributeError:'LinearSVC' object has no attribute 'predict_proba'
I am trying to use LinearSVC classifier

Update: Added imports

```<code>import nltk
from nltk.tokenize import word_tokenize
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.svm import LinearSVC, SVC

LinearSVC_classifier = SklearnClassifier(LinearSVC())
LinearSVC_classifier.train(featuresets)
</code>```

But when I am trying to classify it with probabilities

```<code>LinearSVC_classifier.prob_classify(feats)
</code>```

AttributeError occurs:

```<code>AttributeError:'LinearSVC' object has no attribute 'predict_proba'
</code>```

I checked sklearn documentation, it tells that this function exist.

How to fix that?

答:
Given your question, there is no mentioning about some outside-wrapper like NLTK (except for the tag), so it's hard to grasp what you really need!

Vivek Kumar's comment applies. LinearSVC has no support for probabilities, while SVC does.

Now some additional remarks:

SVM-theory is not much about probabilities and the support for this comes from extra-approaches using cross-validation and an additional classifier

see Platt scaling

the core-solver of LinearSVC, liblinear has not inbuilt-support for this

the approach of mdilip above is a valid workaround, but:

SVC is based on libsvm and therefore slower (and maybe not ready for large-scale)

alternative: build your own pipeline consisting of:

LinearSVC

sklearn's probability-calibration

It seems someone observed this problem before.

Body:
I am trying to use LinearSVC classifier

Update: Added imports

import nltk
from nltk.tokenize import word_tokenize
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.svm import LinearSVC, SVC

LinearSVC_classifier = SklearnClassifier(LinearSVC())
LinearSVC_classifier.train(featuresets)

But when I am trying to classify it with probabilities

LinearSVC_classifier.prob_classify(feats)

AttributeError occurs:

AttributeError:'LinearSVC' object has no attribute 'predict_proba'

I checked sklearn documentation, it tells that this function exist.

How to fix that?


问:
Using numba for cosine similarity between a vector and rows in a matix
Found this gist using numba for fast computation of cosine similarity.

```<code>import numba

@numba.jit(target='cpu', nopython=True)
def fast_cosine(u, v):
    m = u.shape[0]
    udotv = 0
    u_norm = 0
    v_norm = 0
    for i in range(m):
        if (np.isnan(u[i])) or (np.isnan(v[i])):
            continue

        udotv += u[i] * v[i]
        u_norm += u[i] * u[i]
        v_norm += v[i] * v[i]

    u_norm = np.sqrt(u_norm)
    v_norm = np.sqrt(v_norm)

    if (u_norm == 0) or (v_norm == 0):
        ratio = 1.0
    else:
        ratio = udotv / (u_norm * v_norm)
    return ratio
</code>```

Results look promising (500ns vs. only 200us without jit decorator in my machine).

I would like to use numba to parallelize this computation between a vector u and a candidate matrix M -- i.e. cosine across each row.

Example:

```<code>def fast_cosine_matrix(u, M):
    """
    Return array of cosine similarity between u and rows in M
    >>> import numpy as np
    >>> u = np.random.rand(100)
    >>> M = np.random.rand(10, 100)
    >>> fast_cosine_matrix(u, M)
    """
</code>```

One way is to just rewrite with second input a matrix. But I get a NotImplementedError if I try to iterate over the rows of a matrix. Going to try just using slices.

I thought about using vectorize but I can't get it to work.

答:
Solution rewriting it a bit:</p>

```<code>import numpy as np
import numba

@numba.jit(target='cpu', nopython=True, parallel=True)
def fast_cosine_matrix(u, M):
    scores = np.zeros(M.shape[0])
    for i in numba.prange(M.shape[0]):
        v = M[i]
        m = u.shape[0]
        udotv = 0
        u_norm = 0
        v_norm = 0
        for j in range(m):
            if (np.isnan(u[j])) or (np.isnan(v[j])):
                continue

            udotv += u[j] * v[j]
            u_norm += u[j] * u[j]
            v_norm += v[j] * v[j]

        u_norm = np.sqrt(u_norm)
        v_norm = np.sqrt(v_norm)

        if (u_norm == 0) or (v_norm == 0):
            ratio = 1.0
        else:
            ratio = udotv / (u_norm * v_norm)
        scores[i] = ratio
    return scores

u = np.random.rand(100)
M = np.random.rand(100000, 100)

fast_cosine_matrix(u, M)
</code>```

Body:
Found this gist using numba for fast computation of cosine similarity.

import numba

@numba.jit(target='cpu', nopython=True)
def fast_cosine(u, v):
    m = u.shape[0]
    udotv = 0
    u_norm = 0
    v_norm = 0
    for i in range(m):
        if (np.isnan(u[i])) or (np.isnan(v[i])):
            continue

        udotv += u[i] * v[i]
        u_norm += u[i] * u[i]
        v_norm += v[i] * v[i]

    u_norm = np.sqrt(u_norm)
    v_norm = np.sqrt(v_norm)

    if (u_norm == 0) or (v_norm == 0):
        ratio = 1.0
    else:
        ratio = udotv / (u_norm * v_norm)
    return ratio

Results look promising (500ns vs. only 200us without jit decorator in my machine).

I would like to use numba to parallelize this computation between a vector u and a candidate matrix M -- i.e. cosine across each row.

Example:

def fast_cosine_matrix(u, M):
    """
    Return array of cosine similarity between u and rows in M
    >>> import numpy as np
    >>> u = np.random.rand(100)
    >>> M = np.random.rand(10, 100)
    >>> fast_cosine_matrix(u, M)
    """

One way is to just rewrite with second input a matrix. But I get a NotImplementedError if I try to iterate over the rows of a matrix. Going to try just using slices.

I thought about using vectorize but I can't get it to work.

Body:
Solution rewriting it a bit:

import numpy as np
import numba

@numba.jit(target='cpu', nopython=True, parallel=True)
def fast_cosine_matrix(u, M):
    scores = np.zeros(M.shape[0])
    for i in numba.prange(M.shape[0]):
        v = M[i]
        m = u.shape[0]
        udotv = 0
        u_norm = 0
        v_norm = 0
        for j in range(m):
            if (np.isnan(u[j])) or (np.isnan(v[j])):
                continue

            udotv += u[j] * v[j]
            u_norm += u[j] * u[j]
            v_norm += v[j] * v[j]

        u_norm = np.sqrt(u_norm)
        v_norm = np.sqrt(v_norm)

        if (u_norm == 0) or (v_norm == 0):
            ratio = 1.0
        else:
            ratio = udotv / (u_norm * v_norm)
        scores[i] = ratio
    return scores

u = np.random.rand(100)
M = np.random.rand(100000, 100)

fast_cosine_matrix(u, M)