问:
Getting position in linked list from method

In this function (part of a bigger contact book program I am working on) it displays an item in a linked list, or in my case a contact. I would like to get the position of this item in the linked list, in order to delete the contact and add it back to the linked list.

```<code>void display_contact(std::string first, std::string last)
{
        bool found;

        node *curr = head;
        found = false;

        while (curr != NULL & !found)
        {
            if (curr->firstName == first)
            {
                found = true;
            }
            else if (curr->lastName == last)
            {
                found = true;
            }
            else
            {
                curr = curr->next;
            }

        }
        if (found)
        {
            std::cout << "First Name: " << curr->firstName << "\n";
            std::cout << "Last Name: " << curr->lastName << "\n";
            std::cout << "Phone Number: " << curr->phoneNumber << "\n";
            std::cout << "Editing contacts is coming soon.\n";
        }
        else
        {
            std::cout << "\n" << first << " " << last << " was not found.\n";
        }
}
</code>```

The actual result I get right now is just the contact information (Variables from the linked list)

答:
```<code>node *curr = head;
found = false;
int idx = -1;
while (curr != NULL & !found)
{
    idx++;
    ....
 }
</code>```

<p>if found idx has the index         </p>

Body:
In this function (part of a bigger contact book program I am working on) it displays an item in a linked list, or in my case a contact. I would like to get the position of this item in the linked list, in order to delete the contact and add it back to the linked list.

void display_contact(std::string first, std::string last)
{
        bool found;

        node *curr = head;
        found = false;

        while (curr != NULL & !found)
        {
            if (curr->firstName == first)
            {
                found = true;
            }
            else if (curr->lastName == last)
            {
                found = true;
            }
            else
            {
                curr = curr->next;
            }

        }
        if (found)
        {
            std::cout << "First Name: " << curr->firstName << "\n";
            std::cout << "Last Name: " << curr->lastName << "\n";
            std::cout << "Phone Number: " << curr->phoneNumber << "\n";
            std::cout << "Editing contacts is coming soon.\n";
        }
        else
        {
            std::cout << "\n" << first << " " << last << " was not found.\n";
        }
}

The actual result I get right now is just the contact information (Variables from the linked list)

Body:
node *curr = head;
found = false;
int idx = -1;
while (curr != NULL & !found)
{
    idx++;
    ....
 }

if found idx has the index


来源: stackexchange

问:
Chrome Extension: how to capture selected text and send to a web service
For the Google Chrome extension, I need to capture selected text in a web page and send to a web service.  I'm stuck!

First I tried a bookmarklet, but Chrome on Mac seems to have some bookmarklet bugs so I decided to write an extension.

I use this code in my ext:

```<code>function getSelText(){
    var txt = 'nothing';
    if (window.getSelection){
        txt = "1" + window.getSelection();
    } else if (document.getSelection) {
        txt = "2" + document.getSelection();
    } else if (document.selection) {
        txt = "3" + document.selection.createRange().text;
    } else txt = "wtf";
    return txt;
}
var selection = getSelText();
alert("selection = " + selection);
</code>```

When I click on my extension icon, I get a "1".  So I think the act of selecting outside the browser window is causing the text to not be seen by the browser as "selected" any more.

Just a theory....

thoughts?

答:
You don't need a Google API for something as simple as this...

I'll use the Bing online service as an example. Note that the URL is set up to accept a parameter:

```<code>var WebService='http://www.bing.com/translator/?text=';

frameID.contentWindow.document.body.addEventListener('contextmenu',function(e){

 T=frameID.contentWindow.getSelection().toString();

 if(T!==''){e.preventDefault(); Open_New_Tab(WebService+encodeURIComponent(T)); return false;}

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

NB: The function "Open_New_Tab()" used above is an imaginary one that accepts the webservice URL with the encoded selected text as a parameter.

That's the idea basically.

ContentLicense: CC BY-SA 2.5

Body:
For the Google Chrome extension, I need to capture selected text in a web page and send to a web service.  I'm stuck!

First I tried a bookmarklet, but Chrome on Mac seems to have some bookmarklet bugs so I decided to write an extension.

I use this code in my ext:

function getSelText(){
    var txt = 'nothing';
    if (window.getSelection){
        txt = "1" + window.getSelection();
    } else if (document.getSelection) {
        txt = "2" + document.getSelection();
    } else if (document.selection) {
        txt = "3" + document.selection.createRange().text;
    } else txt = "wtf";
    return txt;
}
var selection = getSelText();
alert("selection = " + selection);

When I click on my extension icon, I get a "1".  So I think the act of selecting outside the browser window is causing the text to not be seen by the browser as "selected" any more.

Just a theory....

thoughts?

Body:
You don't need a Google API for something as simple as this...

I'll use the Bing online service as an example. Note that the URL is set up to accept a parameter:

var WebService='http://www.bing.com/translator/?text=';

frameID.contentWindow.document.body.addEventListener('contextmenu',function(e){

 T=frameID.contentWindow.getSelection().toString();

 if(T!==''){e.preventDefault(); Open_New_Tab(WebService+encodeURIComponent(T)); return false;}

},false);

NB: The function "Open_New_Tab()" used above is an imaginary one that accepts the webservice URL with the encoded selected text as a parameter.

That's the idea basically.

ContentLicense: CC BY-SA 3.0


问:
What can't be done in CSS yet?
A while ago I was trying to figure out a way of doing this without using a table layout:

```<code><table>
  <tr><td rowspan="2">Left column</td></tr>
  <tr><td>Right Top</td><td>Right bottom</td></tr>
</table>
</code>```

Eventually I gave up and decided that it's impossible to do without tables (okay, CSS 3 might be able to, but waiting another 5-10 years isn't practical).

Has anyone got more examples like this? (Or even better, can you show me I was wrong?)

答:
Someone answered the question if the design was doable. But I have an example of a thing that can't be done with css. For some reason you need to set a table's cellspacing and cellpadding explicitly. It can't be set through css even though there is the margin and padding property. This is something I've thought to be incredibly annoying because I always want to control the margin and padding on tables through css.

E.g.

```<code><h1> This table won't have it's margin or padding reset </h1>
<table style="padding: 0; margin: 0;">
    <tr><td>a</td><td>b</td></tr>
</table>

<h1> This table will... </h1>
<table cellspacing="0" cellpadding="0">
    <tr><td>a</td><td>b</td></tr>
</table>
</code>```

Title: What can't be done in CSS yet?

Body:
A while ago I was trying to figure out a way of doing this without using a table layout:

Left column

Right Top	Right bottom

Eventually I gave up and decided that it's impossible to do without tables (okay, CSS 3 might be able to, but waiting another 5-10 years isn't practical).

Has anyone got more examples like this? (Or even better, can you show me I was wrong?)

Body:
Someone answered the question if the design was doable. But I have an example of a thing that can't be done with css. For some reason you need to set a table's cellspacing and cellpadding explicitly. It can't be set through css even though there is the margin and padding property. This is something I've thought to be incredibly annoying because I always want to control the margin and padding on tables through css.

E.g.

<h1> This table won't have it's margin or padding reset </h1>
<table style="padding: 0; margin: 0;">
    <tr><td>a</td><td>b</td></tr>
</table>

<h1> This table will... </h1>
<table cellspacing="0" cellpadding="0">
    <tr><td>a</td><td>b</td></tr>
</table>

OwnerDisplayName: Spoike


问:
Using Switch-blocks to Parse input for a Text Adventure?
Okay, I have a goal right now to make a basic text adventure. To do this, however, I would need/want to have a switch statement that can do the following:

Check to see if a string has a word SOMEWHERE inside.

Check to see if a string has two words in any combination somewhere inside.

How would I accomplish this? Could you show me coding for this specific example:

A user is prompted for data. A switch statement checks for "look box" as one case, and "sleep" as another. The program doesn't care what order any words are in, but does care about the order of the letters.

Please explain everything in detail. I just started coding.

EDIT: Thank you for all the answers. I understand there are better, more complicated, and more useful ways of handling this, but it just isn't at my level yet.

答:
You can't do this using switch, you'll have to use the if-else-if type of structure.

```<code>string input=...
if(input.Contains("sleep")){ //contains sleep?
  //do stuff for some word
}else if(input.Contains("look") && input.Contains("box")){ //contains look and box
  //do stuff for the combination thing
}
</code>```

With switch each case must be some static, unique value. So you can't use .Contains as a case.

Body:
You can't do this using switch, you'll have to use the if-else-if type of structure.

string input=...
if(input.Contains("sleep")){ //contains sleep?
  //do stuff for some word
}else if(input.Contains("look") && input.Contains("box")){ //contains look and box
  //do stuff for the combination thing
}

With switch each case must be some static, unique value. So you can't use .Contains as a case.


问:
International Telephone Input number formatting way around?
As I understand they have removed the autoformat option on the latest International Telephone Input library.This option formatted the number accordingly to the country the user choose.  But according to the forms, i can still use util.js and format-number function to achieve this options  (https://github.com/jackocnr/intl-tel-input/wiki/utils.js) I tried multiple times but not being able to apply this option. For example for US Number, how would I format the number to this ex:(201)-255-6655. This is my code below. As I see this seems to be the best js library for international numbers.

$( document ).ready(function() {

    $('#contactForm')
    .find('[name="phoneNumber"]')
        .intlTelInput({
            utilsScript:"https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/js/utils.js",

            autoPlaceholder: true,
            initialCountry:"us",
            geoIpLookup:"auto",

        });

    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Phone</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/css/intlTelInput.css">
<link rel="stylesheet" href="./intlmask.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/js/intlTelInput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/js/utils.js"></script>

<script src="./intlmask.js"></script>
</head>
<body>

  <form id="contactForm" class="form-horizontal">
    <div class="form-group">
        <label class="col-xs-3 control-label">Phone number</label>
        <div class="col-xs-5">
            <input type="tel" class="form-control" name="phoneNumber" />
        </div>
    </div>
</form>

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

like this

答:
so I basically added a  function and ran it when user-focused out of the input. utils.js already provide us with formatting (intlTelInputUtils.formatNumber). we just have to pass the number and country code/initial to it. check my code below

    function test(){
        var number =  $('input[name="phoneNumber"]').val();
        var classf = $(".selected-flag > div").attr("class");
        var flag = classf.slice(-2);

        console.log("check number: ", number);
        console.log("check classf: ", classf);
        console.log("check flag: ", flag);

        var formattedNumber = intlTelInputUtils.formatNumber(number, flag, intlTelInputUtils.numberFormat.INTERNATIONAL);
        $('input[name="phoneNumber"]').val(formattedNumber);

}```

Body:
As I understand they have removed the autoformat option on the latest International Telephone Input library.This option formatted the number accordingly to the country the user choose.  But according to the forms, i can still use util.js and format-number function to achieve this options  (https://github.com/jackocnr/intl-tel-input/wiki/utils.js) I tried multiple times but not being able to apply this option. For example for US Number, how would I format the number to this ex:(201)-255-6655. This is my code below. As I see this seems to be the best js library for international numbers.

$( document ).ready(function() {

    $('#contactForm')
    .find('[name="phoneNumber"]')
        .intlTelInput({
            utilsScript:"https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/js/utils.js",

            autoPlaceholder: true,
            initialCountry:"us",
            geoIpLookup:"auto",

        });

    });

<!DOCTYPE html>

<title>Phone</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.5/css/intlTelInput.css">
<link rel="stylesheet" href="./intlmask.css">

  <form id="contactForm" class="form-horizontal">

        Phone number

            <input type="tel" class="form-control" name="phoneNumber" />

</form>

like this


问:
Automatic version updating using git on commit
I have a python project I'm working on using git for version control I want to set up a unique version number for every commit based on PEP440.

I.e I would use the following version numbering N(.N)*[{a|b|rc}N][.postN][.devN] for the master branch, were for every commit for which a higher level version number isn't incremented devN will be auto incremented by git on commit, the rest of the version would hopefully be controlled by a special git command: git increment-version {level}

where level would be one of major, minor, patch, patch-{level} (patch is the same as patch-0), alpha, beta, release, final, post would map to the version string as  {major}[.{minor}[(.{patch-N})*]], alpha => aN, beta => bN, release => rcN, post => postN, with beta replacing alpha and release replacing beta, final removes pre-release component, if the earlier one is used than the current this should produce a error, When a higher level version is incremented all lower levels are rest to zero, and any patch level set to zero is not included in the string, incrementing major, minor or patch will set the per-release component to a0.

For a branch branching off of the master branch the same numbers will be used but the version applies to the branch it self, with the version string being

{master_version}+{branch_name}.{branch_version} where branch version undertakes the same format as for the master version

For branches off a non master branch the local version is extended as follows
{branchN_name}.{branchN_version}(.{branchN_name}.{branchN_version})*
where branch names must start with a letter and not match any of [{a|b|rc}N][.postN][.devN], each {branchN_name}.{branchN_version} is treated like a extended form of .postN component

The location of the version string should be specified as a file that is part of the repository, and a line pattern as follows using a string with escape sequences \\ = \, \" = ", \' = ', \v = version string
i.e. "__version__ = \"\v\"".

On a commit git should search the specified file for this line load the version string, update it and write out a new version string to the file, intermediately before committing the changes including the updated version string, if the file has be otherwise change, but not added to the commit, the version, string should be update, in the version from the previous commit, and this change propagated to the modified file. If a on the master branch, and a version number has be incremented by a call to git increment-version {level}
than git should also generate a tag for this commit matching the version string.

Ideally I would like to increment this extension to git by way of a python script that is part of the repository it self. However I'm open to other ways of solving this problem.

EDIT:

I believe the best solution is to make git command i.e. git-autoversion executable.

Then to enable said versioning for a repository I would run git autoversion --init --style=pep440 --template=python-info --versionfile=XXX/_info.py

which would create a file .gitautoversion which would contain

```<code>[autoversion]
version=1.0
local=
style=pep440
template=python-info
file=XXX/_info.py
</code>```

it would also have a hook git autoversion --commit which should be run as a pre-commit hook.

finally it could be called as git autoversion --[major|minor|patch{-level}|alpha|beta|release|final|post|dev] which can be used to mark the version number to increment, only the last call would count this would add the line increment=xxx to the .gitautoversion configuration file, the command git autoversion --commit would read this and increment the version, if no increment is specified it defaults to dev, finally it invokes the command git-autoversion-tpl-{template} --version={version} --local={local} --file={file} to update the version file.

QUESTION: is their a way to install a global git hook when autoversion is installed to call git autoversion --commit for a commit to any repository this command can then check for .gitautoversion if found update the version otherwise do nothing. If not this would require manual installing of the hook.

QUESTION 2: is their a way to hook an extra argument to git commit, say --autoversion=[major|minor|patch{-level}|alpha|beta|release|final|post|dev], which would invoke the autoversion command before running commit hooks?

答:
You may be able to use version_scheme option in the following pypi project to do what you want

https://pypi.python.org/pypi/setuptools_scm

ContentLicense: CC BY-SA 4.0

Body:
I have a python project I'm working on using git for version control I want to set up a unique version number for every commit based on PEP440.

I.e I would use the following version numbering N(.N)*[{a|b|rc}N][.postN][.devN] for the master branch, were for every commit for which a higher level version number isn't incremented devN will be auto incremented by git on commit, the rest of the version would hopefully be controlled by a special git command: git increment-version {level}

where level would be one of major, minor, patch, patch-{level} (patch is the same as patch-0), alpha, beta, release, final, post would map to the version string as  {major}[.{minor}[(.{patch-N})*]], alpha => aN, beta => bN, release => rcN, post => postN, with beta replacing alpha and release replacing beta, final removes pre-release component, if the earlier one is used than the current this should produce a error, When a higher level version is incremented all lower levels are rest to zero, and any patch level set to zero is not included in the string, incrementing major, minor or patch will set the per-release component to a0.

For a branch branching off of the master branch the same numbers will be used but the version applies to the branch it self, with the version string being

{master_version}+{branch_name}.{branch_version} where branch version undertakes the same format as for the master version

For branches off a non master branch the local version is extended as follows
{branchN_name}.{branchN_version}(.{branchN_name}.{branchN_version})*
where branch names must start with a letter and not match any of [{a|b|rc}N][.postN][.devN], each {branchN_name}.{branchN_version} is treated like a extended form of .postN component

The location of the version string should be specified as a file that is part of the repository, and a line pattern as follows using a string with escape sequences \\ = \, \" = ", \' = ', \v = version string
i.e. "__version__ = \"\v\"".

On a commit git should search the specified file for this line load the version string, update it and write out a new version string to the file, intermediately before committing the changes including the updated version string, if the file has be otherwise change, but not added to the commit, the version, string should be update, in the version from the previous commit, and this change propagated to the modified file. If a on the master branch, and a version number has be incremented by a call to git increment-version {level}
than git should also generate a tag for this commit matching the version string.

Ideally I would like to increment this extension to git by way of a python script that is part of the repository it self. However I'm open to other ways of solving this problem.

EDIT:

I believe the best solution is to make git command i.e. git-autoversion executable.

Then to enable said versioning for a repository I would run git autoversion --init --style=pep440 --template=python-info --versionfile=XXX/_info.py

which would create a file .gitautoversion which would contain

[autoversion]
version=1.0
local=
style=pep440
template=python-info
file=XXX/_info.py

it would also have a hook git autoversion --commit which should be run as a pre-commit hook.

finally it could be called as git autoversion --[major|minor|patch{-level}|alpha|beta|release|final|post|dev] which can be used to mark the version number to increment, only the last call would count this would add the line increment=xxx to the .gitautoversion configuration file, the command git autoversion --commit would read this and increment the version, if no increment is specified it defaults to dev, finally it invokes the command git-autoversion-tpl-{template} --version={version} --local={local} --file={file} to update the version file.

QUESTION: is their a way to install a global git hook when autoversion is installed to call git autoversion --commit for a commit to any repository this command can then check for .gitautoversion if found update the version otherwise do nothing. If not this would require manual installing of the hook.

QUESTION 2: is their a way to hook an extra argument to git commit, say --autoversion=[major|minor|patch{-level}|alpha|beta|release|final|post|dev], which would invoke the autoversion command before running commit hooks?


问:
Why does my Eclipse project have phantom debugger breakpoints?
I've got a small project which, when run in the Eclipse debugger, always seems to stop in FileInputStream.class line 106, where files are opened.  There are no breakpoints set, but Eclipse behaves exactly as if I have a breakpoint here.  If I clear all breakpoints, it still happens.

I have a second much-larger project in the same Eclipse workspace which does not suffer from this problem.

I just moved the smaller project off of my old Linux machine, where I developed it in Europa Eclipse and had this problem, onto my new Windows machine, where I continue to see the problem in Ganymede Eclipse.  The problem persists across operating systems and across Eclipse versions, yet apparently not across projects.  I don't get it!  I grepped through every file in this project's directory and couldn't find anything that might be a file somehow directing Eclipse to stop in FileInputStream.

Further info: the apparent breakpoint is actually not for line 106 of FileInputStream; it appears to be an Exception breakpoint for FileNotFoundException, being thrown from native code called from that line in FileInputStream.  But again, I don't appear to have any breakpoints set at all.  Are Exception breakpoints defined somewhere else?

答:
I ran into an issue where a source file had persistent markers for breakpoints that didn't exist. I tried cleaning the project, doing a full build, restarting Eclipse - nothing worked.

I went digging through the Eclipse metadata, and found the projects .markers file. Deleting that file finally fixed the issue.

For anyone else having this issue, open your workspace directory, then navigate to .metadata/.plugins/org.eclipse.core.resources/.projects/your project, then rename/remove file .markers.

For example, if your workspace folder is ~/workspace, and your project is named Foo, you could do:

```<code>$ mv ~/workspace/.metadata/.plugins/org.eclipse.core.resources/.projects/Foo/.markers ~/safe.Foo.markers
</code>```

Body:
I ran into an issue where a source file had persistent markers for breakpoints that didn't exist. I tried cleaning the project, doing a full build, restarting Eclipse - nothing worked.

I went digging through the Eclipse metadata, and found the projects .markers file. Deleting that file finally fixed the issue.

For anyone else having this issue, open your workspace directory, then navigate to .metadata/.plugins/org.eclipse.core.resources/.projects/your project, then rename/remove file .markers.

For example, if your workspace folder is ~/workspace, and your project is named Foo, you could do:

$ mv ~/workspace/.metadata/.plugins/org.eclipse.core.resources/.projects/Foo/.markers ~/safe.Foo.markers


问:
Using a variable as part of a javascript array
I have an object (that I can change!) that looks like this:

```<code>var pageContent = {
    "contact_us":[{
        "content":"<p>Lots of content here.</p>",
        "title":"Contact Us"
     }],
    "index":[{
        "content":"<p>Some other content here.</p>",
        "title":"Home Page"
     }],
    "gallery":[{
        "content":"<p>Some more content</p>",
        "title":"Gallery"
     }],
 }
</code>```

To access properties, I'm doing this:

```<code>pageContent.gallery[0]['title'];
</code>```

To get the value "Gallery".

What I want to do is something like this:

```<code>var newPage = "gallery";
pageContent.newpage[0]['title'];
</code>```

But, obviously that fails. How can I do what I want? Changes to anything are welcome, nothing is set in stone here.

答:
You can use square bracket notation, like this:</p>

```<code>var title = pageContent[newpage][0]['title'];
</code>```

Body:
I have an object (that I can change!) that looks like this:

var pageContent = {
    "contact_us":[{
        "content":"
Lots of content here.
",
        "title":"Contact Us"
     }],
    "index":[{
        "content":"
Some other content here.
",
        "title":"Home Page"
     }],
    "gallery":[{
        "content":"
Some more content
",
        "title":"Gallery"
     }],
 }

To access properties, I'm doing this:

pageContent.gallery[0]['title'];

To get the value "Gallery".

What I want to do is something like this:

var newPage = "gallery";
pageContent.newpage[0]['title'];

But, obviously that fails. How can I do what I want? Changes to anything are welcome, nothing is set in stone here.

Body:
You can use square bracket notation, like this:

var title = pageContent[newpage][0]['title'];


问:
How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?
I would like to include image in a jupyter notebook.

If I did the following, it works :

```<code>from IPython.display import Image
Image("img/picture.png")
</code>```

But I would like to include the images in a markdown cell and the following code gives a 404 error :

```<code>![title]("img/picture.png")
</code>```

I also tried

```<code>![texte]("http://localhost:8888/img/picture.png")
</code>```

But I still get the same error :

```<code>404 GET /notebooks/%22/home/user/folder/img/picture.png%22 (127.0.0.1) 2.74ms referer=http://localhost:8888/notebooks/notebook.ipynb
</code>```

答:
This works for me in a markdown cell. Somehow I do not need to mention specifically if its an image or a simple file. </p>

```<code>![](files/picture.png)
</code>```

Body:
I would like to include image in a jupyter notebook.

If I did the following, it works :

from IPython.display import Image
Image("img/picture.png")

But I would like to include the images in a markdown cell and the following code gives a 404 error :

![title]("img/picture.png")

I also tried

![texte]("http://localhost:8888/img/picture.png")

But I still get the same error :

404 GET /notebooks/%22/home/user/folder/img/picture.png%22 (127.0.0.1) 2.74ms referer=http://localhost:8888/notebooks/notebook.ipynb

Body:
This works for me in a markdown cell. Somehow I do not need to mention specifically if its an image or a simple file.

![](files/picture.png)


问:
How can I fix network for docker in kubernetes?
I have a kubernetes cluster and using Jenkins

pipeline jenkins:

```<code>podTemplate(label: 'pod-golang', containers: [
    containerTemplate(name: 'golang', image: 'golang:latest', ttyEnabled: true, command: 'cat'),
    containerTemplate(name: 'docker', image: 'docker:17.11-dind', ttyEnabled: true, command: 'cat'),
  ],
  volumes: [hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock')]
) {
    node('pod-golang') {
        def app
        String applicationName = "auth"
        String buildNumber = "0.1.${env.BUILD_NUMBER}"

        stage 'Checkout'
            checkout scm
        container('docker') {
            stage 'Create docker image'
                app = docker.build("test/${applicationName}")
        }
    }
}
</code>```

When I run "docker build" command  in new (creating) container not working network:

```<code>Step 1/6 : FROM alpine:latest
 ---> e21c333399e0
Step 2/6 : RUN apk --no-cache add ca-certificates
 ---> Running in 8483bb918ee8
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz
[91mWARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz: operation timed out
[0mEXITCODE   0[91mWARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz: operation timed out
</code>```

if I use "docker run" command on host machine I see, It does not work properly  network in "manual"  started docker image:

```<code>root@node2:~/tmp# docker run --rm -it alpine ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
^C
--- 8.8.8.8 ping statistics ---
14 packets transmitted, 0 packets received, 100% packet loss
root@node2:~/tmp# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=57 time=12.9 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=57 time=12.9 ms
^C
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 12.927/12.943/12.960/0.114 ms
</code>```

but When I use pod from kubectl everything worked.

How can I fix that?

答:
Open another windows run the tcpdump -vvv host 8.8.8.8 command see  traffic going out.

Here is my host output.

```<code># tcpdump -vvv host 8.8.8.8
tcpdump: listening on enp0s3, link-type EN10MB (Ethernet), capture size 262144 bytes
18:36:35.142633 IP (tos 0x0, ttl 63, id 2091, offset 0, flags [DF], proto ICMP (1), length 84)
    webserver > google-public-dns-a.google.com: ICMP echo request, id 256, seq 0, length 64
18:36:35.170475 IP (tos 0x0, ttl 55, id 18270, offset 0, flags [none], proto ICMP (1), length 84)
    google-public-dns-a.google.com > webserver: ICMP echo reply, id 256, seq 0, length 64
18:36:36.146145 IP (tos 0x0, ttl 63, id 2180, offset 0, flags [DF], proto ICMP (1), length 84)
    webserver > google-public-dns-a.google.com: ICMP echo request, id 256, seq 1, length 64

# docker run --rm -it alpine ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=54 time=30.720 ms
64 bytes from 8.8.8.8: seq=1 ttl=54 time=25.576 ms
64 bytes from 8.8.8.8: seq=2 ttl=54 time=28.464 ms
64 bytes from 8.8.8.8: seq=3 ttl=54 time=33.860 ms
64 bytes from 8.8.8.8: seq=4 ttl=54 time=25.525 ms
</code>```

Body:
I have a kubernetes cluster and using Jenkins

pipeline jenkins:

podTemplate(label: 'pod-golang', containers: [
    containerTemplate(name: 'golang', image: 'golang:latest', ttyEnabled: true, command: 'cat'),
    containerTemplate(name: 'docker', image: 'docker:17.11-dind', ttyEnabled: true, command: 'cat'),
  ],
  volumes: [hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock')]
) {
    node('pod-golang') {
        def app
        String applicationName = "auth"
        String buildNumber = "0.1.${env.BUILD_NUMBER}"

        stage 'Checkout'
            checkout scm
        container('docker') {
            stage 'Create docker image'
                app = docker.build("test/${applicationName}")
        }
    }
}

When I run "docker build" command  in new (creating) container not working network:

Step 1/6 : FROM alpine:latest
 ---> e21c333399e0
Step 2/6 : RUN apk --no-cache add ca-certificates
 ---> Running in 8483bb918ee8
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz
[91mWARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz: operation timed out
[0mEXITCODE   0[91mWARNING: Ignoring http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz: operation timed out

if I use "docker run" command on host machine I see, It does not work properly  network in "manual"  started docker image:

root@node2:~/tmp# docker run --rm -it alpine ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
^C
--- 8.8.8.8 ping statistics ---
14 packets transmitted, 0 packets received, 100% packet loss
root@node2:~/tmp# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=57 time=12.9 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=57 time=12.9 ms
^C
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 12.927/12.943/12.960/0.114 ms

but When I use pod from kubectl everything worked.

How can I fix that?

Body:
Open another windows run the tcpdump -vvv host 8.8.8.8 command see  traffic going out.

Here is my host output.

# tcpdump -vvv host 8.8.8.8
tcpdump: listening on enp0s3, link-type EN10MB (Ethernet), capture size 262144 bytes
18:36:35.142633 IP (tos 0x0, ttl 63, id 2091, offset 0, flags [DF], proto ICMP (1), length 84)
    webserver > google-public-dns-a.google.com: ICMP echo request, id 256, seq 0, length 64
18:36:35.170475 IP (tos 0x0, ttl 55, id 18270, offset 0, flags [none], proto ICMP (1), length 84)
    google-public-dns-a.google.com > webserver: ICMP echo reply, id 256, seq 0, length 64
18:36:36.146145 IP (tos 0x0, ttl 63, id 2180, offset 0, flags [DF], proto ICMP (1), length 84)
    webserver > google-public-dns-a.google.com: ICMP echo request, id 256, seq 1, length 64

# docker run --rm -it alpine ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=54 time=30.720 ms
64 bytes from 8.8.8.8: seq=1 ttl=54 time=25.576 ms
64 bytes from 8.8.8.8: seq=2 ttl=54 time=28.464 ms
64 bytes from 8.8.8.8: seq=3 ttl=54 time=33.860 ms
64 bytes from 8.8.8.8: seq=4 ttl=54 time=25.525 ms


问:
python flask - passing variable to function from post method

I'm new to flask and I'm making a webpage, where the user submits something and I need to run scripts with the using of the entered value.

2 questions:

Why don't make_nil gets called? - I'm getting the same value I entered.

Why don't i see  sys.stdout('age: ', age) or print('age: ', age)?

Thanks!

flask_ager.py:

```<code>from flask import Flask, render_template, request
import sys
app = Flask(__name__)

@app.route('/send', methods=['GET', 'POST'])
def send():
    if request.method == 'POST':
        kapa = request.form['age']
        age = make_nil(int(kapa))
        sys.stdout('age: ', age)
        return render_template('age.html', age=age)
    return render_template('inka.html')

def make_nil(age):
    return 0

if __name__ == "__main__":
    app.run()
</code>```

age.html:

```<code><!DOCTYPE html>
<html>
<head> Siker? </head>
<body>
<h1> Your age is {{age}} </h1>
</body>
</html>
</code>```

inka.html:

```<code><!DOCTYPE html>
<html>
<head> Siker? </head>
<body>
<h1> How old are you? </h1>
<form method="POST" action="/send">
<div class="form_group">
<input type="text" name="age">
</div>
<input class="btn btn-primary" type="submit" value="submit">
</form>
</body>
</html>
</code>```

答:
When I test this, I get the following:

```<code>ERROR in app: Exception on /send [POST]
...
  File "flask_ager.py", line 10, in send
    sys.stdout('age: ', age)
TypeError: 'file' object is not callable
</code>```

This line should be:

```<code>sys.stdout.write('age: {}'.format(age))
</code>```

Updating that line and retesting shows the app is working correctly:

Body:
I'm new to flask and I'm making a webpage, where the user submits something and I need to run scripts with the using of the entered value.

2 questions:

Why don't make_nil gets called? - I'm getting the same value I entered.

Why don't i see  sys.stdout('age: ', age) or print('age: ', age)?

Thanks!

flask_ager.py:

from flask import Flask, render_template, request
import sys
app = Flask(__name__)

@app.route('/send', methods=['GET', 'POST'])
def send():
    if request.method == 'POST':
        kapa = request.form['age']
        age = make_nil(int(kapa))
        sys.stdout('age: ', age)
        return render_template('age.html', age=age)
    return render_template('inka.html')

def make_nil(age):
    return 0

if __name__ == "__main__":
    app.run()

age.html:

<!DOCTYPE html>

 Siker?

 Your age is {{age}}

inka.html:

<!DOCTYPE html>

 Siker?

 How old are you?

<form method="POST" action="/send">

<input type="text" name="age">

<input class="btn btn-primary" type="submit" value="submit">
</form>

Body:
When I test this, I get the following:

ERROR in app: Exception on /send [POST]
...
  File "flask_ager.py", line 10, in send
    sys.stdout('age: ', age)
TypeError: 'file' object is not callable

This line should be:

sys.stdout.write('age: {}'.format(age))

Updating that line and retesting shows the app is working correctly:


问:
using stack to index multiple columns by a single column
I'm trying to take a format starting with:

```<code> Global_Code | Retailer_X_Code | Retailer_Y_Code | Info | ...
  -----------------------------------------------------------
 'A'              'a'              'a_a'            1     ...
 'B'              'b'              'b_b'            2     ...
 ...              ...               ...            ...    ...
</code>```

And stack the Retailer_X_Code and Retailer_Y_Code into a single Retailer_Name column, indexed by Global_Code. I'd also like to keep other columns in the row such as Info.

So starting off with stack(), I get:

```<code> stacked_df = mapping_df.stack()

 ========

 Global_Code          'A'
 Retailer_X_Code      'a'
 Retailer_Y_Code      'a_a'
 Info                 1
 ...more columns

 Global_Code          'B'
 Retailer_X_Code      'b'
 Retailer_Y_Code      'b_b'
 Info                 2
 ...more columns
</code>```

Great, now I don't all the columns, and want Retailer_X_Code and Retailer_Y_Code to be under one column. So I select these columns, organized by Global_Code:

```<code>stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code']].set_index('Global_Code').stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code'})

========

Global_Code |  Retailer_Name   | Retailer_Code
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
</code>```

So far so good. Now I want to grab Info and include is as part of the stacked column result. The desired output should look like this:

```<code>Global_Code |  Retailer_Name   | Retailer_Code | Info
------------------------------------------------------
'A'           'Retailer_X_Code'   'a'            1
'A'           'Retailer_Y_Code'   'a_a'          1
...           ...                 ...           ...
'B'           'Retailer_X_Code'   'b'            2
'B'           'Retailer_Y_Code'   'b_b'          2
</code>```

But if I add Info as part of the selected columns, then rename it to Product_Info, it doesn't add the Info column.

Instead, it inserts Info values incorrectly under Retailer_Name.

```<code>stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code', 'Info']].set_index('Global_Code').stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code', 1: 'Product_Info'})

========

Global_Code |  Retailer_Name   | Retailer_Code
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
'A'           'Info'              1
'A'           'Info'              1
'A'           'Info'              1
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
'B'           'Info'              2
</code>```

The above without column renaming, .rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Pack'}), gives me:

```<code>Global_Code |  level_1          | 0
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
'A'           'Info'              1
'A'           'Info'              1
'A'           'Info'              1
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
'B'           'Info'              2
</code>```

答:
The way to do it is index by the columns you need: .set_index(['Index1', 'Index2'])

E.g.:

```<code>stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code', 'Info']].set_index(['Global_Code', 'Info']).stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code', 1: 'Product_Info'})
</code>```

Gives:

```<code>Global_Code |  Info | Retailer_Name   | Retailer_Code
------------------------------------------------------
'A'              1    'Retailer_X_Code'   'a'
'A'              1    'Retailer_Y_Code'   'a_a'
...                   ...                 ...
'B'              2    'Retailer_X_Code'   'b'
'B'              2    'Retailer_Y_Code'   'b_b'
</code>```

Body:
I'm trying to take a format starting with:

 Global_Code | Retailer_X_Code | Retailer_Y_Code | Info | ...
  -----------------------------------------------------------
 'A'              'a'              'a_a'            1     ...
 'B'              'b'              'b_b'            2     ...
 ...              ...               ...            ...    ...

And stack the Retailer_X_Code and Retailer_Y_Code into a single Retailer_Name column, indexed by Global_Code. I'd also like to keep other columns in the row such as Info.

So starting off with stack(), I get:

 stacked_df = mapping_df.stack()

 ========

 Global_Code          'A'
 Retailer_X_Code      'a'
 Retailer_Y_Code      'a_a'
 Info                 1
 ...more columns

 Global_Code          'B'
 Retailer_X_Code      'b'
 Retailer_Y_Code      'b_b'
 Info                 2
 ...more columns

Great, now I don't all the columns, and want Retailer_X_Code and Retailer_Y_Code to be under one column. So I select these columns, organized by Global_Code:

stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code']].set_index('Global_Code').stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code'})

========

Global_Code |  Retailer_Name   | Retailer_Code
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'

So far so good. Now I want to grab Info and include is as part of the stacked column result. The desired output should look like this:

Global_Code |  Retailer_Name   | Retailer_Code | Info
------------------------------------------------------
'A'           'Retailer_X_Code'   'a'            1
'A'           'Retailer_Y_Code'   'a_a'          1
...           ...                 ...           ...
'B'           'Retailer_X_Code'   'b'            2
'B'           'Retailer_Y_Code'   'b_b'          2

But if I add Info as part of the selected columns, then rename it to Product_Info, it doesn't add the Info column.

Instead, it inserts Info values incorrectly under Retailer_Name.

stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code', 'Info']].set_index('Global_Code').stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code', 1: 'Product_Info'})

========

Global_Code |  Retailer_Name   | Retailer_Code
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
'A'           'Info'              1
'A'           'Info'              1
'A'           'Info'              1
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
'B'           'Info'              2

The above without column renaming, .rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Pack'}), gives me:

Global_Code |  level_1          | 0
------------------------------------------
'A'           'Retailer_X_Code'   'a'
'A'           'Retailer_Y_Code'   'a_a'
'A'           'Info'              1
'A'           'Info'              1
'A'           'Info'              1
...           ...                 ...
'B'           'Retailer_X_Code'   'b'
'B'           'Retailer_Y_Code'   'b_b'
'B'           'Info'              2

Body:
The way to do it is index by the columns you need: .set_index(['Index1', 'Index2'])

E.g.:

stacked_df = mapping_df[['Global_Code', 'Retailer_X_Code', 'Retailer_Y_Code', 'Info']].set_index(['Global_Code', 'Info']).stack().reset_index().rename(columns={'level_1':'Retailer_Name', 0:'Retailer_Code', 1: 'Product_Info'})

Gives:

Global_Code |  Info | Retailer_Name   | Retailer_Code
------------------------------------------------------
'A'              1    'Retailer_X_Code'   'a'
'A'              1    'Retailer_Y_Code'   'a_a'
...                   ...                 ...
'B'              2    'Retailer_X_Code'   'b'
'B'              2    'Retailer_Y_Code'   'b_b'


问:
how to find if specific value exists in a key, and then extract that array in new array in php
I have the following array:

```<code>Array
(
[0] => Array
    (
        [CODE] => OK
        [company_id] => 170647449000
        [taxnumber] => 944703420
        [name] => SOME NAME
        [title] => S.A

    )

[1] => Array
    (
        [CODE] => OK
        [company_id] => 17063649000
        [taxnumber] => 999033420
        [name] => SOME OTHER NAME
        [title] => ANOTHER DIFFERENT TITLE
    )
)
</code>```

If the array contain the company_id with the value 17063649000 I need to extract that array (1) in an new array, so I can manipulate it further.

I make numerous code snippets but I am not even close to the solution. I still can not figure out how can I find if the $value (17063649000) exists in the array....not to mention how to extract that specific array (1) from the existing array....
My latest attempt was to modify this and to make it to work, but I am still not managing to make it:

```<code>function myfunction($agents, $field, $value)
{
   foreach($agents as $key => $agent)
   {
     if ( $agent[$field] === $value )
        return $key;
  }
 return false;
}
</code>```

I always get false, even I am sending the value that exists.

答:
if your array is $companies then</p>

```<code>function getCompany($search_id, $companies) {
    foreach($company in $companies) {
        if ($companies['company_id'] == $search_id) {
            return $company;
        }
    }
    return false;
}

$companies = [...];
$search = 17063649000;
if ($company = getCompany($search, $companies) ) {
    // do something with $company
} else {
    // not found
}
</code>```

Body:
I have the following array:

Array
(
[0] => Array
    (
        [CODE] => OK
        [company_id] => 170647449000
        [taxnumber] => 944703420
        [name] => SOME NAME
        [title] => S.A

    )

[1] => Array
    (
        [CODE] => OK
        [company_id] => 17063649000
        [taxnumber] => 999033420
        [name] => SOME OTHER NAME
        [title] => ANOTHER DIFFERENT TITLE
    )
)

If the array contain the company_id with the value 17063649000 I need to extract that array (1) in an new array, so I can manipulate it further.

I make numerous code snippets but I am not even close to the solution. I still can not figure out how can I find if the $value (17063649000) exists in the array....not to mention how to extract that specific array (1) from the existing array....
My latest attempt was to modify this and to make it to work, but I am still not managing to make it:

function myfunction($agents, $field, $value)
{
   foreach($agents as $key => $agent)
   {
     if ( $agent[$field] === $value )
        return $key;
  }
 return false;
}

I always get false, even I am sending the value that exists.

Body:
if your array is $companies then

function getCompany($search_id, $companies) {
    foreach($company in $companies) {
        if ($companies['company_id'] == $search_id) {
            return $company;
        }
    }
    return false;
}

$companies = [...];
$search = 17063649000;
if ($company = getCompany($search, $companies) ) {
    // do something with $company
} else {
    // not found
}


问:
Disable IntelliTrace during execution of application
I have an application that loads a lot of metadata when starting up. This is done within a few seconds, but when I turn IntelliTrace on it takes ages. I understand why, but it makes it for me impossible to use IntelliTrace.

What I would like is to add a statement to my code to not record the IntelliTrace events and call information during this loading. After the load has finished, I want to add a statement that the IntelliTrace can record the information again.

Is there a way to achieve this?

答:
Disable IT completely:

```<code>Tools -> Options -> IntelliTrace -> [ ] Enable IntelliTrace
</code>```

or figure out what exactly event type degrades the performance and disable it:

```<code>Tools -> Options -> IntelliTrace -> IntelliTrace Events
</code>```

Body:
Disable IT completely:

Tools -> Options -> IntelliTrace -> [ ] Enable IntelliTrace

or figure out what exactly event type degrades the performance and disable it:

Tools -> Options -> IntelliTrace -> IntelliTrace Events


问:
Is Python3 supported in DSX Local 1.1.1.00 (20170912_0351)?
When I open a notebook I get below warning in DSX Local 1.1.1.00 (20170912_0351) x86_64:

I couldn't find a kernel matching Python 3. Please select a kernel:
Python2 with DSX Spark
and
Python2 with ML

Does this mean that we don't yet support Python3?

答:
Python 3.x is not yet supported on DSX Local.
Please stay tuned for newer version.

Thanks


问:
How can I treat a "empty cluster" warning, in K-means function?
I'm searching for a solution to treat a warning message, from the Kmeans function of amap package. The warning message is the following:

empty cluster: try a better set of initial centers.

Is there anyway I could get a signal, so could know when this error message thrown, and then handle the problem? (e.g: running the algorithm until the there is the return has no empty cluster)

It is quite hard to make a nice reproducible example for me. But, I came with this ugly, but functional:

```<code>library(amap)

numberK = 20
ts.len = 7

time.series <- rep(sample(1:8000, numberK, replace = TRUE),ts.len)
time.series <- rep(rbind(time.series, time.series), 30)
time.series <- matrix(time.series, ncol = ts.len)

centers <- matrix( sample(1:3000, numberK*ts.len), ncol = ts.len)

Kmeans((time.series), centers = centers, iter.max = 99)
</code>```

If you run this on you terminal, it might send you the warning message I'm talking about.

Note: My thoughts of solving this problem is catching the signal of the warning, and then execute the solution. However, I have no idea how can I possibly do that

答:
From ?options (scrolling down a long ways to find warn...):

sets the handling of warning messages. If warn is negative all
  warnings are ignored. If warn is zero (the default) warnings are
  stored until the top–level function returns. If 10 or fewer warnings
  were signalled they will be printed otherwise a message saying how
  many were signalled. An object called last.warning is created and can
  be printed through the function warnings. If warn is one, warnings are
  printed as they occur. If warn is two or larger all warnings are
  turned into errors.

So using tryCatch you can specify a warning handler function to do stuff upon catching a warning:

```<code>> tryCatch(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},
         warning = function(e) "Caught warning")
[1] "Caught warning"
</code>```

Or you can set all warnings to be escalated to errors via:

```<code>options(warn = 2)
</code>```

as described in the docs. Then,

```<code>> tryCatch(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},
           error = function(e) "Caught error")
[1] "Caught error"
</code>```

Although many people seem to prefer tryCatch, I often like the explicitness of try, which feels easier to me if I want to do some sort of if...else block after running the expression:

```<code>options(warn = 2)
attempt <- try(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},silent = TRUE)
> class(attempt)
[1] "try-error"
</code>```

So then you can check class(attempt) in an if statement (the preferred way is to check inherits(attempt,"try-error")) and do stuff accordingly.

Body:
I'm searching for a solution to treat a warning message, from the Kmeans function of amap package. The warning message is the following:

empty cluster: try a better set of initial centers.

Is there anyway I could get a signal, so could know when this error message thrown, and then handle the problem? (e.g: running the algorithm until the there is the return has no empty cluster)

It is quite hard to make a nice reproducible example for me. But, I came with this ugly, but functional:

library(amap)

numberK = 20
ts.len = 7

time.series <- rep(sample(1:8000, numberK, replace = TRUE),ts.len)
time.series <- rep(rbind(time.series, time.series), 30)
time.series <- matrix(time.series, ncol = ts.len)

centers <- matrix( sample(1:3000, numberK*ts.len), ncol = ts.len)

Kmeans((time.series), centers = centers, iter.max = 99)

If you run this on you terminal, it might send you the warning message I'm talking about.

Note: My thoughts of solving this problem is catching the signal of the warning, and then execute the solution. However, I have no idea how can I possibly do that

Body:
From ?options (scrolling down a long ways to find warn...):

sets the handling of warning messages. If warn is negative all
  warnings are ignored. If warn is zero (the default) warnings are
  stored until the top–level function returns. If 10 or fewer warnings
  were signalled they will be printed otherwise a message saying how
  many were signalled. An object called last.warning is created and can
  be printed through the function warnings. If warn is one, warnings are
  printed as they occur. If warn is two or larger all warnings are
  turned into errors.

So using tryCatch you can specify a warning handler function to do stuff upon catching a warning:

> tryCatch(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},
         warning = function(e) "Caught warning")
[1] "Caught warning"

Or you can set all warnings to be escalated to errors via:

options(warn = 2)

as described in the docs. Then,

> tryCatch(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},
           error = function(e) "Caught error")
[1] "Caught error"

Although many people seem to prefer tryCatch, I often like the explicitness of try, which feels easier to me if I want to do some sort of if...else block after running the expression:

options(warn = 2)
attempt <- try(expr = {Kmeans((time.series), centers = centers, iter.max = 99)},silent = TRUE)
> class(attempt)
[1] "try-error"

So then you can check class(attempt) in an if statement (the preferred way is to check inherits(attempt,"try-error")) and do stuff accordingly.


问:
Amazon EC2 Tensorflow GPU support
I tried looking around a lot and couldn't find a fix yet.

Things I tried included checking all the paths and environment variables.

When I try running Keras with the TensorFlow backend using Python 3.6 on the Deep Learning AMI (m4.xlarge)

As soon as Tensorflow is imported this is the output:

/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6
        return f(*args, **kwds)

Running:

```<code>print ("VERSION", tf.Session(config=tf.ConfigProto(log_device_placement=True)))
</code>```

Returns:

2017-12-06 01:19:49.592416: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
      2017-12-06 01:19:49.603333: E tensorflow/stream_executor/cuda/cuda_driver.cc:406] failed call to cuInit: CUDA_ERROR_UNKNOWN
      2017-12-06 01:19:49.603378: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:145] kernel driver does not appear to be running on this host (ip-172-31-41-243): /proc/driver/nvidia/version does not exist
      Device mapping: no known devices.
      2017-12-06 01:19:49.604178: I tensorflow/core/common_runtime/direct_session.cc:299] Device mapping:

```<code>VERSION <tensorflow.python.client.session.Session object at 0x7f24f3d69c88>
</code>```

Any clue why I can't get the GPUs to run?

答:
I think the problem is well interesting. To enable the GPUs support, please make sure there is any supported GPUs device installed in your instance. As far as I know M4 instances do not provide any GPUs.

A solution for this problem, you should be start a new instance with GPUs like P3 and P2 instance. (For personal exploration, I suggest you start will spot instance, which will be more cost-effective.) Then run the same code again, I think it will works if there is no bugs in the code itself.

Title: Amazon EC2 Tensorflow GPU support

Body:
I tried looking around a lot and couldn't find a fix yet.

Things I tried included checking all the paths and environment variables.

When I try running Keras with the TensorFlow backend using Python 3.6 on the Deep Learning AMI (m4.xlarge)

As soon as Tensorflow is imported this is the output:

/home/ubuntu/anaconda3/envs/tensorflow_p36/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.6
        return f(*args, **kwds)

Running:

print ("VERSION", tf.Session(config=tf.ConfigProto(log_device_placement=True)))

Returns:

2017-12-06 01:19:49.592416: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
      2017-12-06 01:19:49.603333: E tensorflow/stream_executor/cuda/cuda_driver.cc:406] failed call to cuInit: CUDA_ERROR_UNKNOWN
      2017-12-06 01:19:49.603378: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:145] kernel driver does not appear to be running on this host (ip-172-31-41-243): /proc/driver/nvidia/version does not exist
      Device mapping: no known devices.
      2017-12-06 01:19:49.604178: I tensorflow/core/common_runtime/direct_session.cc:299] Device mapping:

VERSION <tensorflow.python.client.session.Session object at 0x7f24f3d69c88>

Any clue why I can't get the GPUs to run?


问:
Oracle sql query sum data every month
Let's say i have selected data from oktober until desember like this

i want to get sum of buying customer in every months (okt-des)
The result i want is like table below

i already know how to get last day of months
but i don't have idea query in SQL to get result like i need

答:
One way to do this - if you just need the data for those three months - is to use conditional aggregation:

```<code>select   name,
         sum(case when dt >= date '2017-10-01' and dt < date '2017-11-01'
                  then buying end) as oktober,
         sum(case when dt >= date '2017-11-01' and dt < date '2017-12-01'
                  then buying end) as november,
         sum(case when dt >= date '2017-12-01' and dt < date '2018-01-01'
                  then buying end) as desember
from     YOUR_TABLE
where    dt >= date '2017-10-01' and dt < date '2018-01-01'
group by name
;
</code>```

Note that date is an Oracle keyword which should not be used as a column name; I changed it to dt.  YOUR_TABLE should be your actual table name.

Title: Oracle sql query sum data every month

Body:
One way to do this - if you just need the data for those three months - is to use conditional aggregation:

select   name,
         sum(case when dt >= date '2017-10-01' and dt < date '2017-11-01'
                  then buying end) as oktober,
         sum(case when dt >= date '2017-11-01' and dt < date '2017-12-01'
                  then buying end) as november,
         sum(case when dt >= date '2017-12-01' and dt < date '2018-01-01'
                  then buying end) as desember
from     YOUR_TABLE
where    dt >= date '2017-10-01' and dt < date '2018-01-01'
group by name
;

Note that date is an Oracle keyword which should not be used as a column name; I changed it to dt.  YOUR_TABLE should be your actual table name.


问:
How to add an event outside the Slick after clicking on the dot marker
I use a standard slider slider, and I want to add an event outside the slider itself but on the same page. I tried to catch the event in different ways:

```<code>    $("ul.slick-dots li button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });
</code>```

or

```<code>    $(".main .big-slider-sec .slick-dots li button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });
</code>```

or

```<code>    $("#slick-slide01:button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });
</code>```

or

```<code>    $("#slick-slide00").find("button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });
</code>```

or

```<code>    $("#slick-slide00").children("button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });
</code>```

but none of this has worked, and my event does not happen by clicking on the slider markers

答:
I went through a lot of things, it turned out like this:

```<code>        $('.big-slider-sec').on('afterChange', function(event, slick, currentSlide){
        $("#slick-slide01").click(function() {
            $('.map_animation').toggleClass('map_animation2');
        });
    });
</code>```

maybe someone needs it

Body:
I use a standard slider slider, and I want to add an event outside the slider itself but on the same page. I tried to catch the event in different ways:

    $("ul.slick-dots li button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });

or

    $(".main .big-slider-sec .slick-dots li button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });

or

    $("#slick-slide01:button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });

or

    $("#slick-slide00").find("button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });

or

    $("#slick-slide00").children("button").click(function() {
        $('.map_animation').toggleClass('map_animation2');
    });

but none of this has worked, and my event does not happen by clicking on the slider markers

Body:
I went through a lot of things, it turned out like this:

        $('.big-slider-sec').on('afterChange', function(event, slick, currentSlide){
        $("#slick-slide01").click(function() {
            $('.map_animation').toggleClass('map_animation2');
        });
    });

maybe someone needs it


问:
Display passed data from one Ionic 3 vpage to another
So, I have data displaying on one page with a (click) event that passes data to another page, except I can only get the data to print in the console and not the page itself.  I've been at it for hours and am at my breaking point :)

I am only going to show the relevant code below to keep the post shortened (well, what I think is relevant)

list2page.html

```<code>...
<button class="list-item" tappable ion-item (click)="goToFeed(item)" *ngFor="let item of list2.items">
  ...
</button>
...
</code>```

list2page.ts

```<code>...
goToFeed(item) {
  this.nav.push(ProfilePage, {item: item});
}
...
</code>```

profile.ts - it will print the entire item to console - see screenshot

```<code>import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import 'rxjs/Rx';

@Component({
  selector: 'profile-page',
  templateUrl: 'profile.html'
})
export class ProfilePage {

  constructor(
    public nav: NavController,
    public navParams: NavParams,
  ) {
  }

  ionViewDidLoad() {
    let veteran_first = (this.navParams.get('item.veteran_first'));
    console.log(this.navParams.get('item'));
  }

}
</code>```

答:
You should define veteran_first as a class variable, not a local variable:

```<code>  export class ProfilePage {
  veteran_first; //------------------------> define it here
  constructor(public nav: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    // Assign to this.veteran_first
    this.veteran_first = this.navParams.get("item.veteran_first");
    console.log(this.navParams.get("item"));
  }
}
</code>```

Then in profile.html:

```<code><div>
    veteran_first = {{veteran_first}}
</div>
</code>```

Body:
So, I have data displaying on one page with a (click) event that passes data to another page, except I can only get the data to print in the console and not the page itself.  I've been at it for hours and am at my breaking point :)

I am only going to show the relevant code below to keep the post shortened (well, what I think is relevant)

list2page.html

...
<button class="list-item" tappable ion-item (click)="goToFeed(item)" *ngFor="let item of list2.items">
  ...
</button>
...

list2page.ts

...
goToFeed(item) {
  this.nav.push(ProfilePage, {item: item});
}
...

profile.ts - it will print the entire item to console - see screenshot

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import 'rxjs/Rx';

@Component({
  selector: 'profile-page',
  templateUrl: 'profile.html'
})
export class ProfilePage {

  constructor(
    public nav: NavController,
    public navParams: NavParams,
  ) {
  }

  ionViewDidLoad() {
    let veteran_first = (this.navParams.get('item.veteran_first'));
    console.log(this.navParams.get('item'));
  }

}

Body:
You should define veteran_first as a class variable, not a local variable:

  export class ProfilePage {
  veteran_first; //------------------------> define it here
  constructor(public nav: NavController, public navParams: NavParams) {}

  ionViewDidLoad() {
    // Assign to this.veteran_first
    this.veteran_first = this.navParams.get("item.veteran_first");
    console.log(this.navParams.get("item"));
  }
}

Then in profile.html:

<div>
    veteran_first = {{veteran_first}}
</div>


问:
Expand JTable size to fill JPanel
I'm trying to create a program that displays a table with data on it, called a Time Log program. I'm having trouble expanding a Jtable to fill a JPanel, since it's currently looking like this:

You can see the huge white gap below the table, but I want the rows to be evenly distributed among the space.

Below is my code.

This is a class I call TimeLogApplication, which has main method and creates a JFrame.

```<code>public static void main(String[] args) {

    /* Create a new frame */
    JFrame guiFrame = new JFrame("Time Log Program");

    /* Set size of the frame */
    guiFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);

    /* Add the panel */
    guiFrame.add(new TimeLogPanel());

    /* Exit normally on closing the window */
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    /* Show the frame */
    guiFrame.setVisible(true);
}
</code>```

The JFrame calls TimeLogPanel class that creates a JPanel. This panel has a Border Layout. The table is added to the center panel, which also has Border Layout.

```<code>public TimeLogPanel() {

    // Set layout, add table panel
    setLayout(new BorderLayout(20, 20));
    add(tablePanel);

    // Create table panel and set layout
    tablePanel = new JPanel();
    tablePanel.setLayout(new BorderLayout());

    // Create a new table with row and column number
    table = new JTable(rowNum, colNum);
    table.setShowGrid(true);
    table.setGridColor(Color.BLACK);

    // Set a raised border
    table.setBorder(new EtchedBorder(EtchedBorder.RAISED));

    // Add table to table panel
    tablePanel.add(table);
}
</code>```

I have tried to get the panel height but since it is not created until the frame is created, the panel height is zero.

Thanks in advance for any suggestions!

UPDATE:
I tried out the suggestions and it worked beautifully (adding ComponentListener to the JPanel that holds the JTable). This is what I did:

```<code>tablePanel.addComponentListener(new ComponentListener() {

        @Override
        public void componentResized(ComponentEvent e) {
                tablePanelSize = tablePanel.getHeight();
                table.setRowHeight(tablePanel.getHeight()/rowNum); //RowNum is the number of rows
        }

        // Below methods are not used but must be there, as a requirement when adding a listener
        @Override
        public void componentMoved(ComponentEvent e) {
        }

        @Override
        public void componentShown(ComponentEvent e) {
        }

        @Override
        public void componentHidden(ComponentEvent e) {
        }
    });
</code>```

答: I think you have to add a ComponentListener (componentResized event),  calculate the row height and then call JTable.setRowHeight.

Title: Expand JTable size to fill JPanel

Body:
I'm trying to create a program that displays a table with data on it, called a Time Log program. I'm having trouble expanding a Jtable to fill a JPanel, since it's currently looking like this:

You can see the huge white gap below the table, but I want the rows to be evenly distributed among the space.

Below is my code.

This is a class I call TimeLogApplication, which has main method and creates a JFrame.

public static void main(String[] args) {

    /* Create a new frame */
    JFrame guiFrame = new JFrame("Time Log Program");

    /* Set size of the frame */
    guiFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT);

    /* Add the panel */
    guiFrame.add(new TimeLogPanel());

    /* Exit normally on closing the window */
    guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    /* Show the frame */
    guiFrame.setVisible(true);
}

The JFrame calls TimeLogPanel class that creates a JPanel. This panel has a Border Layout. The table is added to the center panel, which also has Border Layout.

public TimeLogPanel() {

    // Set layout, add table panel
    setLayout(new BorderLayout(20, 20));
    add(tablePanel);

    // Create table panel and set layout
    tablePanel = new JPanel();
    tablePanel.setLayout(new BorderLayout());

    // Create a new table with row and column number
    table = new JTable(rowNum, colNum);
    table.setShowGrid(true);
    table.setGridColor(Color.BLACK);

    // Set a raised border
    table.setBorder(new EtchedBorder(EtchedBorder.RAISED));

    // Add table to table panel
    tablePanel.add(table);
}

I have tried to get the panel height but since it is not created until the frame is created, the panel height is zero.

Thanks in advance for any suggestions!

UPDATE:
I tried out the suggestions and it worked beautifully (adding ComponentListener to the JPanel that holds the JTable). This is what I did:

tablePanel.addComponentListener(new ComponentListener() {

        @Override
        public void componentResized(ComponentEvent e) {
                tablePanelSize = tablePanel.getHeight();
                table.setRowHeight(tablePanel.getHeight()/rowNum); //RowNum is the number of rows
        }

        // Below methods are not used but must be there, as a requirement when adding a listener
        @Override
        public void componentMoved(ComponentEvent e) {
        }

        @Override
        public void componentShown(ComponentEvent e) {
        }

        @Override
        public void componentHidden(ComponentEvent e) {
        }
    });


问:
Should I return success callback return value?
Is it conventional for parent function to return their child success callbacks or does it just depend on a case by case basis?

```<code>var cb = function(){
    return 1;
}

function ret_cb(succ_cb) {
    return(succ_cb ? succ_cb() : 1);
}

var succ = ret_cb(cb);
console.log(succ);

//or

function no_ret_cb(succ_cb) {
    if(succ_cb){
        succ_cb();
    }
    return 1;
}

succ = no_ret_cb(cb);
console.log(succ);
</code>```

This would mainly be the reason I would use the callback

```<code>//functional way

succ = ret_cb(cb);

//vs

var some_value = "hello";
succ = ret_cb();
succ &= cb(some_value);
</code>```

答:
It's case by case.

It is rare for a function to take a callback and not be either asynchronous (in which case there is no return value from the callback to return until later) or operating in a loop (in which case there isn't one result of running the function to return).

Body:
Is it conventional for parent function to return their child success callbacks or does it just depend on a case by case basis?

var cb = function(){
    return 1;
}

function ret_cb(succ_cb) {
    return(succ_cb ? succ_cb() : 1);
}

var succ = ret_cb(cb);
console.log(succ);

//or

function no_ret_cb(succ_cb) {
    if(succ_cb){
        succ_cb();
    }
    return 1;
}

succ = no_ret_cb(cb);
console.log(succ);

This would mainly be the reason I would use the callback

//functional way

succ = ret_cb(cb);

//vs

var some_value = "hello";
succ = ret_cb();
succ &= cb(some_value);


问:
Setting DateTimePicker Value Error
I know (from references) that the value of DateTimePicker can be set like the following:

```<code>DateTimePicker exampleDtPicker = new DateTimePicker();
exampleDtPicker.Value = new DateTime(2010, 10, 6);
</code>```

However, this doesn't change the value displayed on the form, yet displays the current local date.
Does different properties from default of exampleDtPicker affects setting value of DateTimePicker? These are the properties of exampleDtPicker :

```<code>DateTimePicker exampleDtPicker = new DateTimePicker() {
    Checked = false,
    Format = DateTimePickerFormat.Short;
    ShowCheckBox = true;
}
</code>```

What is causing the problem and how to solve it?

答:
Your DateTimePicker has the property Checked set to false. With such setup, if you are setting its ShowCheckBox to false somewhere else (and probably even if you don't do it)... chances are it will never update itself no matter what Value you pass in. From MSDN:

Gets or sets a value indicating whether the Value property has been
  set with a valid date/time value and the displayed value is able to be
  updated.

and:

This property is used to obtain the state of the check box that is
  displayed if the P:System.Windows.Forms.DateTimePicker.ShowCheckBox
  property value is true. If the
  P:System.Windows.Forms.DateTimePicker.Checked property value is true,
  the T:System.Windows.Forms.DateTimePicker control displays the
  properly formatted P:System.Windows.Forms.DateTimePicker.Value
  property value; otherwise, the control displays the last valid
  date/time value assigned to the
  P:System.Windows.Forms.DateTimePicker.Value property or the current
  date and time (P:System.DateTime.Now) if no value has ever been
  assigned.

Title: Setting DateTimePicker Value Error

Body:
I know (from references) that the value of DateTimePicker can be set like the following:

DateTimePicker exampleDtPicker = new DateTimePicker();
exampleDtPicker.Value = new DateTime(2010, 10, 6);

However, this doesn't change the value displayed on the form, yet displays the current local date.
Does different properties from default of exampleDtPicker affects setting value of DateTimePicker? These are the properties of exampleDtPicker :

DateTimePicker exampleDtPicker = new DateTimePicker() {
    Checked = false,
    Format = DateTimePickerFormat.Short;
    ShowCheckBox = true;
}

What is causing the problem and how to solve it?


问:
Will a non-atomic load to the same cache line as an atomic variable cause the atomic variable to fail?
Given something like this on an ARMv8 CPU (though this may apply to many others as well):

```<code>class abcxzy
{
  // Pragma align to cacheline to ensure they exist on same line.
  unit32_t atomic_data;
  uint32_t data;

  void foo()
  {
    volatile asm (
      "   ldr w0, [address of data]\n"
      "# Do stuff with data in w0..."
      "   str w0, [address of data]\n"

      "1: ldaxr w0, [address of atomic_data]\n"
      "   add w1, w0, #0x1\n"
      "   stxr w2,w1, [address of atomic_data]\n"
      "   cbnz w2, 1b\n"
    );
  }
}
</code>```

With proper clobbers and such set on the Asm inline so that C and Asm can coexist happily in a world of rainbow ponies and sunshine.

In a multiple CPU situation, all running this code at the same time, will the stores to data cause the atomic load/store to atomic_data to fail?  From what I've read, the ARM atomic stuff works on a cache line basis, but it is not clear if the non-atomic store will affect the atomic.  I hope that it it doesn't (and assume that it does...), but I am looking to see if anyone else can confirm this.

答:
Ok, finally found what I needed, though I don't like it:

According to the ARM documentation, It is IMPLEMENTATION DEFINED whether a non-exclusive store to the same cache line as the exclusive store causes the exclusive store to fail.  Thanks ARM.  Appreciate that wonderful non-conclusive info.

Edit:

By fail, I mean the stxr command did not write to memory and returned a "1" in the status register.  "Your atomic data updated and needs new RMW" status.

To answer other statements:

Yes, atomic critical areas should be as small as possible.  The docs event give numbers on how small, and they are very reasonable indeed.  I hope that my sections never span 1k or more...

And yes, any situation where you would need to worry about this kind of contention killing performance or worse means your code is "doing it wrong."  The ARM docs are state this in a round about manner :)

As to putting the non-atomic loads and stores inside the atomics - my pseudo test above was just demonstrating a random access to the same cache line as an example.  In real code, you obviously should avoid this.  I was just trying to get a feeling for how "bad" it might be if, perhaps a high speed hardware timer store was hitting the same cache line as a lock.  Again, don't do this...

Body:
Given something like this on an ARMv8 CPU (though this may apply to many others as well):

class abcxzy
{
  // Pragma align to cacheline to ensure they exist on same line.
  unit32_t atomic_data;
  uint32_t data;

  void foo()
  {
    volatile asm (
      "   ldr w0, [address of data]\n"
      "# Do stuff with data in w0..."
      "   str w0, [address of data]\n"

      "1: ldaxr w0, [address of atomic_data]\n"
      "   add w1, w0, #0x1\n"
      "   stxr w2,w1, [address of atomic_data]\n"
      "   cbnz w2, 1b\n"
    );
  }
}

With proper clobbers and such set on the Asm inline so that C and Asm can coexist happily in a world of rainbow ponies and sunshine.

In a multiple CPU situation, all running this code at the same time, will the stores to data cause the atomic load/store to atomic_data to fail?  From what I've read, the ARM atomic stuff works on a cache line basis, but it is not clear if the non-atomic store will affect the atomic.  I hope that it it doesn't (and assume that it does...), but I am looking to see if anyone else can confirm this.


问:
How do declare an array in C++ as a parameter?
I am working with propriety code in my iOS project and all I have access to is the header files for my project. How do you declare an array in C++ so that it will return an array when I make a call?

Here's the header file method,

```<code> short WI_GetIDsFromList(int32_t module, int32_t *idsArray, uint32_t *count);
</code>```

How do you declare an array to received an array of in32_t? I keep getting a parameter error for returnedIdsArray when I make this call? It works perfectly fine for count? I tried making it into a pointer but it did not work?

```<code>    //Array of ID's
    int32_t returnedIdsArray[] = {};

    // Array of ID's count
    uint32_t count;

 rc += WI_GetIDsFromList(mod, returnedIdsArray, &count);
</code>```

Another Example

```<code>short dpCount;

//Get number of data points from the device
WI_GetDatapointCount(modIDHDS, &dpCount);

//dpCount now has returned value of method WI_GetDatapointCount
NSLog@"%d", int(dpCount);
</code>```

答:
I think Mochi's question is how to declare the array that it suits the need of the function given in the header. If I understand him right, he has no influence to the function taking the array as parameter.

Did you try:

```<code>int32_t returnedIdsArray[MaximumExpectedIds];
</code>```

Maybe there is also a function in the API giving you the number of Ids that you could use to determine the array size.

Body:
I am working with propriety code in my iOS project and all I have access to is the header files for my project. How do you declare an array in C++ so that it will return an array when I make a call?

Here's the header file method,

 short WI_GetIDsFromList(int32_t module, int32_t *idsArray, uint32_t *count);

How do you declare an array to received an array of in32_t? I keep getting a parameter error for returnedIdsArray when I make this call? It works perfectly fine for count? I tried making it into a pointer but it did not work?

    //Array of ID's
    int32_t returnedIdsArray[] = {};

    // Array of ID's count
    uint32_t count;

 rc += WI_GetIDsFromList(mod, returnedIdsArray, &count);

Another Example

short dpCount;

//Get number of data points from the device
WI_GetDatapointCount(modIDHDS, &dpCount);

//dpCount now has returned value of method WI_GetDatapointCount
NSLog@"%d", int(dpCount);

Body:
I think Mochi's question is how to declare the array that it suits the need of the function given in the header. If I understand him right, he has no influence to the function taking the array as parameter.

Did you try:

int32_t returnedIdsArray[MaximumExpectedIds];

Maybe there is also a function in the API giving you the number of Ids that you could use to determine the array size.


问:
Repeat Python function call on exception?
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

```<code>try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2
</code>```

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

答:
I like to do these problems with recursion:</p>

```<code>def tryfor(times, on_failure, excepts, func, *args, **kwargs):
    if times < 1:
        raise on_failure()
    try:
        return func(*args, **kwargs)
    except excepts:
        return tryfor(times-1, on_failure, excepts, func, *args, **kwargs)

tryfor(3, PermanentException, (SomeError,), dostuff,1,2)
</code>```

Body:
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

Body:
I like to do these problems with recursion:

def tryfor(times, on_failure, excepts, func, *args, **kwargs):
    if times < 1:
        raise on_failure()
    try:
        return func(*args, **kwargs)
    except excepts:
        return tryfor(times-1, on_failure, excepts, func, *args, **kwargs)

tryfor(3, PermanentException, (SomeError,), dostuff,1,2)


问:
repeating rows of data based on specific data in a given group of cells
I have a row of data that contains 40 possible cells of specific data that I need to separate and repeat that row of data with the cell that contains the specific data out the 40 possibilities and then continue to repeat this process until there are no more cells with the specific data.

EqType1 and EqSerial1 would need to be selected together but are in separate cells.  this example should return 2 rows of data the first with the FirstName LastName EqType1 EqSerial1 and the second row with FirstName LastName EqType2 EqSerial2 and then stop if there are no more Eq and move on to the next row of data and perform the same function over again.

Sample Row of Data:

```<code>FirstName   LastName    EqType1   EqSerial1      EqType2    EqSerial2
MORGAN      TURNBULL    ARPCXDT   PAX501037020   TG1682G    7823AE179414
</code>```

答:
"this example should return 2 rows of data the first with the FirstName LastName EqType1 EqSerial1 and the second row with FirstName LastName EqType2 EqSerial2"

A disclaimer: The following will only work if you put your 2 new combined indexes into columns and not rows

If I understand your question correctly, you could try this:

Insert two extra columns at the end of your data: Eq1 and Eq2

So your data would be laid out like this:

```<code>  A         B        C       D            E       F            G    H
1 FirstName LastName EqType1 EqSerial1    EqType2 EqSerial2    Eq1 Eq2
2 MORGAN    TURNBULL ARPCXDT PAX501037020 TG1682G 7823AE179414
</code>```

In cell G2 insert the formula: = A2 & " " & B2 & " " & C2 & " " & D2

In cell H2 insert the formula: = A2 & " " & B2 & " " & E2 & " " & F2

Body:
I have a row of data that contains 40 possible cells of specific data that I need to separate and repeat that row of data with the cell that contains the specific data out the 40 possibilities and then continue to repeat this process until there are no more cells with the specific data.

EqType1 and EqSerial1 would need to be selected together but are in separate cells.  this example should return 2 rows of data the first with the FirstName LastName EqType1 EqSerial1 and the second row with FirstName LastName EqType2 EqSerial2 and then stop if there are no more Eq and move on to the next row of data and perform the same function over again.

Sample Row of Data:

FirstName   LastName    EqType1   EqSerial1      EqType2    EqSerial2
MORGAN      TURNBULL    ARPCXDT   PAX501037020   TG1682G    7823AE179414

Body:
"this example should return 2 rows of data the first with the FirstName LastName EqType1 EqSerial1 and the second row with FirstName LastName EqType2 EqSerial2"

A disclaimer: The following will only work if you put your 2 new combined indexes into columns and not rows

If I understand your question correctly, you could try this:

Insert two extra columns at the end of your data: Eq1 and Eq2

So your data would be laid out like this:

  A         B        C       D            E       F            G    H
1 FirstName LastName EqType1 EqSerial1    EqType2 EqSerial2    Eq1 Eq2
2 MORGAN    TURNBULL ARPCXDT PAX501037020 TG1682G 7823AE179414

In cell G2 insert the formula: = A2 & " " & B2 & " " & C2 & " " & D2

In cell H2 insert the formula: = A2 & " " & B2 & " " & E2 & " " & F2


问:
Make JavaFX window active
I am trying to make a JavaFX application (running in the background to show up (set visible)) by a specific keystroke and to make the window the active window immediately. Therefore I set the primary stage alwaysOnTop-property true, call stage.toFront() and finally call stage.requestFocus(). Afterwards I request focus for a text field. When the window is made visible I would like to instantly start typing into the text field.

However, when I for example have a Ubuntu-terminal selected and make the window visible and start typing, the application is shown on top of everything, however, the typing goes to the terminal. The application window is not active! Nevertheless, the focused property of the stage is true. Is that a bug or am I missing something? Is it OS related?

Edit: I am willed to give my little hack-around for this problem that I am using at the moment, because the internet is suggesting, that a lot of people are facing this problem: Since I am working on a linux maschine I have access to the wonderful tool wmctrl. It is part of most standard repositories. wmctrl -a WINDOWNAME sets the window with the name WINDOWNAME active. For now, I simply call this tool from my source code when I need the window to be active. Since this is more of a dirty hack than any thing else, I sure want to get rid of it.

答:
Not perfect, but it works:</p>

```<code>Platform.runLater(() ->
{
    //primaryStage.setAlwaysOnTop(true);
    //primaryStage.setAlwaysOnTop(false);
    primaryStage.setIconified(true);
    primaryStage.setIconified(false);
});
</code>```

Title: Make JavaFX window active

Body:
Not perfect, but it works:

Platform.runLater(() ->
{
    //primaryStage.setAlwaysOnTop(true);
    //primaryStage.setAlwaysOnTop(false);
    primaryStage.setIconified(true);
    primaryStage.setIconified(false);
});