问:
Facebook SDK returned an error: Cross-site request forgery validation failed. The "state" param from the URL and session do not match
i'm trying to get Facebook user id using the php sdk like this

```<code>$fb = new Facebook\Facebook([
    'app_id' => '11111111111',
    'app_secret' => '1111222211111112222',
    'default_graph_version' => 'v2.4',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['public_profile','email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://MyWebSite', $permissions);

echo '<a href="' . $loginUrl . '">Log in with Facebook!</a>';

    try {
        $accessToken = $helper->getAccessToken();
        var_dump($accessToken);
    } catch (Facebook\Exceptions\FacebookResponseException $e) {
        // When Graph returns an error
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }

    if (!isset($accessToken)) {
        if ($helper->getError()) {
            header('HTTP/1.0 401 Unauthorized');
            echo "Error: " . $helper->getError() . "\n";
            echo "Error Code: " . $helper->getErrorCode() . "\n";
            echo "Error Reason: " . $helper->getErrorReason() . "\n";
            echo "Error Description: " . $helper->getErrorDescription() . "\n";
        } else {
            header('HTTP/1.0 400 Bad Request');
            echo 'Bad request';
        }
        exit;
    }

// Logged in
    echo '<h3>Access Token</h3>';
    var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
    $oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
    $tokenMetadata = $oAuth2Client->debugToken($accessToken);
    echo '<h3>Metadata</h3>';
    var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)
    $tokenMetadata->validateAppId($config['11111111111']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
    $tokenMetadata->validateExpiration();

    if (!$accessToken->isLongLived()) {
        // Exchanges a short-lived access token for a long-lived one
        try {
            $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
            exit;
        }

        echo '<h3>Long-lived</h3>';
        var_dump($accessToken->getValue());
    }

    $_SESSION['fb_access_token'] = (string)$accessToken;
</code>```

but it give me this error:

```<code>Facebook SDK returned an error:
Cross-site request forgery validation failed.
The "state" param from the URL and session do not match.
</code>```

please any help i'm new in php and Facebook sdk's thank for any help in advance.

答:
For me setting the session state worked

Complete code ( in the redirect url php )

```<code>$accessToken = '';

$helper = $fb->getRedirectLoginHelper();

if(isset($_GET['state'])){

    $_SESSION['FBRLH_state']=$_GET['state'];
}

try {
    $accessToken = $helper->getAccessToken();
} catch ( Facebook\Exceptions\FacebookResponseException $e ) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();

}
</code>```

Body:
i'm trying to get Facebook user id using the php sdk like this

$fb = new Facebook\Facebook([
    'app_id' => '11111111111',
    'app_secret' => '1111222211111112222',
    'default_graph_version' => 'v2.4',
]);

$helper = $fb->getRedirectLoginHelper();

$permissions = ['public_profile','email']; // Optional permissions
$loginUrl = $helper->getLoginUrl('http://MyWebSite', $permissions);

echo 'Log in with Facebook!';

    try {
        $accessToken = $helper->getAccessToken();
        var_dump($accessToken);
    } catch (Facebook\Exceptions\FacebookResponseException $e) {
        // When Graph returns an error
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }

    if (!isset($accessToken)) {
        if ($helper->getError()) {
            header('HTTP/1.0 401 Unauthorized');
            echo "Error: " . $helper->getError() . "\n";
            echo "Error Code: " . $helper->getErrorCode() . "\n";
            echo "Error Reason: " . $helper->getErrorReason() . "\n";
            echo "Error Description: " . $helper->getErrorDescription() . "\n";
        } else {
            header('HTTP/1.0 400 Bad Request');
            echo 'Bad request';
        }
        exit;
    }

// Logged in
    echo '
Access Token
';
    var_dump($accessToken->getValue());

// The OAuth 2.0 client handler helps us manage access tokens
    $oAuth2Client = $fb->getOAuth2Client();

// Get the access token metadata from /debug_token
    $tokenMetadata = $oAuth2Client->debugToken($accessToken);
    echo '
Metadata
';
    var_dump($tokenMetadata);

// Validation (these will throw FacebookSDKException's when they fail)
    $tokenMetadata->validateAppId($config['11111111111']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
    $tokenMetadata->validateExpiration();

    if (!$accessToken->isLongLived()) {
        // Exchanges a short-lived access token for a long-lived one
        try {
            $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            echo "
Error getting long-lived access token: " . $helper->getMessage() . "
\n\n";
            exit;
        }

        echo '
Long-lived
';
        var_dump($accessToken->getValue());
    }

    $_SESSION['fb_access_token'] = (string)$accessToken;

but it give me this error:

Facebook SDK returned an error:
Cross-site request forgery validation failed.
The "state" param from the URL and session do not match.

please any help i'm new in php and Facebook sdk's thank for any help in advance.

Body:
For me setting the session state worked

Complete code ( in the redirect url php )

$accessToken = '';

$helper = $fb->getRedirectLoginHelper();

if(isset($_GET['state'])){

    $_SESSION['FBRLH_state']=$_GET['state'];
}

try {
    $accessToken = $helper->getAccessToken();
} catch ( Facebook\Exceptions\FacebookResponseException $e ) {
    // When Graph returns an error
    echo 'Graph returned an error: ' . $e->getMessage();

}


来源: stackexchange

问:
You do not have permission to call getContacts
I'm developing the GMail Add-on that pulls out all user's contacts to card:

```<code>var contacts = ContactsApp.getContacts();
</code>```

I already enabled ContactsAPI in Google API Console and added scope:
https://www.googleapis.com/auth/contacts.readonly

But the error is still there and the Contacts API is missing in the project's Advanced Google Service pop-up.

答:
Through trial and error, and this hard-to-find list I managed to get ContactsApp.getContacts() to work.  You need to add this scope:

```<code>"oauthScopes": [
  "https://www.google.com/m8/feeds",
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm developing the GMail Add-on that pulls out all user's contacts to card:

var contacts = ContactsApp.getContacts();

I already enabled ContactsAPI in Google API Console and added scope:
https://www.googleapis.com/auth/contacts.readonly

But the error is still there and the Contacts API is missing in the project's Advanced Google Service pop-up.

Body:
Through trial and error, and this hard-to-find list I managed to get ContactsApp.getContacts() to work.  You need to add this scope:

"oauthScopes": [
  "https://www.google.com/m8/feeds",


问:
Beaglebone Black or raspberry PI?
I had a question about the Beaglebone Black. why texas instruments  suggest using Beaglebone Black instead of Raspberry PI 3 which has Bluetooth and Wi-Fi chip inside and it is cheaper and more powerful. Is there any special reason ?</p>

答: Mostly the extra GPIO pins. But also the embedded PRUs. The beaglebone black has 2 extra RISC processors onboard that are great for PID loops if you want to get experience with TI's assembly programming.</p>

Title: Beaglebone Black or raspberry PI?


问:
Reusing code - Java
Is there any way of reusing the iteration through the array code in these functions:</p>

```<code>public static double[] ln(double[] z) {
    // returns  an array that consists of the natural logarithm of the values in array z
    int count = 0;

    for (double i : z){
        z[count] = Math.log(i);
        count += 1;
    }
    return z;
}

public static double[] inverse(double[] z) {
    //  returns  an array that consists of the inverse of the values in array z
    int count = 0;

    for (double i : z){
        z[count] = Math.pow(i,-1);
        count += 1;
    }
    return z;
}
</code>```

答:
Yes, as a couple of examples here illustrate. But if this is the real problem and not an extreme simplification, creating three classes with inheritance and overloading to save on writing one FOR statement seems to me to be heading in the wrong direction. You're writing twenty lines of code to save on repeating one line of code. What's the gain?

If in real life the process of iterating through the data is much more complicated for some reason -- if it's not just looping through an array but, I don't know, some complex process of looking things up in a database and submitting a web services request and doing a page full of complex calculations to find the next element -- then my answer would be different.

ContentLicense: CC BY-SA 2.5

Title: Reusing code - Java

Body:
Is there any way of reusing the iteration through the array code in these functions:

public static double[] ln(double[] z) {
    // returns  an array that consists of the natural logarithm of the values in array z
    int count = 0;

    for (double i : z){
        z[count] = Math.log(i);
        count += 1;
    }
    return z;
}

public static double[] inverse(double[] z) {
    //  returns  an array that consists of the inverse of the values in array z
    int count = 0;

    for (double i : z){
        z[count] = Math.pow(i,-1);
        count += 1;
    }
    return z;
}


问:
Adding scale labels to levelplot's margins
I'd like to add label showing the values of latitudinal zonal averages to levelplot's gray margin. In the following example, the min and max values for latitudinal means are 286 and 751 respectively. Any suggestion on adding an axis with this information to the margin?

```<code>library(raster)
library(rasterVis)
r <- raster(system.file("external/test.grd", package="raster"))
levelplot(r, at=seq(100, 1850, by = 250))
# calculating the latitudinal means
rows <- init(r, v='y')
yAve <- zonal(r, rows, fun='mean',na.rm=TRUE)
summary(yAve)
</code>```

答:
Use margin=list(axis=TRUE) to add the min and max values to the margin.

```<code>library(raster)
library(rasterVis)
r <- raster(system.file("external/test.grd", package="raster"))
levelplot(r, at=seq(100, 1850, by = 250), margin=list(axis=TRUE))
</code>```

You can change the color and fontsize of the margin labels using gpar.

```<code>library(grid)
levelplot(r, at=seq(100, 1850, by = 250), margin=list(axis=gpar(col = 'black', fontsize = 9)))
</code>```

Body:
I'd like to add label showing the values of latitudinal zonal averages to levelplot's gray margin. In the following example, the min and max values for latitudinal means are 286 and 751 respectively. Any suggestion on adding an axis with this information to the margin?

library(raster)
library(rasterVis)
r <- raster(system.file("external/test.grd", package="raster"))
levelplot(r, at=seq(100, 1850, by = 250))
# calculating the latitudinal means
rows <- init(r, v='y')
yAve <- zonal(r, rows, fun='mean',na.rm=TRUE)
summary(yAve)

Body:
Use margin=list(axis=TRUE) to add the min and max values to the margin.

library(raster)
library(rasterVis)
r <- raster(system.file("external/test.grd", package="raster"))
levelplot(r, at=seq(100, 1850, by = 250), margin=list(axis=TRUE))

You can change the color and fontsize of the margin labels using gpar.

library(grid)
levelplot(r, at=seq(100, 1850, by = 250), margin=list(axis=gpar(col = 'black', fontsize = 9)))


问:
Is it possible in Red to test value? for a variable inside a context not in global context?
In last example, probe value? 'a returns true as it detects 'a has value in global context. But I'd like to test 'a exclusively in local context, is there a syntax to do so ?</p>

```<code>    context [
        probe value? 'a; false
    ]

    context [
        a: 1
        probe value? 'a; true
    ]

    ; would like false instead of true
    a: 1
    context [
        probe value? 'a; true
    ]
</code>```

答:
I think the simplest check would be

```<code>context [
    probe in self 'a ; none
]
</code>```

It returns none instead of false, but that is the only other falsy value anyway, so it's totally appropriate to check against. If you need it to be false, you can put to-logic in front.

Body:
In last example, probe value? 'a returns true as it detects 'a has value in global context. But I'd like to test 'a exclusively in local context, is there a syntax to do so ?

    context [
        probe value? 'a; false
    ]

    context [
        a: 1
        probe value? 'a; true
    ]

    ; would like false instead of true
    a: 1
    context [
        probe value? 'a; true
    ]

Body:
I think the simplest check would be

context [
    probe in self 'a ; none
]

It returns none instead of false, but that is the only other falsy value anyway, so it's totally appropriate to check against. If you need it to be false, you can put to-logic in front.


问:
How to create android button bar?
I need to create a horizontal list of buttons without a separating space like this one

each button will contain a text and an icon I know about buttonbarlayout but it didn't work for me, please can someone help me, Thanks in advance

答: What you can see in that picture isn't a simple button bar, it's called Bottom Navigation Bar, and Android has specific code for that. In this question you can learn how to create one and use it. You can change of course the colors with simple XML or Java code. Hope you find it helpful.

Title: How to create android button bar?


问:
Reducing execution time C++

Task

You are given an amount of pages in a book. The book printer is lazy and will only print the side number on every other page. The first page number to be printed is 1. The task is to calculate the amount of times a specific number is used on the printed book pages. The goal is to print out all numbers used in bookpages being; 10^9 < pages < 10^12 in less than 5 seconds.

For example

Amount of book pages is 20. The book pages to be printed are then, 1, 3, 5, 7, 9, 11, 13, 15, 17 and 19. The 1 contains only the number 1 and should therefor only increment the savings on 1 by one. However, the number 13 contains 1 and 3, therefor the number 1 and 3 will in the savings will be incremented and so forth.

Question

How do I make the program execute faster at larger numbers? I've been thinking about using threads but I'm unsure if it's beneficial or not.

```<code>#include <iostream>
#include <string>

int main(int argc, char *argv[]) {

    long long sideNumber;
    long long numbers[10];

    if(argv[1]) {
        sideNumber = std::stoll(argv[1]);
    } else {
        std::printf("Please enter amount of pages.\n");
        return -1;
    }

    for(int i = 0; i < 10; i++) numbers[i] = 0;

    long long index = 1;

    while(index < sideNumber) {
        long long current = index;
        while(current > 0) {
            numbers[current%10]++;
            current /= 10;
        }
        index += 2;
    }

    for(int i = 0; i < 10; i++) {
        std::printf("%i : %i\n", i, numbers[i]);
    }

    return 0;
}
</code>```

答:
This is trivially a maths problem, not a computing problem.
However, if this has really been set as a computing problem, then the answer is probably recursive.

Consider the page numbers 1-9. How many do they tally for digits 0-9?

Now consider the pages 11-19. Can you re-use the tally from the previous task to make a new tally? and again for 2x,3x,4x, etc.

Then, can you reuse the tally from 1-99 for 101-199?, etcetera.

Note that you need to think some more about how you deal with middle zeros.

Alternatively, you can use a pencil to get the same result in half the time it takes you to write the program.

Title: Reducing execution time C++

Body:
Task

You are given an amount of pages in a book. The book printer is lazy and will only print the side number on every other page. The first page number to be printed is 1. The task is to calculate the amount of times a specific number is used on the printed book pages. The goal is to print out all numbers used in bookpages being; 10^9 < pages < 10^12 in less than 5 seconds.

For example

Amount of book pages is 20. The book pages to be printed are then, 1, 3, 5, 7, 9, 11, 13, 15, 17 and 19. The 1 contains only the number 1 and should therefor only increment the savings on 1 by one. However, the number 13 contains 1 and 3, therefor the number 1 and 3 will in the savings will be incremented and so forth.

Question

How do I make the program execute faster at larger numbers? I've been thinking about using threads but I'm unsure if it's beneficial or not.

#include <iostream>
#include <string>

int main(int argc, char *argv[]) {

    long long sideNumber;
    long long numbers[10];

    if(argv[1]) {
        sideNumber = std::stoll(argv[1]);
    } else {
        std::printf("Please enter amount of pages.\n");
        return -1;
    }

    for(int i = 0; i < 10; i++) numbers[i] = 0;

    long long index = 1;

    while(index < sideNumber) {
        long long current = index;
        while(current > 0) {
            numbers[current%10]++;
            current /= 10;
        }
        index += 2;
    }

    for(int i = 0; i < 10; i++) {
        std::printf("%i : %i\n", i, numbers[i]);
    }

    return 0;
}


问:
Modify Hashtable value of a specific key
I need to increase the value of a specific key in a Hashtable,
here is my code (I want to create the Hashtable during the function,
and I want the table to be like that - <string><int>):

```<code>public void getMssg(string ipSend, string mssg, Hashtable table)
{
    if (table.Contains(ipSend))
        table[ipSend]++;        //error
}
</code>```

By the way, can I define a Hashtable like I wrote above?

答:
Use a Dictionary<string, int> instead.

```<code>public void getMssg(string ipSend, IDictionary<string, int> table)
{
    int result;
    if(!table.TryGetValue(ipSend, out result))
        result = 0; // do something if the key is not found
    table[ipSend] = ++result;
}
</code>```

Body:
I need to increase the value of a specific key in a Hashtable,
here is my code (I want to create the Hashtable during the function,
and I want the table to be like that - <string><int>):

public void getMssg(string ipSend, string mssg, Hashtable table)
{
    if (table.Contains(ipSend))
        table[ipSend]++;        //error
}

By the way, can I define a Hashtable like I wrote above?

Body:
Use a Dictionary<string, int> instead.

public void getMssg(string ipSend, IDictionary<string, int> table)
{
    int result;
    if(!table.TryGetValue(ipSend, out result))
        result = 0; // do something if the key is not found
    table[ipSend] = ++result;
}


问:
Haskell Use guarded equation to create type
I want to create a type called TwoValued and it contains two values: a and b, and I'd like to make sure that a <= b

```<code>data TwoValued a b | a <= b = ValuePair a b
                   | otherwise = ValuePair b a
</code>```

But it's not working, I think guarded equation is not allowed here, so is there any other way to achieve what I want? Thanks.

答:
Smart constructors are the idiomatic approach, as others already commented.

As an alternative, we can also use "smart pattern-constructors", which allow logic beyond regular ones.

```<code>{-# LANGUAGE PatternSynonyms #-}

module SmartCons(OrdPair(OrdPair)) where

data OrdPair = OP Int Int

pattern OrdPair :: Int -> Int -> OrdPair
pattern OrdPair x y <- OP x y where
   OrdPair x y = if x <= y then OP x y else OP y x
</code>```

We can then use them as intended:

```<code>> import SmartCons
> case OrdPair 3 2 of OrdPair x _ -> x
2
</code>```

Note that the OP dumb constructor is accessible only within the module. From outside, we can only use the smart one.

Whether this is a good or bad idea is arguable, though. I guess we are not yet used to expect constructors to involve some logic. Hiding an expensive computation behind construction could easily surprise the user.

ContentLicense: CC BY-SA 4.0

Body:
I want to create a type called TwoValued and it contains two values: a and b, and I'd like to make sure that a <= b

data TwoValued a b | a <= b = ValuePair a b
                   | otherwise = ValuePair b a

But it's not working, I think guarded equation is not allowed here, so is there any other way to achieve what I want? Thanks.

Body:
Smart constructors are the idiomatic approach, as others already commented.

As an alternative, we can also use "smart pattern-constructors", which allow logic beyond regular ones.

{-# LANGUAGE PatternSynonyms #-}

module SmartCons(OrdPair(OrdPair)) where

data OrdPair = OP Int Int

pattern OrdPair :: Int -> Int -> OrdPair
pattern OrdPair x y <- OP x y where
   OrdPair x y = if x <= y then OP x y else OP y x

We can then use them as intended:

> import SmartCons
> case OrdPair 3 2 of OrdPair x _ -> x
2

Note that the OP dumb constructor is accessible only within the module. From outside, we can only use the smart one.

Whether this is a good or bad idea is arguable, though. I guess we are not yet used to expect constructors to involve some logic. Hiding an expensive computation behind construction could easily surprise the user.


问:
Partial/Selective backup/copy of a Firebird database
I would like to backup a Firebird database but exclude certain tables from the backup, is this possible?

If not, I'd like to make a copy of the Firebird database while it's running (without doing a backup followed by a restore)

Neither gbak nor nbackup seem to support things like this, and yet we have a piece of software here in the company that can do a selective backup, I just have no idea how it works. I'd like to replicate its behaviour.

答:
There is a new parameter named skip_d in gbak for version 3 of Firebird, and you can give regex to this parameter.

You can find detail information in here

For example: gbak -b -skip_d '(table1|table2|table3)' -user ...


问:
Can a value from a JTextField be forced into the ValueModel (JGoodies)
I have this code:

```<code>this.trigger = new Trigger();
this.presentationModel = new PresentationModel(this.personBean, this.trigger);
final ValueModel firstNameAdapter = presentationModel.getBufferedModel("firstName");
final JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);
</code>```

and

```<code>firstNameTextField.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            trigger.triggerCommit();
        }
    });
</code>```

So when I push the enter button on the JTextField, I expect the value in my ValueModel class to be the same as the value in my JTextField. This doesn't happen unless I click outside the JTextField, then back inside the JTextField, and then push enter. If I just type in the text and hit enter, the ValueModel does not get the updated value. I am stuck on this problem, can anybody help?

BTW, I used this link for figuring out JGoodies in the first place: JGoodies Tutorial

答:
I hope I am understanding your question correctly.

You need to get the text in the text field and set it in the ValueModel.

```<code>firstNameTextField.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
       //this get the text from the text field
       String firstName = firstNameTextField.getText();

       //now write your code to set the firstname into the ValueModel

       trigger.triggerCommit();
    }
 });
</code>```

Body:
I have this code:

this.trigger = new Trigger();
this.presentationModel = new PresentationModel(this.personBean, this.trigger);
final ValueModel firstNameAdapter = presentationModel.getBufferedModel("firstName");
final JTextField firstNameTextField = BasicComponentFactory.createTextField(firstNameAdapter);

and

firstNameTextField.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            trigger.triggerCommit();
        }
    });

So when I push the enter button on the JTextField, I expect the value in my ValueModel class to be the same as the value in my JTextField. This doesn't happen unless I click outside the JTextField, then back inside the JTextField, and then push enter. If I just type in the text and hit enter, the ValueModel does not get the updated value. I am stuck on this problem, can anybody help?

BTW, I used this link for figuring out JGoodies in the first place: JGoodies Tutorial

Body:
I hope I am understanding your question correctly.

You need to get the text in the text field and set it in the ValueModel.

firstNameTextField.addActionListener(new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
       //this get the text from the text field
       String firstName = firstNameTextField.getText();

       //now write your code to set the firstname into the ValueModel

       trigger.triggerCommit();
    }
 });


问:
You seem to not be depending on "@angular/core". This is an error
I want to create an angular 2 App with angular cli

I have written in the cmd:

npm install angular-cli -g

then:

ng firstngapp

but it show me an error when I write npm start !

I don't understand the problem

答:
I was getting the same error when I tried to run "ng serve" after that I saw some suggetions one of the techie told me to update my npm.I did that as well then I got this screen after entering "ng server"

""Versions of @angular/compiler-cli and typescript could not be determined.
The most common reason for this is a broken npm install.
Please make sure your package.json contains both @angular/compiler-cli and typescript in devDependencies, then delete node_module and package-lock.json(if you have one) and
Run npm install again.""

After performing all the actions now its working correctly...and getting message "Compiled Successfully."


问:
Dynamic conversion of JSON to XML using saxon
We have incoming JSON data from Source which has data and column in same payload. Using json-to-xml in XSLT I was able to generate XML like following:

```<code>  <?xml version="1.0" encoding="UTF-8"?>
  <map xmlns="http://www.w3.org/2005/xpath-functions">
   <boolean key="allData">true</boolean>
   <map key="factMap">
  <map key="T!T">
     <array key="rows">
        <map>
           <array key="dataCells">
              <map>
                 <string key="label">1A</string>
                 <string key="value">1A</string>
              </map>
              <map>
                 <string key="label">1B</string>
                 <null key="value"/>
              </map>
              <map>
                 <string key="label">1C</string>
                 <string key="value">1C</string>
              </map>
           </array>
        </map>
        <map>
           <array key="dataCells">
              <map>
                 <string key="label">2A</string>
                 <string key="value">2A</string>
              </map>
              <map>
                 <string key="label">2B</string>
                 <string key="value">2B</string>
              </map>
              <map>
                 <string key="label">2C</string>
                 <null key="value"/>
              </map>
           </array>
        </map>
      </map>
 <map key="detailColumnInfo">
  <map key="name.F1">
     <string key="dataType">string</string>
     <string key="label">F1</string>
  </map>
  <map key="state.F2">
     <string key="dataType">string</string>
     <string key="label">F2</string>
  </map>
  <map key="dist.F3">
     <string key="dataType">string</string>
     <string key="label">F3</string>
  </map>
  </map>
     </map>
</code>```

We have to generate following XML output.

```<code><Root>
  <Rows>
   <Row>
    <F1> 1A </F1>
    </F2>
    <F3> 1C </F3>
   </Row>
  <Row>
    <F1>2A </F1>
    <F2> 2B </F2>
    </F3>
  </Row>
           </Rows>
</code>```

We are able to generate data after taking reference from

https://stackoverflow.com/questions/47173669/dynamic-xml-generation-using-xslt#=
But it not working as expected for null tags.
Can anyone suggest possible solutions to implement such dynamic mapping.

答:
By reference to the other question you linked, I take your question to be about the fact that the values you want to extract are sometimes represented as <string> elements, but also sometimes as <null> elements.  It appears that either way, the elements of interest are distinguished by a key attribute with value 'value', so you can base your selection criteria on that.

That is, instead of using fn:string[@key = 'value'] in your XPath expressions, use *[@key = 'value'] or even node()[@key = 'value'].  There are other alternatives, but applying either of those variations to the XSL in the answer you referenced will yield a transform that handles the input you present in the manner you seem to want (notwithstanding ill-formedness in the output presented in this question, which I am taking to be unintentional).

Body:
We have incoming JSON data from Source which has data and column in same payload. Using json-to-xml in XSLT I was able to generate XML like following:

  <?xml version="1.0" encoding="UTF-8"?>
  <map xmlns="http://www.w3.org/2005/xpath-functions">
   <boolean key="allData">true</boolean>
   <map key="factMap">
  <map key="T!T">
     <array key="rows">
        <map>
           <array key="dataCells">
              <map>
                 <string key="label">1A</string>
                 <string key="value">1A</string>
              </map>
              <map>
                 <string key="label">1B</string>
                 <null key="value"/>
              </map>
              <map>
                 <string key="label">1C</string>
                 <string key="value">1C</string>
              </map>
           </array>
        </map>
        <map>
           <array key="dataCells">
              <map>
                 <string key="label">2A</string>
                 <string key="value">2A</string>
              </map>
              <map>
                 <string key="label">2B</string>
                 <string key="value">2B</string>
              </map>
              <map>
                 <string key="label">2C</string>
                 <null key="value"/>
              </map>
           </array>
        </map>
      </map>
 <map key="detailColumnInfo">
  <map key="name.F1">
     <string key="dataType">string</string>
     <string key="label">F1</string>
  </map>
  <map key="state.F2">
     <string key="dataType">string</string>
     <string key="label">F2</string>
  </map>
  <map key="dist.F3">
     <string key="dataType">string</string>
     <string key="label">F3</string>
  </map>
  </map>
     </map>

We have to generate following XML output.

<Root>
  <Rows>
   <Row>
    <F1> 1A </F1>
    </F2>
    <F3> 1C </F3>
   </Row>
  <Row>
    <F1>2A </F1>
    <F2> 2B </F2>
    </F3>
  </Row>
           </Rows>

We are able to generate data after taking reference from

https://stackoverflow.com/questions/47173669/dynamic-xml-generation-using-xslt#=
But it not working as expected for null tags.
Can anyone suggest possible solutions to implement such dynamic mapping.


问:
How do I count the number of commits made in to all repos hosted by gitosis on my server
I am trying to found out the total number of commits made across all repositories hosted on a gitosis install I have. Anyone have any ideas to how I may do this?</p>

答: For newer versions of git (tested on 2.14.1), the command git rev-list --count HEAD will work, and give the same result as git rev-list --all | wc -l.


问:
Javascript Interval functions not working
I am currently working on a clicker game for a game dev class I attend, and I can not figure out why my interval functions refuse to work.

What I am trying to achieve with this:

every 100 milliseconds a variable will increase by a number, multiplied by another variable, lets use 10, and i for example.

The code I tried:

```<code>var interval = setInterval( increment, 100);

function increment(){
  money += 10 * i;
  document.getElementById("money").innerHTML = money;
  document.getElementById("i").innerHTML = i;
}
</code>```

This is refusing to work, and I was wondering if it was a problem with defining the variable, or just with the syntax.

Any suggestion?

答:
You need to initialize i (as well as money). You probably also want to increment i so you get different values at every interval.

```<code>var interval = setInterval(increment, 100);
var money = 0;
var i = 0;

function increment(){
    money += 10 * i
    document.getElementById("money").innerHTML = money;
    document.getElementById("i").innerHTML = i;
    i++; // increment
}
</code>```

A few other ways you could increment i:

```<code>i = i + 1;
i += 1;
++i;
</code>```

Also keep in mind that ++i and i++ have some particular effects when used in expressions (though that’s out of scope for this question).

Body:
I am currently working on a clicker game for a game dev class I attend, and I can not figure out why my interval functions refuse to work.

What I am trying to achieve with this:

every 100 milliseconds a variable will increase by a number, multiplied by another variable, lets use 10, and i for example.

The code I tried:

var interval = setInterval( increment, 100);

function increment(){
  money += 10 * i;
  document.getElementById("money").innerHTML = money;
  document.getElementById("i").innerHTML = i;
}

This is refusing to work, and I was wondering if it was a problem with defining the variable, or just with the syntax.

Any suggestion?

Body:
You need to initialize i (as well as money). You probably also want to increment i so you get different values at every interval.

var interval = setInterval(increment, 100);
var money = 0;
var i = 0;

function increment(){
    money += 10 * i
    document.getElementById("money").innerHTML = money;
    document.getElementById("i").innerHTML = i;
    i++; // increment
}

A few other ways you could increment i:

i = i + 1;
i += 1;
++i;

Also keep in mind that ++i and i++ have some particular effects when used in expressions (though that’s out of scope for this question).


问:
Jenkins EC2 Plugin Script Approval
I just updated my Jenkins from 2.79 to 2.86

It seems to add new security fixes but it broke the EC2-Plugin

Indeed, now everytime the plugin is trying to launch a slave agent, I got an error:

"Launching agent" "ERROR: script not yet approved for use"

But the script to be approve via the Script Approval page is dynamic, containing temporary information

Did someone find how to solve the issue?

Thank you

EDIT:
I partially found a fix by unchecking the Connect by SSH Process in the EC2 configuration

答:
I also downgraded to 2.84 as I could not figure out how to enable sandbox mode.
Created new JIRA with Jenkins team.

https://issues.jenkins-ci.org/browse/JENKINS-47979

Title: Jenkins EC2 Plugin Script Approval


问:
Assembly: Few Commands in a Single Line
I have to shorten my code a lot and I thought, whether it is possible to write a few commands in a single line in Assembly x16. For example,

```<code>MOV cl,10b  CMP cl,10b  JE label
</code>```

I know that it's impossible to write in this way as I've written above, but maybe there is a way to join these commands. Thanks!

This is one of the procedures that I used in my disassembler. I would like to inform you, that I didn't have to identify all commands! I've written all possible variations of commands that I have to identify. THIS IS ONE OF FOUR PROCEDURES, THAT IDENTIFIES COMMAND. I've done this by using this method: I take first two bits of operation code, then divide in four groups (00,01,10,11) and do the same in each group with next to bits and so on.

```<code>    THIS IS THE PROCEDURE THAT HELPS TO FIND THE OPERATION CODE
 PROC FINDOPK
        opk11:                     ;first two bits of operation coda are 11
                MOV al,opk
                AND al,00110000b
                SHR al,4
                CMP al,01b
                JE opk1101
                CMP al,10b
                JE opk1110
                CMP al,11b
                JE opk1111  ;opk1100 starts here
                    MOV al,opk
                    AND al,00001100b
                    SHR al,2
                    CMP al,01b
                    JE opk110001
                    CMP al,10b
                    JE opk110010
                    CMP al,11b
                    JE opk110011    ;opk110000 starts here
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11000010
                        CMP al,11b
                        JE opk11000011  ;opk11000000 ir opk11000001
                            JMP neatpazinta   ;it means that i didn't have to identify this command and it prints that
                        opk11000010:  ;Doing stuff if operation code is like this
                            ;
                        opk11000011:  ;Same here
                            ;
                    opk110001:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11000110
                        CMP al,11b
                        JE opk11000111  ;opk11000100 ir opk11000101
                            JMP neatpazinta
                        opk11000110:
                            ;
                        opk11000111:
                            ;
                    opk110010:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,11b
                        JE opk11001011  ;opk11001000 ir opk11001001 ir opk11001010
                            JMP neatpazinta
                        opk11001011:
                            ;
                    opk110011:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,01b
                        JE opk11001101
                        CMP al,11b
                        JE opk11001111  ;opk11001100 ir opk11001110
                            JMP neatpazinta
                        opk11001101:
                            ;
                        opk11001111:
                            ;
                opk1101:
                    JMP neatpazinta
                opk1110:
                    MOV al,opk
                    AND al,00001100b
                    SHR al,2
                    CMP al,00b
                    JE opk111000
                    CMP al,10b
                    JE opk111010    ;opk111001 ir opk 111011
                        JMP neatpazinta
                    opk111000:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11100010
                        CMP al,11b
                        JE opk11100011  ;opk11100000 ir opk11100001
                            JMP neatpazinta
                        opk11100010:
                            ;
                        opk11100011:
                            ;
                    opk111010:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,01b
                        JE opk11101001
                        CMP al,10b
                        JE opk11101010
                        CMP al,11b
                        JE opk11101011  ;opk11101000
                            ;
                        opk11101001:
                            ;
                        opk11101010:
                            ;
                        opk11101011:
                            ;
                opk1111:
                    MOV al,opk
                    AND al,00001100b
                    SHR al,2
                    CMP al,01b
                    JE opk111101
                    CMP al,11b
                    JE opk111111    ;opk111100 ir opk 111110
                        JMP neatpazinta
                    opk111101:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11110110
                        CMP al,11b
                        JE opk11110111  ;opk11110100 ir opk11110101
                            JMP neatpazinta
                        opk11110110:
                            ;
                        opk11110111:
                            ;
                    opk111111:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11111110
                        CMP al,11b
                        JE opk11111111  ;opk11111100 ir opk11111101
                            JMP neatpazinta
                        opk11111110:
                            ;
                        opk11111111:
                            ;
            neatpazinta:
                CALL SpausdinkNeatpazinta
            SkipOPK:
        RET
        FINDOPK ENDP
</code>```

答:
Some flavours of x86 assembly syntax allow writing multiple instructions on one line.  For example, GAS (the GNU assembler) uses ; as a separator.  (# is the comment character).

```<code>.intel_syntax noprefix
MOV cl,10b;   CMP cl,10b;  JE label
</code>```

NASM syntax doesn't allow this, because it's usually not useful.

I have to shorten my code a lot

In assembly, usually this means you're worried about code-size of the machine code, not the size or line-count of the text source.

This means optimizing your code to need fewer and/or shorter instructions.  For ideas, see some of my x86 machine code answers on codegolf.SE, like Adler32 in 31 bytes of x86-32 machine code.  (NASM source included along with the machine code of course).

In your case, the je is always taken so you could probably optimize away most of that and just jmp label, depending on what you need cl and FLAGS set when you reach label.  You could get exactly the same architectural state (low byte of ecx = 10b, ZF set, CF,OF,SF cleared) from this:

```<code>MOV cl,10b
CMP cl,cl
JE label
</code>```

Interestingly, je label may be more efficient than jmp label on modern CPUs, because it can macro-fuse with the cmp into a single uop.  If label doesn't depend on flags being set, then you could do this.

```<code>MOV cl,10b
JMP label
</code>```

But really, you should step back and look for optimizations at a larger scale, e.g. maybe lay out your branches so you can fall through into label.

Title: Assembly: Few Commands in a Single Line

Body:
I have to shorten my code a lot and I thought, whether it is possible to write a few commands in a single line in Assembly x16. For example,

MOV cl,10b  CMP cl,10b  JE label

I know that it's impossible to write in this way as I've written above, but maybe there is a way to join these commands. Thanks!

This is one of the procedures that I used in my disassembler. I would like to inform you, that I didn't have to identify all commands! I've written all possible variations of commands that I have to identify. THIS IS ONE OF FOUR PROCEDURES, THAT IDENTIFIES COMMAND. I've done this by using this method: I take first two bits of operation code, then divide in four groups (00,01,10,11) and do the same in each group with next to bits and so on.

    THIS IS THE PROCEDURE THAT HELPS TO FIND THE OPERATION CODE
 PROC FINDOPK
        opk11:                     ;first two bits of operation coda are 11
                MOV al,opk
                AND al,00110000b
                SHR al,4
                CMP al,01b
                JE opk1101
                CMP al,10b
                JE opk1110
                CMP al,11b
                JE opk1111  ;opk1100 starts here
                    MOV al,opk
                    AND al,00001100b
                    SHR al,2
                    CMP al,01b
                    JE opk110001
                    CMP al,10b
                    JE opk110010
                    CMP al,11b
                    JE opk110011    ;opk110000 starts here
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11000010
                        CMP al,11b
                        JE opk11000011  ;opk11000000 ir opk11000001
                            JMP neatpazinta   ;it means that i didn't have to identify this command and it prints that
                        opk11000010:  ;Doing stuff if operation code is like this
                            ;
                        opk11000011:  ;Same here
                            ;
                    opk110001:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11000110
                        CMP al,11b
                        JE opk11000111  ;opk11000100 ir opk11000101
                            JMP neatpazinta
                        opk11000110:
                            ;
                        opk11000111:
                            ;
                    opk110010:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,11b
                        JE opk11001011  ;opk11001000 ir opk11001001 ir opk11001010
                            JMP neatpazinta
                        opk11001011:
                            ;
                    opk110011:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,01b
                        JE opk11001101
                        CMP al,11b
                        JE opk11001111  ;opk11001100 ir opk11001110
                            JMP neatpazinta
                        opk11001101:
                            ;
                        opk11001111:
                            ;
                opk1101:
                    JMP neatpazinta
                opk1110:
                    MOV al,opk
                    AND al,00001100b
                    SHR al,2
                    CMP al,00b
                    JE opk111000
                    CMP al,10b
                    JE opk111010    ;opk111001 ir opk 111011
                        JMP neatpazinta
                    opk111000:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11100010
                        CMP al,11b
                        JE opk11100011  ;opk11100000 ir opk11100001
                            JMP neatpazinta
                        opk11100010:
                            ;
                        opk11100011:
                            ;
                    opk111010:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,01b
                        JE opk11101001
                        CMP al,10b
                        JE opk11101010
                        CMP al,11b
                        JE opk11101011  ;opk11101000
                            ;
                        opk11101001:
                            ;
                        opk11101010:
                            ;
                        opk11101011:
                            ;
                opk1111:
                    MOV al,opk
                    AND al,00001100b
                    SHR al,2
                    CMP al,01b
                    JE opk111101
                    CMP al,11b
                    JE opk111111    ;opk111100 ir opk 111110
                        JMP neatpazinta
                    opk111101:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11110110
                        CMP al,11b
                        JE opk11110111  ;opk11110100 ir opk11110101
                            JMP neatpazinta
                        opk11110110:
                            ;
                        opk11110111:
                            ;
                    opk111111:
                        MOV al,opk
                        AND al,00000011b
                        CMP al,10b
                        JE opk11111110
                        CMP al,11b
                        JE opk11111111  ;opk11111100 ir opk11111101
                            JMP neatpazinta
                        opk11111110:
                            ;
                        opk11111111:
                            ;
            neatpazinta:
                CALL SpausdinkNeatpazinta
            SkipOPK:
        RET
        FINDOPK ENDP

Body:
Some flavours of x86 assembly syntax allow writing multiple instructions on one line.  For example, GAS (the GNU assembler) uses ; as a separator.  (# is the comment character).

.intel_syntax noprefix
MOV cl,10b;   CMP cl,10b;  JE label

NASM syntax doesn't allow this, because it's usually not useful.

I have to shorten my code a lot

In assembly, usually this means you're worried about code-size of the machine code, not the size or line-count of the text source.

This means optimizing your code to need fewer and/or shorter instructions.  For ideas, see some of my x86 machine code answers on codegolf.SE, like Adler32 in 31 bytes of x86-32 machine code.  (NASM source included along with the machine code of course).

In your case, the je is always taken so you could probably optimize away most of that and just jmp label, depending on what you need cl and FLAGS set when you reach label.  You could get exactly the same architectural state (low byte of ecx = 10b, ZF set, CF,OF,SF cleared) from this:

MOV cl,10b
CMP cl,cl
JE label

Interestingly, je label may be more efficient than jmp label on modern CPUs, because it can macro-fuse with the cmp into a single uop.  If label doesn't depend on flags being set, then you could do this.

MOV cl,10b
JMP label

But really, you should step back and look for optimizations at a larger scale, e.g. maybe lay out your branches so you can fall through into label.


问:
glClear causing problems according to Instruments? (OpenGL ES on iPhone)
I've been noticing lately that my game sometimes has performance issues, where each frame takes a lot longer than it should to finish. I plugged it into the CPU Sampler in Instruments and found something pretty strange (I think, this is my first time using CPU Sampler so I don't understand all of it).

glClear is apparently taking up an insane amount of CPU time (it currently reads 36%, and is steadily rising). This is a fairly processor-heavy game, so there is no way one call to glClear should be taking up so much time.

```<code>glClearColor(backgroundcolor[0], backgroundcolor[1], backgroundcolor[2], 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
</code>```

This is only called once per frame. I don't have an active stencil buffer, so that's not the problem. One thing that might be problematic is that my game allows you to move off virtually as far as you want in any direction, meaning that your x and y location can get very far from the origin. Does glClear try to clear the entire landscape you've covered or does it only clear the dimensions of the screen? And if that's not a problem, than does anyone know why it is being so expensive on my processor?

答:
glClear is waiting on the rest of your commands to complete (which, afaik on iOS means vsync?).

If you

glFlush();
glFinish();

at the end of your rendering, you'll see a lot of the time spent in glClear move to glFinish.

Body:
I've been noticing lately that my game sometimes has performance issues, where each frame takes a lot longer than it should to finish. I plugged it into the CPU Sampler in Instruments and found something pretty strange (I think, this is my first time using CPU Sampler so I don't understand all of it).

glClear is apparently taking up an insane amount of CPU time (it currently reads 36%, and is steadily rising). This is a fairly processor-heavy game, so there is no way one call to glClear should be taking up so much time.

glClearColor(backgroundcolor[0], backgroundcolor[1], backgroundcolor[2], 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

This is only called once per frame. I don't have an active stencil buffer, so that's not the problem. One thing that might be problematic is that my game allows you to move off virtually as far as you want in any direction, meaning that your x and y location can get very far from the origin. Does glClear try to clear the entire landscape you've covered or does it only clear the dimensions of the screen? And if that's not a problem, than does anyone know why it is being so expensive on my processor?


问:
Can word2vec algorithm be distributed on multi-computers using tensorflow?
I want to train word2vec model on a very big corpus such that embedded words cannot be allocated to RAM.

I know there are existing solutions for the algorithm parallelization, for example Spark implementation, but I would like to use tensorflow library.

Is it possible?

答:
Yes, it is possible in tensorflow out-of-the-box. The trick is to use variable partitioning, e.g. tf.fixed_size_partitioner, and parameter server replication via tf.train.replica_device_setter to split the variable across several machines. Here's how it looks like in code:

with tf.device(tf.train.replica_device_setter(ps_tasks=3)):
  embedding = tf.get_variable("embedding", [1000000000, 20],
                              partitioner=tf.fixed_size_partitioner(3))
```

The best part is that these changes are very local and for the rest of the training code it doesn't make any difference. In runtime, however, these is a big difference, namely embedding will be chunked into 3 shards, each pinned to a different ps task, which you can run on a separate machine. See also this relevant question.

Body:
Yes, it is possible in tensorflow out-of-the-box. The trick is to use variable partitioning, e.g. tf.fixed_size_partitioner, and parameter server replication via tf.train.replica_device_setter to split the variable across several machines. Here's how it looks like in code:

with tf.device(tf.train.replica_device_setter(ps_tasks=3)):
  embedding = tf.get_variable("embedding", [1000000000, 20],
                              partitioner=tf.fixed_size_partitioner(3))

The best part is that these changes are very local and for the rest of the training code it doesn't make any difference. In runtime, however, these is a big difference, namely embedding will be chunked into 3 shards, each pinned to a different ps task, which you can run on a separate machine. See also this relevant question.


问:
SQL Server database tuning advisor suggests existing clustered index
I have a table whose definition looks like this:

```<code>CREATE TABLE Budget_Cost_Centers
(
    CostCenterIDX INT NOT NULL,
    Name VARCHAR(100) NOT NULL,
    ...
    CONSTRAINT PK_Budget_Cost_Centers
        PRIMARY KEY CLUSTERED (CostCenterIDX ASC)
);
</code>```

(some columns were left out because they are not relevant)

I now run the Database Tuning Advisor on a query against this table and it suggests:

```<code>CREATE NONCLUSTERED INDEX [_dta_index_Budget_Cost_Centers_5_1079674894__K1]
ON [dbo].[Budget_Cost_Centers] ([COSTCENTERIDX] ASC)
   WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
</code>```

Which is obviously the same as the existing primary key. Any idea why it would suggest this? Trying to make sure I'm not missing something about how SQL Server works as opposed to the advisor suggesting something ridiculous because that's just the limitations of automated tuning analysis.

More info: I broke down the query that was producing this recommendation to the bare essentials:

```<code>select
    d.PhaseIDX,
    sum(d.YTDActual) YTDActual
from
    Budget_Cost_Centers cc
join
    Budget_Cost_Centers mc on cc.MasterCostCenteridx = mc.CostCenterIDX
join
    Budget_Detail d on cc.CostCenterIDX= d.CostCenterIDX
group by
    d.PhaseIDX
</code>```

The table self-references and the query author joined it to itself in order to filter the records to only those that contained said reference. Changing the query to the following equivalent results in the advisor no longer making the recommendation:

```<code>select
    d.PhaseIDX,
    sum(d.YTDActual) YTDActual
from
    Budget_Cost_Centers cc
join
    Budget_Detail d on cc.CostCenterIDX = d.CostCenterIDX
where
    cc.MasterCostCenterIDX is not null
group by
    d.PhaseIDX
</code>```

Here is the execution plan with the original sql:

答:
The PK is clustered and the other is not clustered. There may be an advantage to having both.

Non-clustered index and clustered index on the same column

Body:
I have a table whose definition looks like this:

CREATE TABLE Budget_Cost_Centers
(
    CostCenterIDX INT NOT NULL,
    Name VARCHAR(100) NOT NULL,
    ...
    CONSTRAINT PK_Budget_Cost_Centers
        PRIMARY KEY CLUSTERED (CostCenterIDX ASC)
);

(some columns were left out because they are not relevant)

I now run the Database Tuning Advisor on a query against this table and it suggests:

CREATE NONCLUSTERED INDEX [_dta_index_Budget_Cost_Centers_5_1079674894__K1]
ON [dbo].[Budget_Cost_Centers] ([COSTCENTERIDX] ASC)
   WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]

Which is obviously the same as the existing primary key. Any idea why it would suggest this? Trying to make sure I'm not missing something about how SQL Server works as opposed to the advisor suggesting something ridiculous because that's just the limitations of automated tuning analysis.

More info: I broke down the query that was producing this recommendation to the bare essentials:

select
    d.PhaseIDX,
    sum(d.YTDActual) YTDActual
from
    Budget_Cost_Centers cc
join
    Budget_Cost_Centers mc on cc.MasterCostCenteridx = mc.CostCenterIDX
join
    Budget_Detail d on cc.CostCenterIDX= d.CostCenterIDX
group by
    d.PhaseIDX

The table self-references and the query author joined it to itself in order to filter the records to only those that contained said reference. Changing the query to the following equivalent results in the advisor no longer making the recommendation:

select
    d.PhaseIDX,
    sum(d.YTDActual) YTDActual
from
    Budget_Cost_Centers cc
join
    Budget_Detail d on cc.CostCenterIDX = d.CostCenterIDX
where
    cc.MasterCostCenterIDX is not null
group by
    d.PhaseIDX

Here is the execution plan with the original sql:


问:
aws lambda js unit testing
I've been looking into aws lambda. How are people testing the harness for api gateway requests responses? In Java I have a lambda that's a bit like this.

```<code>import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
...
@Test
void turnsBarToFooTest() {

    TestContext ctx = new TestContext(); //implements  com.amazonaws.services.lambda.runtime.Context

    Fooer handler = new Fooer();

    APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent();
    Map<String, String> params = HashMap.of("thing_to_foo", "bar");
    request.setPathParameters(params.toJavaMap());

    APIGatewayProxyResponseEvent response = handler.handleRequest(request, ctx);
    assertEquals(200, response.getStatusCode().intValue());
    assertEquals("foo", response.getBody());
}
</code>```

I'd love to do something really simple with Jest and ES6 to replicate the above. Are there similar known events objects to use? How can I wire them up with jest.

答:
I've got jest doing what I wanted. Martin's idea of the test responses will be helpful as it gets more involved, thanks.</p>

```<code>test('fooer will foo a bar', done => {

  const context = {}
  const request = {pathParameters:{thing_to_foo:'foo'}}
  const callback = (bar, foo) => {
    expect(foo.body).toBe('bar')
    done()
  }
  myHandler.handler(request, context, callback)

})
</code>```

Title: aws lambda js unit testing

Body:
I've been looking into aws lambda. How are people testing the harness for api gateway requests responses? In Java I have a lambda that's a bit like this.

import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
...
@Test
void turnsBarToFooTest() {

    TestContext ctx = new TestContext(); //implements  com.amazonaws.services.lambda.runtime.Context

    Fooer handler = new Fooer();

    APIGatewayProxyRequestEvent request = new APIGatewayProxyRequestEvent();
    Map<String, String> params = HashMap.of("thing_to_foo", "bar");
    request.setPathParameters(params.toJavaMap());

    APIGatewayProxyResponseEvent response = handler.handleRequest(request, ctx);
    assertEquals(200, response.getStatusCode().intValue());
    assertEquals("foo", response.getBody());
}

I'd love to do something really simple with Jest and ES6 to replicate the above. Are there similar known events objects to use? How can I wire them up with jest.

Body:
I've got jest doing what I wanted. Martin's idea of the test responses will be helpful as it gets more involved, thanks.

test('fooer will foo a bar', done => {

  const context = {}
  const request = {pathParameters:{thing_to_foo:'foo'}}
  const callback = (bar, foo) => {
    expect(foo.body).toBe('bar')
    done()
  }
  myHandler.handler(request, context, callback)

})


问:
How to find if 3 numbers in a set of size N exactly sum up to M
I want to know how I can implement a better solution than O(N^3). Its similar to the knapsack and subset problems. In my question N<=8000, so i started computing sums of pairs of numbers and stored them in an array. Then I would binary search in the sorted set for each (M-sum[i]) value but the problem arises how will I keep track of the indices which summed up to sum[i]. I know I could declare extra space but my Sums array already has a size of 64 million, and hence I couldn't complete my O(N^2) solution. Please advice if I can do some optimization or if I need some totally different technique.</p>

答:
Create a "bitset" of all the numbers which makes it constant time to check if a number is there. That is a start.

The solution will then be at most O(N^2) to make all combinations of 2 numbers.

The only tricky bit here is when the solution contains a repeat, but it doesn't really matter, you can discard repeats unless it is the same number 3 times because you will hit the "repeat" case when you pair up the 2 identical numbers and see if the unique one is present.

The 3 times one is simply a matter of checking if M is divisible by 3 and whether M/3 appears 3 times as you create the bitset.

This solution does require creating extra storage, up to MAX/8 where MAX is the highest number in your set. You could use a hash table though if this number exceeds a certain point: still O(1) lookup.


问:
Finding it difficult to pass data to separate viewController
I have searched through the net for couple of hours now thought this would be an easy task, but things are not going as planned. This question is edited, some of great fella has given great answer but I am still struggling.

Here is the scenario, I have a viewControllerA which is always visible. There is a small button on top of this view, when I click it there comes viewControllerB as a static tableViewController. Its a slide view from left to right to be honest like other apps.

There is one section and couple of rows in the tableView, when I tap 4th row I present viewControllerC, there is a UISwitch button there. When I dismiss the viewControllerC, viewControllerA appear again. viewControllerB is my menu controller therefore its not my greater concern .Now I want to pass data from viewControllerC to viewControllerA. Here is my broken code:

for viewControllerC :

```<code>class viewControllerC: UIViewController {
 ..//
 @IBAction func switchTapped(_ sender: UISwitch) {
     let vc = viewControllerA()
     if sender.isOn == true {
         vc.state = true
     } else if sender.isOn == false {
         vc.state = false
     }
  }
 ..//
}
</code>```

for viewControllerA :

```<code>class viewControllerA: UIViewController, GMSMapViewDelegate {
  var state:Bool?
  ...//
  if self.state == true {
      self.mapView.isTrafficEnabled = true
    } else {
      self.mapView.isTrafficEnabled = false
   }
}
</code>```

But its not working an I know I am not heading to the right direction. As you can see from the example I want to send ture when UISwitch is on and false when its off from viewControllerC to viewControllerA. Some of the folks have suggested delegate method but I am still struggling. I was following this link , I think "Passing data backwards through the shared state of the app" section meets my criteria. Although I need help. Thanks in advance.

答:
You can pass data with Delegate pattern, here's an idea:</p>

```<code>import UIKit

// Make a delegate protocol
protocol ViewControllerBDelegate: class {
    func didTapSwitch(isOn: Bool)
}

class ViewControllerB: UIViewController {

    // Make a weak delegate reference in VC B
    weak var delegate: ViewControllerBDelegate?

    var state: Bool?

    // On action trigger delegate method:
    @IBAction func switchTapped(_ sender: UISwitch) {
        delegate?.didTapSwitch(isOn: sender.isOn)
    }

}

class ViewControllerA: UIViewController {

    var stateFromSwitch: Bool?
    // In this VC you are instantiating viewController B
    // ... code ...
    // set delegate: viewControllerB.delegate = self
}

// implement ViewControllerBDelegate
extension ViewControllerA: ViewControllerBDelegate {
    func didTapSwitch(isOn: Bool) {
        stateFromSwitch = isOn
    }
}
</code>```

Body:
I have searched through the net for couple of hours now thought this would be an easy task, but things are not going as planned. This question is edited, some of great fella has given great answer but I am still struggling.

Here is the scenario, I have a viewControllerA which is always visible. There is a small button on top of this view, when I click it there comes viewControllerB as a static tableViewController. Its a slide view from left to right to be honest like other apps.

There is one section and couple of rows in the tableView, when I tap 4th row I present viewControllerC, there is a UISwitch button there. When I dismiss the viewControllerC, viewControllerA appear again. viewControllerB is my menu controller therefore its not my greater concern .Now I want to pass data from viewControllerC to viewControllerA. Here is my broken code:

for viewControllerC :

class viewControllerC: UIViewController {
 ..//
 @IBAction func switchTapped(_ sender: UISwitch) {
     let vc = viewControllerA()
     if sender.isOn == true {
         vc.state = true
     } else if sender.isOn == false {
         vc.state = false
     }
  }
 ..//
}

for viewControllerA :

class viewControllerA: UIViewController, GMSMapViewDelegate {
  var state:Bool?
  ...//
  if self.state == true {
      self.mapView.isTrafficEnabled = true
    } else {
      self.mapView.isTrafficEnabled = false
   }
}

But its not working an I know I am not heading to the right direction. As you can see from the example I want to send ture when UISwitch is on and false when its off from viewControllerC to viewControllerA. Some of the folks have suggested delegate method but I am still struggling. I was following this link , I think "Passing data backwards through the shared state of the app" section meets my criteria. Although I need help. Thanks in advance.

Body:
You can pass data with Delegate pattern, here's an idea:

import UIKit

// Make a delegate protocol
protocol ViewControllerBDelegate: class {
    func didTapSwitch(isOn: Bool)
}

class ViewControllerB: UIViewController {

    // Make a weak delegate reference in VC B
    weak var delegate: ViewControllerBDelegate?

    var state: Bool?

    // On action trigger delegate method:
    @IBAction func switchTapped(_ sender: UISwitch) {
        delegate?.didTapSwitch(isOn: sender.isOn)
    }

}

class ViewControllerA: UIViewController {

    var stateFromSwitch: Bool?
    // In this VC you are instantiating viewController B
    // ... code ...
    // set delegate: viewControllerB.delegate = self
}

// implement ViewControllerBDelegate
extension ViewControllerA: ViewControllerBDelegate {
    func didTapSwitch(isOn: Bool) {
        stateFromSwitch = isOn
    }
}


问:
serialize inputs inside element (not form)
I have a HTML like:

```<code><table>
    <tr id="01">
        <td><input name="x"></td>
        <td><input name="y"></td>
    </tr>
    <tr id="02">
        <td><input name="x"></td>
        <td><input name="y"></td>
    </tr>
</table>
</code>```

And I'm trying to make a JSON string of the inputs only on a specific row. Would there be a good solution for this? Something like:

```<code>json = $('#01').serialize();
</code>```

but I need a json instead of the URLEncode'd string the serialize() provides.

答:
You can use  $("#01 input").serialize().

$('#abc').click(function(){
    json = $("#01 input").serialize().replace(/%20/g, "+");
    console.log(json);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
    <tr id="01">
        <td><input name="x"></td>
        <td><input name="y"></td>
    </tr>
    <tr id="02">
        <td><input name="x"></td>
        <td><input name="y"></td>
    </tr>
</table>
<button id = "abc">serialize 01</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script></code>```

Body:
I have a HTML like:

        <input name="x">
        <input name="y">

        <input name="x">
        <input name="y">

And I'm trying to make a JSON string of the inputs only on a specific row. Would there be a good solution for this? Something like:

json = $('#01').serialize();

but I need a json instead of the URLEncode'd string the serialize() provides.

Body:
You can use  $("#01 input").serialize().

$('#abc').click(function(){
    json = $("#01 input").serialize().replace(/%20/g, "+");
    console.log(json);
});

<table>
    <tr id="01">
        <td><input name="x"></td>
        <td><input name="y"></td>
    </tr>
    <tr id="02">
        <td><input name="x"></td>
        <td><input name="y"></td>
    </tr>
</table>
<button id = "abc">serialize 01</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


问:
Memory leaks caused due to CoreFoundation Framework
I am developing an iPhone application which mainly makes use of the Address Book and database. After fetching about 3000 contacts from the address book, I am attaching string tags to the contacts (5 for each). I am saving my tags in the database.

For Load testing purpose i have added 10,000 tags to the App. But during the load testing of my application, I observed some memory leaks which were not related to the Application code but represents a set of Instruction sets. Also Instruments showed Foundation as the  responsible library for the Leak (Extensive use of NSString,NSDictionary,NSArray which belongs to the Foundation framework). My application crashes after 10 - 15 mins of usage.The Crash report mentions, application crashed due to low memory.

Memory profiling using CLANG shows zero leaks. How do i solve these memory leaks?
Are these leaks the real culprit behind the crash? Are there any other tools available to check memory leaks?

答:
I often find my leaks say they're caused by Core Foundation (or any other framework for that matter) but are really my own. With the exception of the Simulator, rarely will you find excessive leaking in the frameworks.

If you open up the detail panel to the right in Instruments you may find listed your App's methods in there. That will give you indication of where it could be coming from in your code. One leak can spring many other leaks, and you may have to find the top level culprit to get rid of the lower level ones.

You should not expect Clang to do anything but find the most obvious leaks. It's very handy, but that's it, just a helpful addition to compiling.


问:
Sort Entry Set of String, Integer by more than one field
Have a Map<String, Integer> and trying to sort on value and length of String. I am trying to compare two different things in the statement so don't know if I need two different statements.  This is being used to compare digit root so the String length and then the digit root is the value and the value.

For example:

```<code>("103",4); (1+0+3 == 4)
("4",4); (4 ==4)
("11101",4); (1+1+1+0+1 == 4)
("5",5); (5 == 5 )
("1003",4); (1+0+0+3 == 4)
</code>```

But ("103",4) > ("4",4) because the length of "103" > "4", and ("11101",4) > ("103",4);, length "11101" > "103"

```<code>Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int length = o1.getKey().length().compareTo(o2.getKey().length());
if(length != 0) {
 return length;
}
return (o1.getValue()).compareTo(o2.getValue());
}
});
</code>```

Edit Answered to the above Question(Also, response given)

```<code> Map<String,Integer> unsortMap = new.
                        TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4); Map<String,

 Integer> result =unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length)) )
   .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap
     (Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

 System.println(result);
</code>```

答:
You can compare in this way, if you are aiming to sort with length.</p>

```<code>Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {

    @Override
    public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
        // TODO Auto-generated method stub

        if (o1.getKey().length() == o2.getKey().length()) {
            return 0;
        }

        if (o1.getKey().length() > o2.getKey().length()) {
            return 1;
        } else {
            return -1;
        }

    }

});
</code>```

Body:
Have a Map<String, Integer> and trying to sort on value and length of String. I am trying to compare two different things in the statement so don't know if I need two different statements.  This is being used to compare digit root so the String length and then the digit root is the value and the value.

For example:

("103",4); (1+0+3 == 4)
("4",4); (4 ==4)
("11101",4); (1+1+1+0+1 == 4)
("5",5); (5 == 5 )
("1003",4); (1+0+0+3 == 4)

But ("103",4) > ("4",4) because the length of "103" > "4", and ("11101",4) > ("103",4);, length "11101" > "103"

Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int length = o1.getKey().length().compareTo(o2.getKey().length());
if(length != 0) {
 return length;
}
return (o1.getValue()).compareTo(o2.getValue());
}
});

Edit Answered to the above Question(Also, response given)

 Map<String,Integer> unsortMap = new.
                        TreeMap<String,Integer>();

unsortMap.put("103",4);
unsortMap.put("4",4);
unsortMap.put("11101",4);
unsortMap.put("5",5);
unsortMap.put("1003",4); Map<String,

 Integer> result =unsortMap.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.comparingInt(String::length)) )
   .sorted(Map.Entry.comparingByValue()) .collect(Collectors.toMap
     (Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

 System.println(result);

Body:
You can compare in this way, if you are aiming to sort with length.

Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {

    @Override
    public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
        // TODO Auto-generated method stub

        if (o1.getKey().length() == o2.getKey().length()) {
            return 0;
        }

        if (o1.getKey().length() > o2.getKey().length()) {
            return 1;
        } else {
            return -1;
        }

    }

});


问:
Return deleted docs data returns undefined
I am using Google Cloud Function, but since it runs on a older version of Node, I can not use this answer anymore. I want a function that will batch delete all the documents in a collection and returns the data from it. This is my attempt:

```<code>function deleteCollectionAndReturnResults(db, collectionRef, batchSize) {
  var query = collectionRef.limit(batchSize);
  return deleteQueryBatch(db, query, batchSize, []);
}

function deleteQueryBatch(db, query, batchSize, results) {
  return query.get().then(snapshot => {
    if (snapshot.size == 0) return 0;
    var batch = db.batch();
    snapshot.docs.forEach(doc => {
      if (doc.exists) {results.push(doc);}
      batch.delete(doc.ref);
    });
    return batch.commit().then(() => snapshot.size);
  }).then(function(numDeleted) {
    if (numDeleted >= batchSize) {
      return deleteQueryBatch(db, query, batchSize, results);
    }else{
      return results
    }
  });
}
</code>```

But when I run it like this:

```<code>exports.tester = functions.firestore.document('x/{x}').onCreate(event => {
      deleteCollectionAndReturnResults(db, db.collection("x"), 100).then(docs => {
        console.log(docs)
      })
})
</code>```

This is my output:

Is there something wrong why I do get the 'function returned undefined'?

答:
Your tester function doesn't return anything.  Instead, it should return a promise that's resolved when all the work is complete.  It looks like you've simply forgotten to return the promise returned by deleteCollectionAndReturnResults:

```<code>exports.tester = functions.firestore.document('x/{x}').onCreate(event => {
    return deleteCollectionAndReturnResults(db, db.collection("x"), 100).then(docs => {
        console.log(docs)
    })
})
</code>```

Body:
I am using Google Cloud Function, but since it runs on a older version of Node, I can not use this answer anymore. I want a function that will batch delete all the documents in a collection and returns the data from it. This is my attempt:

function deleteCollectionAndReturnResults(db, collectionRef, batchSize) {
  var query = collectionRef.limit(batchSize);
  return deleteQueryBatch(db, query, batchSize, []);
}

function deleteQueryBatch(db, query, batchSize, results) {
  return query.get().then(snapshot => {
    if (snapshot.size == 0) return 0;
    var batch = db.batch();
    snapshot.docs.forEach(doc => {
      if (doc.exists) {results.push(doc);}
      batch.delete(doc.ref);
    });
    return batch.commit().then(() => snapshot.size);
  }).then(function(numDeleted) {
    if (numDeleted >= batchSize) {
      return deleteQueryBatch(db, query, batchSize, results);
    }else{
      return results
    }
  });
}

But when I run it like this:

exports.tester = functions.firestore.document('x/{x}').onCreate(event => {
      deleteCollectionAndReturnResults(db, db.collection("x"), 100).then(docs => {
        console.log(docs)
      })
})

This is my output:

Is there something wrong why I do get the 'function returned undefined'?

Body:
Your tester function doesn't return anything.  Instead, it should return a promise that's resolved when all the work is complete.  It looks like you've simply forgotten to return the promise returned by deleteCollectionAndReturnResults:

exports.tester = functions.firestore.document('x/{x}').onCreate(event => {
    return deleteCollectionAndReturnResults(db, db.collection("x"), 100).then(docs => {
        console.log(docs)
    })
})


问:
Unexpected Error while executing imgkit
I'm a newbie to Python, While learning imgkit (PI module) I got this error which was not expected for a simple code. Below is the code

```<code>import imgkit

imgkit.from_url('https://www.google.co.in/','fs.jpg')
</code>```

and the error which I got is

```<code>Traceback (most recent call last):
  File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\config.py", line 30, in __init__
    with open(self.wkhtmltoimage):
FileNotFoundError: [Errno 2] No such file or directory: b''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\ALEXANDER\Desktop\def img.py", line 3, in <module>
    imgkit.from_url('https://www.google.co.in/','fs.jpg')
  File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\api.py", line 20, in from_url
    rtn = IMGKit(url, 'url', options=options, toc=toc, cover=cover, config=config, cover_first=cover_first)
  File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\imgkit.py", line 34, in __init__
    self.config = Config() if not config else config
  File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\config.py", line 36, in __init__
    'http://wkhtmltopdf.org\n'.format(self.wkhtmltoimage))
OSError: No wkhtmltoimage executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - http://wkhtmltopdf.org
</code>```

Could anyone tell me what mistake I have done.

答: It looks like you need to install wkhtmltopdf. To do so, run pip install wkhtmltopdf

Title: Unexpected Error while executing imgkit

Body:
I'm a newbie to Python, While learning imgkit (PI module) I got this error which was not expected for a simple code. Below is the code

import imgkit

imgkit.from_url('https://www.google.co.in/','fs.jpg')

and the error which I got is

Traceback (most recent call last):
  File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\config.py", line 30, in __init__
    with open(self.wkhtmltoimage):
FileNotFoundError: [Errno 2] No such file or directory: b''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\ALEXANDER\Desktop\def img.py", line 3, in <module>
    imgkit.from_url('https://www.google.co.in/','fs.jpg')
  File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\api.py", line 20, in from_url
    rtn = IMGKit(url, 'url', options=options, toc=toc, cover=cover, config=config, cover_first=cover_first)
  File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\imgkit.py", line 34, in __init__
    self.config = Config() if not config else config
  File "G:\python\lib\site-packages\imgkit-0.1.8-py3.6.egg\imgkit\config.py", line 36, in __init__
    'http://wkhtmltopdf.org\n'.format(self.wkhtmltoimage))
OSError: No wkhtmltoimage executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - http://wkhtmltopdf.org

Could anyone tell me what mistake I have done.


问:
Prevent python script from running if another one is being executed
I have two scripts inside a bigger system I'm developing. Lets call one foo.py and the other one bar.py.

foo creates files that bar will afterwards read and delete. Now, if foo is running and working on a file, bar will mess things up by working on the same file before foo is finished.

foo and bar get started automatically by other stuff, not manually by someone that runs them. How can I make sure that, if foo is working on a file, bar will not start?

I have thought about editing both of them so that foo writes a 1 to a text file at the beginning of the execution and a 0 when it finishes, and to make bar read the text file to check wheter it can start. But I'm not really sure this is the most elegant solution, and also I don't want to block bar if foo ever fails in the middle of execution, leaving the file at 1.

答:
You can use subprocess

In your main file:

```<code>import subprocess

def main():
    p = subprocess.Popen(['python', 'foo.py'])
    res = p.wait()
    if res == 0:
        print("foo did ok")
        # execute bar.py
    else:
        print("foo failed along the way")
</code>```

In foo.py, make sure to exit with code 0 if everything went fine:
exit(0) (this will be returned to res in main script).

You can also use poll() if you want to do other stuff while waiting for foo to finish.

```<code>def main():
    p = subprocess.Popen(['python', 'foo.py'])

    while not p.poll()==0:
        print("wait for foo")
        #do some other magic. but make sure to have a break condition
        # e.g. if foo takes too long.
</code>```

Body:
You can use subprocess

In your main file:

import subprocess

def main():
    p = subprocess.Popen(['python', 'foo.py'])
    res = p.wait()
    if res == 0:
        print("foo did ok")
        # execute bar.py
    else:
        print("foo failed along the way")

In foo.py, make sure to exit with code 0 if everything went fine:
exit(0) (this will be returned to res in main script).

You can also use poll() if you want to do other stuff while waiting for foo to finish.

def main():
    p = subprocess.Popen(['python', 'foo.py'])

    while not p.poll()==0:
        print("wait for foo")
        #do some other magic. but make sure to have a break condition
        # e.g. if foo takes too long.


问:
Custom workspace in jenkins

I am not getting the check box to select custom workspace in Jenkins(ver. 1.465) while configuring the job, is there any plugin to get it?

After getting check box how to configure (path of workspace)?

答:
A couple of images to clarify how to configure a custom workspace directory.

The "Advanced" button to click to show the "Workspace Root Directory" option:

Use a root directory with ${ITEM_FULLNAME} to put your projects' workspaces under a custom directory:
<img src="https://i.stack.imgur.com/x9X0k.png" alt="Use a root directory with ${ITEM_FULLNAME} to put your projects' workspaces under a custom directory">

Title: Custom workspace in jenkins


问:
WebGL THREE: changing position of obj, but the object doesn't move
I am working with an object which i loaded like this (I save it as a global variable such that I can change it later):

```<code>model1 = null;

var mtlLoader = new THREE.MTLLoader();
  mtlLoader.load("http://blabla.mtl", function(materials) {
  materials.preload();
  var objLoader = new THREE.OBJLoader();
  objLoader.setMaterials(materials);
  objLoader.load("http://blabla.obj", function(object) {
    object.scale.x = 0.0004;
    object.scale.y = 0.0004;
    object.scale.z = 0.0004;
    object.rotateX(Math.PI / 2);
    object.rotateZ(Math.PI / 2);
    object.add(new THREE.AxisHelper(2))
    model1 = object;     //save in global variables
    scene.add(model1);
   });
});
</code>```

When I am rendering I want to change the position of the model, based on a box's change in position:

```<code>function render(ms: number) {
  if (lastTime) {
    update((ms-lastTime)/1000)
  }

  lastTime = ms
  requestAnimationFrame(render)
  renderer.render( scene, camera )
}

var pos_current;
var pos_new;
var trans;

function update(dt: number) {
  if (pause.on) return

  //save position of box before it is transformed
  pos_current = box.position.clone();

  box.updatePosition()

  //save new position of box
  pos_new = box.position.clone();

  //transform the 3D-model according to the box's transformation
  trans = pos_current.sub(pos_new);

  model1.position.add(trans);
  console.log(model1.position)
</code>```

I can in the console see that the position of model1 changes, but the object just doesn't move at all, and I can't really figure out why.

Any help is very appreciated :)

答: Got it to work - the problem was that I was trying to update the position of model1, before it was actually done loading in the obj-loader :D</p>

Body:
I am working with an object which i loaded like this (I save it as a global variable such that I can change it later):

model1 = null;

var mtlLoader = new THREE.MTLLoader();
  mtlLoader.load("http://blabla.mtl", function(materials) {
  materials.preload();
  var objLoader = new THREE.OBJLoader();
  objLoader.setMaterials(materials);
  objLoader.load("http://blabla.obj", function(object) {
    object.scale.x = 0.0004;
    object.scale.y = 0.0004;
    object.scale.z = 0.0004;
    object.rotateX(Math.PI / 2);
    object.rotateZ(Math.PI / 2);
    object.add(new THREE.AxisHelper(2))
    model1 = object;     //save in global variables
    scene.add(model1);
   });
});

When I am rendering I want to change the position of the model, based on a box's change in position:

function render(ms: number) {
  if (lastTime) {
    update((ms-lastTime)/1000)
  }

  lastTime = ms
  requestAnimationFrame(render)
  renderer.render( scene, camera )
}

var pos_current;
var pos_new;
var trans;

function update(dt: number) {
  if (pause.on) return

  //save position of box before it is transformed
  pos_current = box.position.clone();

  box.updatePosition()

  //save new position of box
  pos_new = box.position.clone();

  //transform the 3D-model according to the box's transformation
  trans = pos_current.sub(pos_new);

  model1.position.add(trans);
  console.log(model1.position)

I can in the console see that the position of model1 changes, but the object just doesn't move at all, and I can't really figure out why.

Any help is very appreciated :)


问:
What is the difference between router.METHOD() and router.route() methods in Express
I've seen code written both ways.

```<code>router.get(path, callback)
</code>```

and

```<code>router.route(path).get(callback)
</code>```

From the surrounding code they look equivalent.  The docs are here:

router.route

and

router.METHOD

where method can be get, post, etc.

Why are there two ways to do this?  I've read the docs and they did not help so much.

答:
These are just two of the methods of the router object provided by express. According to the documentation there are a total of five methods associated with the router object.

As you have specifically asked for the router.METHOD() & router.route(), so I will only be focussing on these two methods.

To begin with, let us take router.MEHTOD() method first. It simply matches the incoming requests with the path provided and performs the suitable action as per the METHOD used. METHOD is one of the HTTP methods, such as get, put, post and so on.Here, the catch is that sometimes it becomes cumbersome to deal with such different naming conventions and may also lead to duplicate route naming and things just get messed up eventually when dealing with large and complex apps.

However, in the case of router.route() method, it returns an instance of a single route(path provided) which can then be used with the http verbs. It re-uses the path provided which avoids confusion and makes the code look clean and hence less chances of errors.

Body:
I've seen code written both ways.

router.get(path, callback)

and

router.route(path).get(callback)

From the surrounding code they look equivalent.  The docs are here:

router.route

and

router.METHOD

where method can be get, post, etc.

Why are there two ways to do this?  I've read the docs and they did not help so much.