问:
Methods of testing Simplex (Linear Programming) calculation output
I have been tasked with created a web-based machine for solving real-world issues using Linear Programming techniques, specifically at present, Danzig's Simplex Method. With this in mind I've found a rather nifty bit of C++ code that calculates the results, and with some considerable speed even on this particularly low-end machine.

However, I currently have nothing other than the console output itself attesting the result to be anywhere close to the correct solution for the given problem. Which is an issue if people are being asked to trust the result as being indicative of anything significantly more important than that some digits can be made to flash up on a computer screen.

I will spare you from the full details of the entire program, as it's fairly long, but here's the function responsible for taking the data, just for reference:

```<code>void Data() {
    double R1, R2;
    char R;
    int I, J;
    printf("\n LINEAR PROGRAMMING\n\n");
    printf(" MAXIMIZE (Y/N) ? "); scanf("%c", &R);
    printf("\n NUMBER OF VARIABLES OF ECONOMIC FUNCTION ? "); scanf("%d", &NV);
    printf("\n NUMBER OF CONSTRAINTS ? "); scanf("%d", &NC);
    if (R == 'Y' || R == 'y')
        R1 = 1.0;
    else
        R1 = -1.0;
    printf("\n INPUT COEFFICIENTS OF ECONOMIC FUNCTION:\n");
    for (J = 1; J <= NV; J++) {
        printf("       #%d ? ", J); scanf("%lf", &R2);
        TS[1][J + 1] = R2 * R1;
    }
    printf("       Right hand side ? "); scanf("%lf", &R2);
    TS[1][1] = R2 * R1;
    for (I = 1; I <= NC; I++) {
        printf("\n CONSTRAINT #%d:\n", I);
        for (J = 1; J <= NV; J++) {
            printf("       #%d ? ", J); scanf("%lf", &R2);
            TS[I + 1][J + 1] = -R2;
        }
        printf("       Right hand side ? "); scanf("%lf", &TS[I + 1][1]);
    }
    printf("\n\n RESULTS:\n\n");
    for (J = 1; J <= NV; J++)  TS[0][J + 1] = J;
    for (I = NV + 1; I <= NV + NC; I++)  TS[I - NV + 1][0] = I;
}
</code>```

I can also include the pivot table, formulation and optimisation functions if need be.

I would like to ask for specific techniques which might be employed to ensure that, given a set of coefficients and constraints, the C++ program returns the economic function correctly (I'll have to implement additional checking stages later when the data gets output to the web, but I'll cross that bridge when I come to it).

(For reasons of attribution, I note that the above code was created by Jean-Pierre Moreau in 1982. Coincidentally, 1982 happens to be my birth year, but that's probably not important right now.)

答: To check the results you can use any non-linear method of optimization (for example Quasi-Newton with bounds constraints). There are a lot of mathematical packets (Octave, MathLab, MathCAD, SciLab etc.) that can help you. If you want to get the solution by programm code try to look to MINPACK (https://en.wikipedia.org/wiki/MINPACK)</p>

Body:
I have been tasked with created a web-based machine for solving real-world issues using Linear Programming techniques, specifically at present, Danzig's Simplex Method. With this in mind I've found a rather nifty bit of C++ code that calculates the results, and with some considerable speed even on this particularly low-end machine.

However, I currently have nothing other than the console output itself attesting the result to be anywhere close to the correct solution for the given problem. Which is an issue if people are being asked to trust the result as being indicative of anything significantly more important than that some digits can be made to flash up on a computer screen.

I will spare you from the full details of the entire program, as it's fairly long, but here's the function responsible for taking the data, just for reference:

void Data() {
    double R1, R2;
    char R;
    int I, J;
    printf("\n LINEAR PROGRAMMING\n\n");
    printf(" MAXIMIZE (Y/N) ? "); scanf("%c", &R);
    printf("\n NUMBER OF VARIABLES OF ECONOMIC FUNCTION ? "); scanf("%d", &NV);
    printf("\n NUMBER OF CONSTRAINTS ? "); scanf("%d", &NC);
    if (R == 'Y' || R == 'y')
        R1 = 1.0;
    else
        R1 = -1.0;
    printf("\n INPUT COEFFICIENTS OF ECONOMIC FUNCTION:\n");
    for (J = 1; J <= NV; J++) {
        printf("       #%d ? ", J); scanf("%lf", &R2);
        TS[1][J + 1] = R2 * R1;
    }
    printf("       Right hand side ? "); scanf("%lf", &R2);
    TS[1][1] = R2 * R1;
    for (I = 1; I <= NC; I++) {
        printf("\n CONSTRAINT #%d:\n", I);
        for (J = 1; J <= NV; J++) {
            printf("       #%d ? ", J); scanf("%lf", &R2);
            TS[I + 1][J + 1] = -R2;
        }
        printf("       Right hand side ? "); scanf("%lf", &TS[I + 1][1]);
    }
    printf("\n\n RESULTS:\n\n");
    for (J = 1; J <= NV; J++)  TS[0][J + 1] = J;
    for (I = NV + 1; I <= NV + NC; I++)  TS[I - NV + 1][0] = I;
}

I can also include the pivot table, formulation and optimisation functions if need be.

I would like to ask for specific techniques which might be employed to ensure that, given a set of coefficients and constraints, the C++ program returns the economic function correctly (I'll have to implement additional checking stages later when the data gets output to the web, but I'll cross that bridge when I come to it).

(For reasons of attribution, I note that the above code was created by Jean-Pierre Moreau in 1982. Coincidentally, 1982 happens to be my birth year, but that's probably not important right now.)


来源: stackexchange

问:
Python split by character only if wrapped in parenthesis
I am parsing a large text file that has key value pairs separated by '='. I need to split these key value pairs into a dictionary. I was simply going to split by '='. However I noticed that some of the values contain the equals sign character. When a value contains the equals sign character, it seems to be always wrapped in parenthesis.

Question: How can I split by equals sign only when the equals sign is not in between two parenthesis?

Example data:

```<code>PowSup=PS1(type=Emerson,fw=v.03.05.00)
</code>```

Desired output:

```<code>{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}
</code>```

UPDATE: The data does not seem to have any nested parenthesis. (Hopefully that remains true in the future)

UPDATE 2: The key doesn't ever seem to have equals sign either.

UPDATE 3: The full requirements are much more complicated and at this point I am stuck so I have opened up a new question here: Python parse output of mixed format text file to key value pair dictionaries

答:
```<code>mydict=dict()
for line in file:
    k,v=line.split('=',1)
    mydict[k]=v
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am parsing a large text file that has key value pairs separated by '='. I need to split these key value pairs into a dictionary. I was simply going to split by '='. However I noticed that some of the values contain the equals sign character. When a value contains the equals sign character, it seems to be always wrapped in parenthesis.

Question: How can I split by equals sign only when the equals sign is not in between two parenthesis?

Example data:

PowSup=PS1(type=Emerson,fw=v.03.05.00)

Desired output:

{'PowSup': 'PS1(type=Emerson,fw=v.03.05.00)'}

UPDATE: The data does not seem to have any nested parenthesis. (Hopefully that remains true in the future)

UPDATE 2: The key doesn't ever seem to have equals sign either.

UPDATE 3: The full requirements are much more complicated and at this point I am stuck so I have opened up a new question here: Python parse output of mixed format text file to key value pair dictionaries


问:
How can I have tab 1 and 4 selected
I have two tab sections and I would like the first tab of each tab section to be selected by default. In this case tab 1 and tab 4 . How can I do that?

In my attempted I created a for loop selecting by class name, but I noticed only the last element in the loop is always selected not all. I did not included it as i think the issues is that only one tab can be selected at a time, but I do not see where this statement is.

Just picked up js a week ago. This a modified example i got from w3schools.

```<code>        <!DOCTYPE html>
<html>
<head>
<style>
body {font-family: "Lato", sans-serif;}

/* Style the tab */
div.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
div.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
div.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
div.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

/* Style the close button */
.topright {
    float: right;
    cursor: pointer;
    font-size: 20px;
}

.topright:hover {color: red;}
</style>
</head>
<body>

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen1">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, '1')" id="defaultOpen2">1</button>
  <button class="tablinks" onclick="openCity(event, '2')">2</button>
  <button class="tablinks" onclick="openCity(event, '3')">3</button>
</div>

<div id="1" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="2" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="3" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen1").click();
document.getElementById("defaultOpen2").click();
</script>

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

答:
The problem is that when you click on the tabs links you are making the call globally, so javascript starts looking for the classes tabContent and hides all of them, even if they are not the one you wanted to hide, to solve this problem you can wrap the tabs in a div and when you click on the tablink first find which is the ID of the tab container you have and then find the right content to show and hide. I made a few tweaks in the code.

Note: This is a solution, but certainly there's a better way to do this tabs

function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    var parent = evt.target.parentNode.parentNode.className;
    console.log(parent);
    tabcontent = document.querySelectorAll("." + parent + " .tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.querySelectorAll("." + parent + " .tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
//    document.getElementById(cityName).style.display = "block";

    document.querySelector("." + parent +" #" + cityName).style.display = "block";
//    console.log(this)
    evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen1").click();
document.getElementById("defaultOpen2").click();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: "Lato", sans-serif;}

/* Style the tab */
div.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
div.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
div.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
div.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

/* Style the close button */
.topright {
    float: right;
    cursor: pointer;
    font-size: 20px;
}

.topright:hover {color: red;}</code>```

        <!DOCTYPE html>

Click on the x button in the top right corner to close the current tab:

    <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen1">London</button>
    <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
    <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

    x

London

London is the capital city of England.

    x

Paris

Paris is the capital of France.

    x

Tokyo

Tokyo is the capital of Japan.

Click on the x button in the top right corner to close the current tab:

    <button class="tablinks" onclick="openCity(event, 'one')" id="defaultOpen2">1</button>
    <button class="tablinks" onclick="openCity(event, 'two')">2</button>
    <button class="tablinks" onclick="openCity(event, 'three')">3</button>

    x

London

London is the capital city of England.

    x

Paris

Paris is the capital of France.

    x

Tokyo

Tokyo is the capital of Japan.

 ```

Title: How can I have tab 1 and 4 selected

Body:
I have two tab sections and I would like the first tab of each tab section to be selected by default. In this case tab 1 and tab 4 . How can I do that?

In my attempted I created a for loop selecting by class name, but I noticed only the last element in the loop is always selected not all. I did not included it as i think the issues is that only one tab can be selected at a time, but I do not see where this statement is.

Just picked up js a week ago. This a modified example i got from w3schools.

        <!DOCTYPE html>

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen1">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  x

London

London is the capital city of England.

  x

Paris

Paris is the capital of France.

  x

Tokyo

Tokyo is the capital of Japan.

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, '1')" id="defaultOpen2">1</button>
  <button class="tablinks" onclick="openCity(event, '2')">2</button>
  <button class="tablinks" onclick="openCity(event, '3')">3</button>

  x

London

London is the capital city of England.

  x

Paris

Paris is the capital of France.

  x

Tokyo

Tokyo is the capital of Japan.

Body:
The problem is that when you click on the tabs links you are making the call globally, so javascript starts looking for the classes tabContent and hides all of them, even if they are not the one you wanted to hide, to solve this problem you can wrap the tabs in a div and when you click on the tablink first find which is the ID of the tab container you have and then find the right content to show and hide. I made a few tweaks in the code.

Note: This is a solution, but certainly there's a better way to do this tabs

function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    var parent = evt.target.parentNode.parentNode.className;
    console.log(parent);
    tabcontent = document.querySelectorAll("." + parent + " .tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.querySelectorAll("." + parent + " .tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
//    document.getElementById(cityName).style.display = "block";

    document.querySelector("." + parent +" #" + cityName).style.display = "block";
//    console.log(this)
    evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen1").click();
document.getElementById("defaultOpen2").click();

body {font-family: "Lato", sans-serif;}

/* Style the tab */
div.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
div.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
div.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
div.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

/* Style the close button */
.topright {
    float: right;
    cursor: pointer;
    font-size: 20px;
}

.topright:hover {color: red;}

        <!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>Click on the x button in the top right corner to close the current tab:</p>
<div class="cities">
  <div class="tab">
    <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen1">London</button>
    <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
    <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
  </div>

  <div id="London" class="tabcontent">
    <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
    <h3>London</h3>
    <p>London is the capital city of England.</p>
  </div>

  <div id="Paris" class="tabcontent">
    <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
    <h3>Paris</h3>
    <p>Paris is the capital of France.</p>
  </div>

  <div id="Tokyo" class="tabcontent">
    <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
    <h3>Tokyo</h3>
    <p>Tokyo is the capital of Japan.</p>
  </div>
</div>

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="countries">
  <div class="tab">
    <button class="tablinks" onclick="openCity(event, 'one')" id="defaultOpen2">1</button>
    <button class="tablinks" onclick="openCity(event, 'two')">2</button>
    <button class="tablinks" onclick="openCity(event, 'three')">3</button>
  </div>

  <div id="one" class="tabcontent">
    <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
    <h3>London</h3>
    <p>London is the capital city of England.</p>
  </div>

  <div id="two" class="tabcontent">
    <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
    <h3>Paris</h3>
    <p>Paris is the capital of France.</p>
  </div>

  <div id="three" class="tabcontent">
    <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
    <h3>Tokyo</h3>
    <p>Tokyo is the capital of Japan.</p>
  </div>
</div>

</body>
</html>


问:
How to drop these rows in Pandas?
I am trying to drop the rows in my pandas dataframe that have no price in them. Technically, in the data source the dollar sign ($) appears by default so
df1.dropna(subset=['Price ($)'], inplace = True) does not work in my case. How can I drop the rows that have no price attached to them.

```<code>import pandas as pd

first = pd.read_excel('......')
df1 = pd.DataFrame(first)

   Car                          Price ($)

   Honda                          $200
   Benz                           $             ----------> drop
   Chevy                          $300
   BMW                            $250
   Kia                            $             ----------> drop
</code>```

答:
If I understand correctly this should work:

```<code>first = first[first['Price ($)'] != '$']
</code>```

This just keeps rows where the Price column isn't equal to '$'

Title: How to drop these rows in Pandas?

Body:
I am trying to drop the rows in my pandas dataframe that have no price in them. Technically, in the data source the dollar sign ($) appears by default so
df1.dropna(subset=['Price ($)'], inplace = True) does not work in my case. How can I drop the rows that have no price attached to them.

import pandas as pd

first = pd.read_excel('......')
df1 = pd.DataFrame(first)

   Car                          Price ($)

   Honda                          $200
   Benz                           $             ----------> drop
   Chevy                          $300
   BMW                            $250
   Kia                            $             ----------> drop

Body:
If I understand correctly this should work:

first = first[first['Price ($)'] != '$']

This just keeps rows where the Price column isn't equal to '$'


问:
Swiftmailer Ampersand Decoding Issue (&)
I've got a weird problem with Swiftmailer 5.x:

```<code>  $mailUrl = htmlspecialchars("$serverDiff/test/?action=passwordreset&token=$user_token");
  $mailtext = "Für Ihren Account wurde das Zurücksetzen des Passwortes veranlasst. Bitte gehen Sie über folgenden Link, um dies einzugeben: $mailUrl";
  $mailtext = $textclass->text($mailtext);
</code>```

This always returns & token= which, of course, is wrong. No matter how often I try to utf8_decode, encode, htmlspecialchars it or just try using the xhtml or unicode for the ampersand it still switches to &

Does anybody have an idea how to fix this? I already asked a bunch of colleagues and friends and no one knows ...
Thank you very much!

答:
I finally soluted this with the help of another post that lead me right to the answer:
https://stackoverflow.com/a/31426274/2181606

Just went into the framework (/swiftmailer-5.x/lib/classes/Swift/Mime/MimePart.php) in line 64 (setBody function) and inserted this (see line 2, first is just for positioning reference):

```<code>    $body = $this->_convertString($body);
    $body = str_replace('&', '&', $body);
</code>```

Thank you, me. :D

Body:
I've got a weird problem with Swiftmailer 5.x:

  $mailUrl = htmlspecialchars("$serverDiff/test/?action=passwordreset&token=$user_token");
  $mailtext = "Für Ihren Account wurde das Zurücksetzen des Passwortes veranlasst. Bitte gehen Sie über folgenden Link, um dies einzugeben: $mailUrl";
  $mailtext = $textclass->text($mailtext);

This always returns & token= which, of course, is wrong. No matter how often I try to utf8_decode, encode, htmlspecialchars it or just try using the xhtml or unicode for the ampersand it still switches to &

Does anybody have an idea how to fix this? I already asked a bunch of colleagues and friends and no one knows ...
Thank you very much!

Body:
I finally soluted this with the help of another post that lead me right to the answer:
https://stackoverflow.com/a/31426274/2181606

Just went into the framework (/swiftmailer-5.x/lib/classes/Swift/Mime/MimePart.php) in line 64 (setBody function) and inserted this (see line 2, first is just for positioning reference):

    $body = $this->_convertString($body);
    $body = str_replace('&amp;', '&', $body);

Thank you, me. :D


问:
how to change the pipeline name in data factory?
I have created pipeline in data factory I want to changer the pipeline name but when i change this in pipeline i am getting error can you please help me?

```<code>"name": "TEST_debt",
    "properties": {
        "description": "Luna_debt",
        "activities": [
            {
                "type": "Copy",
                "typeProperties": {
                    "source": {
                        "type": "RelationalSource",
                        "query": "select * from `orbitms_live`.`debt`"
                    },
</code>```

I want to change the name debt to Lunadebt

答:
The simply answer is, you can't perform a rename operation at a pipeline level.

But...

If you want to change it in the Azure portal you can Clone the pipeline from the Author and Deploy blade. Then deploy the pipeline again with the new name and drop the old version.

Or...

Use Visual Studio. Again, it won't rename the pipeline. At publish time it will detect the difference and give you the option to drop the old version and create the newly named pipeline.

In both cases I would recommend you Pause the pipeline via the Monitor and Manage area to avoid duplicate data (depending on your activities).

Hope this helps.

Body:
I have created pipeline in data factory I want to changer the pipeline name but when i change this in pipeline i am getting error can you please help me?

"name": "TEST_debt",
    "properties": {
        "description": "Luna_debt",
        "activities": [
            {
                "type": "Copy",
                "typeProperties": {
                    "source": {
                        "type": "RelationalSource",
                        "query": "select * from `orbitms_live`.`debt`"
                    },

I want to change the name debt to Lunadebt


问:
what is the best way to convert one dictionary to another
i have one dictionary that has entries that looks like this:

```<code>dictionary["ABC.123"] = "Test"
dictionary["DEF.123"] = "Test2"
dictionary["EFG.123"] = "Test3"
dictionary["EFG.343"] = "Test3"
dictionary["ABC.456"] = "Test"
</code>```

and i want to create a new dictionary that looks like this: (basically parse out the beginning string before the "." and create that as the key and use the same value.

```<code>dictionary["ABC"] = "Test"
dictionary["DEF"] = "Test2"
dictionary["EFG"] = "Test3"
</code>```

as you can see: there is always a 1 to 1 mapping between the first part of the key in the first dictionary to the value so there will be no clashes

what is the easiest way using LINQ to convert to create the second dictionary from the first ??

I can loop through each record manually and parse out the new key and create each new record but i figured there was a LINQ way of doing it

答:
A simple approach is to use the Select method to generate your desired KeyValuePair in conjuntion with ToDictionary</p>

```<code>var response = dictionary
              .Select(kvp => new KeyValuePair<string, string>(kvp.Key.Remove(kvp.Key.IndexOf('.')), kvp.Value))
              .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
</code>```

Body:
i have one dictionary that has entries that looks like this:

dictionary["ABC.123"] = "Test"
dictionary["DEF.123"] = "Test2"
dictionary["EFG.123"] = "Test3"
dictionary["EFG.343"] = "Test3"
dictionary["ABC.456"] = "Test"

and i want to create a new dictionary that looks like this: (basically parse out the beginning string before the "." and create that as the key and use the same value.

dictionary["ABC"] = "Test"
dictionary["DEF"] = "Test2"
dictionary["EFG"] = "Test3"

as you can see: there is always a 1 to 1 mapping between the first part of the key in the first dictionary to the value so there will be no clashes

what is the easiest way using LINQ to convert to create the second dictionary from the first ??

I can loop through each record manually and parse out the new key and create each new record but i figured there was a LINQ way of doing it

Body:
A simple approach is to use the Select method to generate your desired KeyValuePair in conjuntion with ToDictionary

var response = dictionary
              .Select(kvp => new KeyValuePair<string, string>(kvp.Key.Remove(kvp.Key.IndexOf('.')), kvp.Value))
              .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);


答:
You could try partition('=') to split from the first instance</p>

```<code>'PowSup=PS1(type=Emerson,fw=v.03.05.00)'.partition('=')[0:3:2]
</code>```

Title: Python split by character only if wrapped in parenthesis

Body:
You could try partition('=') to split from the first instance

'PowSup=PS1(type=Emerson,fw=v.03.05.00)'.partition('=')[0:3:2]


问:
How to leave a copy of the original file when we save the file
When modifying and saving a file, how to leave a copy of the original file, say give it *.bak?Is there a built-in support?</p>

答: You could use the .NET framework to simply copy the file to a .bak and then modify the original.</p>

ContentLicense: CC BY-SA 2.5


问:
React: How do I create an array from an API object and then select one element randomly for a value?
Do you know how I could make an array of the x,y coordinates and then select one randomly to place in a value?     </p>

```<code><g id="lines">
    {data.sites.map((item, i) => {
  let findX = (180 + item.attributes.address.Longitude) * (1552 / 360);
  let findY = (90 - item.attributes.address.Latitude) * (818/ 180);
let randoXY = findX + ',' findY (and randomly selects one of the X, Y values);
       return (
  <path key={i + i + '--'} id={'line' + (i + 1)} class="cls-3" d={'M' + findX + ','
+ findY +'L' + randoXY} />
                             )
   })}
</g>
</code>```

答:
Create an array that will contains some random points:

```<code>let arr = [0,1,2,3,4,5,6,7,8,9];
</code>```

Then Use Math.random() to select a random index, make sure index always lies within the length of the array (always multiply the value of Math.random() by the length of the array by this way it will never be greater than the length) then convert the value to integer by using Math.floor().

Use this to select random x and y values from the array:

```<code><g id="lines">
    {data.sites.map((item, i) => {
        let findX = (180 + item.attributes.address.Longitude) * (1552 / 360);
        let findY = (90 - item.attributes.address.Latitude) * (818/ 180);
        let x = a[Math.floor(Math.random() * 10)];
        let y = a[Math.floor(Math.random() * 10)];
        return (
            <path
                key={i + i + '--'}
                id={'line' + (i + 1)}
                class="cls-3"
                d={`M${findX}, ${findY}L${x},${y}`} />
        )})
    }
</g>
</code>```

Body:
Do you know how I could make an array of the x,y coordinates and then select one randomly to place in a value?

<g id="lines">
    {data.sites.map((item, i) => {
  let findX = (180 + item.attributes.address.Longitude) * (1552 / 360);
  let findY = (90 - item.attributes.address.Latitude) * (818/ 180);
let randoXY = findX + ',' findY (and randomly selects one of the X, Y values);
       return (
  <path key={i + i + '--'} id={'line' + (i + 1)} class="cls-3" d={'M' + findX + ','
+ findY +'L' + randoXY} />
                             )
   })}
</g>

Body:
Create an array that will contains some random points:

let arr = [0,1,2,3,4,5,6,7,8,9];

Then Use Math.random() to select a random index, make sure index always lies within the length of the array (always multiply the value of Math.random() by the length of the array by this way it will never be greater than the length) then convert the value to integer by using Math.floor().

Use this to select random x and y values from the array:

<g id="lines">
    {data.sites.map((item, i) => {
        let findX = (180 + item.attributes.address.Longitude) * (1552 / 360);
        let findY = (90 - item.attributes.address.Latitude) * (818/ 180);
        let x = a[Math.floor(Math.random() * 10)];
        let y = a[Math.floor(Math.random() * 10)];
        return (
            <path
                key={i + i + '--'}
                id={'line' + (i + 1)}
                class="cls-3"
                d={`M${findX}, ${findY}L${x},${y}`} />
        )})
    }
</g>


问:
Firebase on value event only fires once
In my React Native iOS app, it's possible to have multiple instances of a component mounted at the same time.

Think Instagram – when a user taps a photo in Instagram and then taps the photo owner's avatar, the user scene pushes in from the right.

If she then goes on to tap the same photo in the user's list of photos, a clone of the first scene will also push in the from right.

I need all instances of the scene to mount, establish the Firebase listener, get a snapshot of the initial data and listen for changes after that.

Everything works great for the first component instance.

However, in any subsequent instances, the listeners are defined, but their callbacks don't immediately execute, so the component does not receive a snapshot.

Worth noting is that both listeners do execute their callbacks when the data changes.

```<code>constructor(props) {

  super(props);

  const { uid } = props;

  // Set firebase refs
  this.postsRef = firebase.database().ref('posts');
  this.hostsRef = firebase.database()
    .ref(`users/${uid}/host`)
    .orderByChild('startTime');

  this.hostedPostRefs = {};

  // Keep a raw copy of the hosts
  this.hostedPosts = {};

  // ListView DataSource instance
  this.hostedPostsDataSource = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1._key !== r2._key,
  });

  // Initial State
  this.state = {
    loading: true,
    hostedPostsDataSource: this.hostedPostsDataSource.cloneWithRows(this.hostedPosts),
  };
}

componentDidMount() {
  this.hostsRef.on('value', this._onHostsReceived)
}

componentWillUnmount() {
  this.hostsRef.off();
  forEach(this.hostedPostRefs, hostedPostRef => {
    hostedPostRef.off()
  })
}

_onHostsReceived = (snapshot) => {
  snapshot.forEach(this._requestPost)
};

_requestPost = (snapshot) => {

  const { key } = snapshot;

  if (!this.hostedPostRefs[key]) {
    this.hostedPostRefs[key] = this.postsRef.child(key);
    this.hostedPostRefs[key].on('child_changed event', this._onPostReceived)
  }
};

_onPostReceived = (snapshot) => {
  this.hostedPosts[snapshot.key] = snapshot.val();
  this.setState({
    hostedPostsDataSource: this.hostedPostsDataSource.cloneWithRows(this.hostedPosts)
  });
};
</code>```

Here's what the Firebase docs have to say:

Firebase data is retrieved by attaching an asynchronous listener to a
firebase.database.Reference. The listener is triggered once for the
initial state of the data and again anytime the data changes.

I'm using React Native Firebase. Given that, I'm not sure if this is a bug in React Native Firebase or Firebase's API behaving as intended.

答: It was explained to me by a React Native Firebase contributor that there is a mistake in the library's db implementation and that it will be resolved in the near future.</p>

Title: Firebase on value event only fires once

Body:
In my React Native iOS app, it's possible to have multiple instances of a component mounted at the same time.

Think Instagram – when a user taps a photo in Instagram and then taps the photo owner's avatar, the user scene pushes in from the right.

If she then goes on to tap the same photo in the user's list of photos, a clone of the first scene will also push in the from right.

I need all instances of the scene to mount, establish the Firebase listener, get a snapshot of the initial data and listen for changes after that.

Everything works great for the first component instance.

However, in any subsequent instances, the listeners are defined, but their callbacks don't immediately execute, so the component does not receive a snapshot.

Worth noting is that both listeners do execute their callbacks when the data changes.

constructor(props) {

  super(props);

  const { uid } = props;

  // Set firebase refs
  this.postsRef = firebase.database().ref('posts');
  this.hostsRef = firebase.database()
    .ref(`users/${uid}/host`)
    .orderByChild('startTime');

  this.hostedPostRefs = {};

  // Keep a raw copy of the hosts
  this.hostedPosts = {};

  // ListView DataSource instance
  this.hostedPostsDataSource = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1._key !== r2._key,
  });

  // Initial State
  this.state = {
    loading: true,
    hostedPostsDataSource: this.hostedPostsDataSource.cloneWithRows(this.hostedPosts),
  };
}

componentDidMount() {
  this.hostsRef.on('value', this._onHostsReceived)
}

componentWillUnmount() {
  this.hostsRef.off();
  forEach(this.hostedPostRefs, hostedPostRef => {
    hostedPostRef.off()
  })
}

_onHostsReceived = (snapshot) => {
  snapshot.forEach(this._requestPost)
};

_requestPost = (snapshot) => {

  const { key } = snapshot;

  if (!this.hostedPostRefs[key]) {
    this.hostedPostRefs[key] = this.postsRef.child(key);
    this.hostedPostRefs[key].on('child_changed event', this._onPostReceived)
  }
};

_onPostReceived = (snapshot) => {
  this.hostedPosts[snapshot.key] = snapshot.val();
  this.setState({
    hostedPostsDataSource: this.hostedPostsDataSource.cloneWithRows(this.hostedPosts)
  });
};

Here's what the Firebase docs have to say:

Firebase data is retrieved by attaching an asynchronous listener to a
firebase.database.Reference. The listener is triggered once for the
initial state of the data and again anytime the data changes.

I'm using React Native Firebase. Given that, I'm not sure if this is a bug in React Native Firebase or Firebase's API behaving as intended.


问:
How to convert a string to hyphen-conjoined words in JavaScript (& regex?)?
Let's say I have a string of text:

```<code>The quick brown fox jumped over 8 or 9 lazy dogs
</code>```

How would you convert this to lower case hyphen-conjoined words like this?

```<code>the-quick-brown-fox-jumped-over-8-or-9-lazy-dogs
</code>```

I assume it requires some kind of regex to convert it correctly?

答:
```<code>str.replace(/ +/g, '-').toLowerCase();
</code>```

Body:
Let's say I have a string of text:

The quick brown fox jumped over 8 or 9 lazy dogs

How would you convert this to lower case hyphen-conjoined words like this?

the-quick-brown-fox-jumped-over-8-or-9-lazy-dogs

I assume it requires some kind of regex to convert it correctly?

Body: str.replace(/ +/g, '-').toLowerCase();


问:
Matplotlib Scatter - ValueError: RGBA sequence should have length 3 or 4
I am trying to plot a graph for my features and I keep getting this error:

```<code>ValueError: RGBA sequence should have length 3 or 4
</code>```

The code worked perfectly whenever I only had 6 types of shapes but now that i've increased it to 10 it wont work?

If I make c=c with c = np.random.random((100, 4)) instead of c=y it works but then every data point has a different colour.

My code is:

```<code>features = ["Number of Sides", "Standard Deviation of Number of Sides/Perimeter",
      "Standard Deviation of the Angles", "Largest Angle"]

features1 = ["Label"]

def Build_Data_Set():

    data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")

    #This line randomly shuffles the data so that the different types of training data get
    #mixed up randomly to prevent the data being skewed
    data_df = data_df.reindex(np.random.permutation(data_df.index))
    X = np.array(data_df[features].values)

    data_df2 = pd.DataFrame.from_csv("AllMixedShapes2.csv")
    y = np.array(data_df2[features1].replace("Circle",0).replace("Equilateral Triangle",1)
             .replace("Right Angle Triangle",2).replace("Acute Triangle",3)
             .replace("Obtuse Triangle",4).replace("Square",5)
             .replace("Parallelogram",6).replace("Rectangle",7)
             .replace("Pentagon",8).replace("Seal",9).values.tolist())
return X,y

def SVC_Analysis():

    test_size = 300
    X,y = Build_Data_Set()

    clf = svm.SVC(kernel = 'rbf', C = 1.0)
    clf.fit(X[:test_size],y[:test_size])

    correct_count = 0

    for x in range(1, test_size+1):
            if clf.predict(X[-x])[0] == y[-x]:
                correct_count += 1

    print("Accuracy:", (correct_count/test_size) * 100.00)

    data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")
    X1 = np.array(data_df[features2].values)
    y1 = np.array(data_df[features3].values)
    #w = clf.coef_[0]
    #a = -w[0] / w[1]
    xx = np.linspace(0,5)
    yy = np.linspace(0,185)

    h0 = plt.plot(xx,yy, "k-", label="non weighted")

    plt.scatter(X1[:, 0],y1, c=y, cmap=plt.cm.Paired)
    plt.ylabel("Maximum Angle (Degrees)")
    plt.xlabel("Number Of Sides")
    plt.title('Shapes')
    plt.legend()
    plt.show()

SVC_Analysis()
</code>```

My csv file for reference looks like

As far as I can tell the problem is to do with c=y, cmap=plt.cm.Paired) but I cant be sure and I cant find a solution.

Body:
I am trying to plot a graph for my features and I keep getting this error:

ValueError: RGBA sequence should have length 3 or 4

The code worked perfectly whenever I only had 6 types of shapes but now that i've increased it to 10 it wont work?

If I make c=c with c = np.random.random((100, 4)) instead of c=y it works but then every data point has a different colour.

My code is:

features = ["Number of Sides", "Standard Deviation of Number of Sides/Perimeter",
      "Standard Deviation of the Angles", "Largest Angle"]

features1 = ["Label"]

def Build_Data_Set():

    data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")

    #This line randomly shuffles the data so that the different types of training data get
    #mixed up randomly to prevent the data being skewed
    data_df = data_df.reindex(np.random.permutation(data_df.index))
    X = np.array(data_df[features].values)

    data_df2 = pd.DataFrame.from_csv("AllMixedShapes2.csv")
    y = np.array(data_df2[features1].replace("Circle",0).replace("Equilateral Triangle",1)
             .replace("Right Angle Triangle",2).replace("Acute Triangle",3)
             .replace("Obtuse Triangle",4).replace("Square",5)
             .replace("Parallelogram",6).replace("Rectangle",7)
             .replace("Pentagon",8).replace("Seal",9).values.tolist())
return X,y

def SVC_Analysis():

    test_size = 300
    X,y = Build_Data_Set()

    clf = svm.SVC(kernel = 'rbf', C = 1.0)
    clf.fit(X[:test_size],y[:test_size])

    correct_count = 0

    for x in range(1, test_size+1):
            if clf.predict(X[-x])[0] == y[-x]:
                correct_count += 1

    print("Accuracy:", (correct_count/test_size) * 100.00)

    data_df = pd.DataFrame.from_csv("AllMixedShapes2.csv")
    X1 = np.array(data_df[features2].values)
    y1 = np.array(data_df[features3].values)
    #w = clf.coef_[0]
    #a = -w[0] / w[1]
    xx = np.linspace(0,5)
    yy = np.linspace(0,185)

    h0 = plt.plot(xx,yy, "k-", label="non weighted")

    plt.scatter(X1[:, 0],y1, c=y, cmap=plt.cm.Paired)
    plt.ylabel("Maximum Angle (Degrees)")
    plt.xlabel("Number Of Sides")
    plt.title('Shapes')
    plt.legend()
    plt.show()

SVC_Analysis()

My csv file for reference looks like

As far as I can tell the problem is to do with c=y, cmap=plt.cm.Paired) but I cant be sure and I cant find a solution.

Body:
Your y array looks like

 ['3']
 ['9']
 ['0']
 ['5']
 ['5']
 ['Triangle']
 ['7']
 ['9']
 ['0']
 ['0']
...

while in reality it should look like

[3,9,0,5,5,5,7,9,0,0, ...]


问:
Substituting Variables Value in Mongodb statement
My main intention is to dynamically change the Employees collection while using pymongo, and i was able to do it for insert commands, I am facing problems with the find command, no matter what i do exec() always returns None. but if i copy the string and run it value gets assigned to the variable.

can someone throw some light on why the exec is unable to return a resultset or assign a the resultset to a variable?

```<code>db.Employees.update_one(
        {"id": criteria},
        {
        "$set": {
            "name":name,
            "age":age,
            "country":country
        }
        }
    )

from pymongo import MongoClient
import ast

client = MongoClient('localhost:27017')
db = client.TextClassifier
</code>```

insert works

```<code>def mongo_insert_one(COLLECTION_NAME, JSON):
    QUERY = """db.%(COLLECTION_NAME)s.insert_one( %(JSON)s )""" % locals();
    exec(QUERY)

def mongo_retrive(COLLECTION_NAME, JSON):
    resultset = None
    query = """resultset = db.%(COLLECTION_NAME)s.find( %(JSON)s )""" % locals();
    return resultset

print(mongo_retrive('hungry_intent', "{'Intent':'Hungry'}"))
</code>```

neither this would work

```<code>resultset = exec(""" db.%(COLLECTION_NAME)s.find( %(JSON)s )""" % locals();)
</code>```

this would not work for an entirely different reason,it says If you meant to call the 'locals' method on a 'Database' object it is failing because no such method exists.

```<code>resultset = db.locals()[COLLECTION_NAME].find()
</code>```

答:
PyMongo Database objects support bracket notation to access a named collection, and PyMongo's included bson module provides a much better JSON decoder than "eval":

```<code>from bson import json_util

COLLECTION_NAME = 'hungry_intent'
JSON = "{'Intent':'Hungry'}"
print(list(db[COLLECTION_NAME].find(json_util.loads(JSON))))
</code>```

This will be faster and more reliable than your "eval" code, and also prevents the injection attack that your "eval" code is vulnerable to.

If you can avoid using JSON at all it could be preferable:

```<code>COLLECTION_NAME = 'hungry_intent'
QUERY = {'Intent':'Hungry'}
print(list(db[COLLECTION_NAME].find(QUERY)))
</code>```

Body:
My main intention is to dynamically change the Employees collection while using pymongo, and i was able to do it for insert commands, I am facing problems with the find command, no matter what i do exec() always returns None. but if i copy the string and run it value gets assigned to the variable.

can someone throw some light on why the exec is unable to return a resultset or assign a the resultset to a variable?

db.Employees.update_one(
        {"id": criteria},
        {
        "$set": {
            "name":name,
            "age":age,
            "country":country
        }
        }
    )

from pymongo import MongoClient
import ast

client = MongoClient('localhost:27017')
db = client.TextClassifier

insert works

def mongo_insert_one(COLLECTION_NAME, JSON):
    QUERY = """db.%(COLLECTION_NAME)s.insert_one( %(JSON)s )""" % locals();
    exec(QUERY)

def mongo_retrive(COLLECTION_NAME, JSON):
    resultset = None
    query = """resultset = db.%(COLLECTION_NAME)s.find( %(JSON)s )""" % locals();
    return resultset

print(mongo_retrive('hungry_intent', "{'Intent':'Hungry'}"))

neither this would work

resultset = exec(""" db.%(COLLECTION_NAME)s.find( %(JSON)s )""" % locals();)

this would not work for an entirely different reason,it says If you meant to call the 'locals' method on a 'Database' object it is failing because no such method exists.

resultset = db.locals()[COLLECTION_NAME].find()

Body:
PyMongo Database objects support bracket notation to access a named collection, and PyMongo's included bson module provides a much better JSON decoder than "eval":

from bson import json_util

COLLECTION_NAME = 'hungry_intent'
JSON = "{'Intent':'Hungry'}"
print(list(db[COLLECTION_NAME].find(json_util.loads(JSON))))

This will be faster and more reliable than your "eval" code, and also prevents the injection attack that your "eval" code is vulnerable to.

If you can avoid using JSON at all it could be preferable:

COLLECTION_NAME = 'hungry_intent'
QUERY = {'Intent':'Hungry'}
print(list(db[COLLECTION_NAME].find(QUERY)))


问:
How do I keep all data in a td side by side fixed height
I am trying to put all these three data side by side. Like the second row last column. but after the first column (within php loop) 3rd and 4th elements get to lower line.
screenshot

here is what I have tried (included style in line.

```<code><?php while ($each_row = mysqli_fetch_assoc($table_data)){ ?>
                        <tr style="border: 1px solid black; ">
                            <td style="border: 1px solid black;"><?php echo $i; ?></td>
                            <td style="border: 1px solid black;"><?php echo $each_row["roll"]; ?></td>
                            <td style="border: 1px solid black;"><?php echo $each_row["name"]; ?></td>
                            <td style="border: 1px solid black; text-align:center;"><?php echo $each_row["present"]; ?></td>
                            <td style="border: 1px solid black; width: 300px;">
                                    <a href="attendence.php?change=present&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>">
                                        <button type="button" name="button">Present</button></a>
                                    <a href="attendence.php?change=absent&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>">
                                        <button type="button" name="button">Absent</button></a>
                                    <form class="" style="width: 100px;" action="attendence.php?change=absent&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>" method="post">
                                        <input style="width: 50px;" type="text" name="late" value="0">
                                        <input style="width: 50px;" type="submit" name="" value="Late">
                                    </form>
                            </td>
                        </tr>
      <?php } ?>
</code>```

答:
I have a different view for your design, it might be little difficult for you to digest but you can go for BOOTSTRAP framework and use simple grid to design the same thing using
 or  tags in the tabular view (which will be responsive too) and will make you form look even better.

For Reference : Bootstrap Grid System

Body:
I am trying to put all these three data side by side. Like the second row last column. but after the first column (within php loop) 3rd and 4th elements get to lower line.
screenshot

here is what I have tried (included style in line.

<?php while ($each_row = mysqli_fetch_assoc($table_data)){ ?>

                            <?php echo $i; ?>
                            <?php echo $each_row["roll"]; ?>
                            <?php echo $each_row["name"]; ?>
                            <?php echo $each_row["present"]; ?>

                                    <a href="attendence.php?change=present&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>">
                                        <button type="button" name="button">Present</button>
                                    <a href="attendence.php?change=absent&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>">
                                        <button type="button" name="button">Absent</button>
                                    <form class="" style="width: 100px;" action="attendence.php?change=absent&date=<?php echo $today; ?>&class=<?php echo $class; ?>&batch=<?php echo $batch; ?>&roll=<?php echo $each_row["roll"]; ?>" method="post">
                                        <input style="width: 50px;" type="text" name="late" value="0">
                                        <input style="width: 50px;" type="submit" name="" value="Late">
                                    </form>

      <?php } ?>

Body:
I have a different view for your design, it might be little difficult for you to digest but you can go for BOOTSTRAP framework and use simple grid to design the same thing using <div> or <span> tags in the tabular view (which will be responsive too) and will make you form look even better.

For Reference : Bootstrap Grid System


问:
How to connect PHP with HIVE?
I want to make a website where I'll be using big data at back end . I'm using hadoop framework and I wish to store the data in HDFS and want to fetch it using HIVE and display it in the browser.
 I do know how to fetch and display data using PHP+MySQL.
 Now the problem is I don't know how to use PHP with HIVE to do the job.
 I'll be thankful to you if you kindly explain it from the scratch.
:)</p>

答:
Try using the ODBC connectors available for Hive.
https://cwiki.apache.org/confluence/display/Hive/HiveODBC
http://php.net/manual/en/function.odbc-connect.php

Hive also has a Thrift interface which is more faster.
https://cwiki.apache.org/confluence/display/Hive/HiveClient#HiveClient-Thrift
https://thrift.apache.org/tutorial/php

Title: How to connect PHP with HIVE?


问:
Sencha Touch: List ItemTap Event Firing
I am following along very closely with the code within the GeoCongress.us App, as this is my first Sencha Touch app and the premise behind that app's layout functionality is similar to what I hope to achieve.

I am having an issue getting a List object to respond to the itemtap event though. My intent is to capture the itemtap event at the SetsScreen level, fire my own custom event which my App object would listen for, and App could then handle the process of displaying a new card (based on the item tapped).

First, the SetsScreen object (relevant portions of it at least):

```<code>DataSets.views.SetsScreen = Ext.extend(Ext.Panel, {
    cls: 'sets-screen',
    layout: 'card',

    initComponent: function() {
        // Build the main content list and add it to the main scren
        this.setsList = new DataSets.views.SetsList({
            scroll: false
        });
        this.setsList.on('itemtap', this.onListItemTap, this);

        this.main = new Ext.Container({
            scroll: true,
            items: [this.setsList]
        });

        this.items = [this.main];
        DataSets.views.SetsScreen.superclass.initComponent.call(this);
    },

    onListItemTap: function(dv, index, item, e) {
        alert('Test');
    }
});
</code>```

Here is my SetsList object (nothing really amazing here):

```<code>DataSets.views.SetsList = Ext.extend(Ext.List, {
    itemSelector: '.sets-list-item',
    singleSelect: true,

    initComponent: function() {
        this.store = DataSets.stores.Sets;
        this.itemTpl = Ext.XTemplate.from('sets-list');

        DataSets.views.SetsList.superclass.initComponent.call(this);
    }
});
</code>```

And the Sets object is nothing more than a quick data model and Ext.data.Store:

```<code>Ext.regModel('Sets', {
    idProperty: 'id',
    fields: [
        'title',
        'last_updated',
        'current_value'
    ]
});

DataSets.stores.Sets = new Ext.data.Store({
    model: 'Sets',
    data: [
        {id: 0, title: 'Weight', last_updated: new Date('11/28/2010 00:00:00 AM GMT-0600'), current_value: 145},
        {id: 1, title: 'Cups of Coffee', last_updated: new Date('11/28/2010 07:00:00 AM GMT-0600'), current_value: 1}
    ]
});
</code>```

答:
Oh man - I don't know how I stumbled across this answer, a very obscure typo was the only thing preventing this from working.

Ext.List() uses it's itemSelector property to determine what element qualified for a "tap". My itemSelector was set to .sets-list-item but the template had
. Correcting the template and itemtap is firing as expected.

Title: Sencha Touch: List ItemTap Event Firing

Body:
I am following along very closely with the code within the GeoCongress.us App, as this is my first Sencha Touch app and the premise behind that app's layout functionality is similar to what I hope to achieve.

I am having an issue getting a List object to respond to the itemtap event though. My intent is to capture the itemtap event at the SetsScreen level, fire my own custom event which my App object would listen for, and App could then handle the process of displaying a new card (based on the item tapped).

First, the SetsScreen object (relevant portions of it at least):

DataSets.views.SetsScreen = Ext.extend(Ext.Panel, {
    cls: 'sets-screen',
    layout: 'card',

    initComponent: function() {
        // Build the main content list and add it to the main scren
        this.setsList = new DataSets.views.SetsList({
            scroll: false
        });
        this.setsList.on('itemtap', this.onListItemTap, this);

        this.main = new Ext.Container({
            scroll: true,
            items: [this.setsList]
        });

        this.items = [this.main];
        DataSets.views.SetsScreen.superclass.initComponent.call(this);
    },

    onListItemTap: function(dv, index, item, e) {
        alert('Test');
    }
});

Here is my SetsList object (nothing really amazing here):

DataSets.views.SetsList = Ext.extend(Ext.List, {
    itemSelector: '.sets-list-item',
    singleSelect: true,

    initComponent: function() {
        this.store = DataSets.stores.Sets;
        this.itemTpl = Ext.XTemplate.from('sets-list');

        DataSets.views.SetsList.superclass.initComponent.call(this);
    }
});

And the Sets object is nothing more than a quick data model and Ext.data.Store:

Ext.regModel('Sets', {
    idProperty: 'id',
    fields: [
        'title',
        'last_updated',
        'current_value'
    ]
});

DataSets.stores.Sets = new Ext.data.Store({
    model: 'Sets',
    data: [
        {id: 0, title: 'Weight', last_updated: new Date('11/28/2010 00:00:00 AM GMT-0600'), current_value: 145},
        {id: 1, title: 'Cups of Coffee', last_updated: new Date('11/28/2010 07:00:00 AM GMT-0600'), current_value: 1}
    ]
});

Body:
Oh man - I don't know how I stumbled across this answer, a very obscure typo was the only thing preventing this from working.

Ext.List() uses it's itemSelector property to determine what element qualified for a "tap". My itemSelector was set to .sets-list-item but the template had <div class="set-list-item">. Correcting the template and itemtap is firing as expected.


问:
Azure VHD performance vs BLOB
I have 2 containers in the same blob service. One contains a single VHD, the other a single test PDF.

Running a process in a VM to which the VHD is attached, I get the following numbers.

VHD read:

```<code>// VHD = e: drive, copy files
using (FileStream fs = new FileStream(@"e:\various\14681.pdf", FileMode.Open))
using (var mstream = new MemoryStream())
{
    byte[] buffer = new byte[32 * 1024];
    int bytesRead;
    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
    {
        mstream.Write(buffer, 0, bytesRead);
    }
}
// 20MB file = 250ms, 250k file = <1ms
</code>```

blockBlob.DownloadToStream:

```<code>//read blob
//CloudBlockBlob blockBlob = container.GetBlockBlobReference("14681.pdf");

using (var mstream = new MemoryStream())
{
    blockBlob.DownloadToStream(mstream);
}

// 20MB file = 700-800ms, 250k file = 40ms
</code>```

Why is there such a difference in the performance of these two processes

答:
Well, when you access the storage blob you are going through the public internet (not even internally), so that adds latency and when you access the VHD you go through the Azure Backbone (the hypervisor does that for you).

I would speculate that this is the main reason.

Title: Azure VHD performance vs BLOB

Body:
I have 2 containers in the same blob service. One contains a single VHD, the other a single test PDF.

Running a process in a VM to which the VHD is attached, I get the following numbers.

VHD read:

// VHD = e: drive, copy files
using (FileStream fs = new FileStream(@"e:\various\14681.pdf", FileMode.Open))
using (var mstream = new MemoryStream())
{
    byte[] buffer = new byte[32 * 1024];
    int bytesRead;
    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
    {
        mstream.Write(buffer, 0, bytesRead);
    }
}
// 20MB file = 250ms, 250k file = <1ms

blockBlob.DownloadToStream:

//read blob
//CloudBlockBlob blockBlob = container.GetBlockBlobReference("14681.pdf");

using (var mstream = new MemoryStream())
{
    blockBlob.DownloadToStream(mstream);
}

// 20MB file = 700-800ms, 250k file = 40ms

Why is there such a difference in the performance of these two processes


问:
Python, replacing characters in a string while preserving original string
More specifically:

Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

```<code>def(base,word):
plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"
</code>```

My original thought was this:

```<code>def main():

    x = base.split(word)
    y = ''.join(x)
    print(y.replace(y,'+')*len(y))
</code>```

From here I have trouble reinserting the word back into the str in the correct places. Any help is appreciated.

答:
You can use any string to join (instead of the empty string '' like you have).

```<code>def plusOut(s, word):
    x = s.split(word)
    y = ['+' * len(z) for z in x]
    final = word.join(y)
    return final
</code>```

Edit: I've removed the regex, but I'm keeping the function across multiple lines to more closely match your original code.

Body:
More specifically:

Given a string and a non-empty word string, return a version of the original String where all chars have been replaced by pluses ("+"), except for appearances of the word string which are preserved unchanged.

def(base,word):
plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

My original thought was this:

def main():

    x = base.split(word)
    y = ''.join(x)
    print(y.replace(y,'+')*len(y))

From here I have trouble reinserting the word back into the str in the correct places. Any help is appreciated.

Body:
You can use any string to join (instead of the empty string '' like you have).

def plusOut(s, word):
    x = s.split(word)
    y = ['+' * len(z) for z in x]
    final = word.join(y)
    return final

Edit: I've removed the regex, but I'm keeping the function across multiple lines to more closely match your original code.


问:
Putting a dict into a dataframe - python
I have a list called 'gender', of which I counted all the occurrences of the values with Counter:

```<code>gender = ['2',
          'Female,',
          'All Female Group,',
          'All Male Group,',
          'Female,',
          'Couple,',
          'Mixed Group,'....]

gender_count = Counter(gender)
gender_count
Counter({'2': 1,
     'All Female Group,': 222,
     'All Male Group,': 119,
     'Couple,': 256,
     'Female,': 1738,
     'Male,': 2077,
     'Mixed Group,': 212,
     'NA': 16})
</code>```

I want to put this dict into a pandas Dataframe. I have used pd.series(Convert Python dict into a dataframe):

```<code>s = pd.Series(gender_count, name='gender count')
s.index.name = 'gender'
s.reset_index()
</code>```

Which gives me the dataframe I want, but I don't know how to save these steps into a pandas DataFrame.
I also tried using DataFrame.from_dict()

```<code>s2 = pd.DataFrame.from_dict(gender_count, orient='index')
</code>```

But this creates a dataframe with the categories of gender as the index.

I eventually want to use gender categories and the count for a piechart.

答:
Skip the intermediate step</p>

```<code>gender = ['2',
          'Female',
          'All Female Group',
          'All Male Group',
          'Female',
          'Couple',
          'Mixed Group']

pd.value_counts(gender)

Female              2
2                   1
Couple              1
Mixed Group         1
All Female Group    1
All Male Group      1
dtype: int64
</code>```

Body:
I have a list called 'gender', of which I counted all the occurrences of the values with Counter:

gender = ['2',
          'Female,',
          'All Female Group,',
          'All Male Group,',
          'Female,',
          'Couple,',
          'Mixed Group,'....]

gender_count = Counter(gender)
gender_count
Counter({'2': 1,
     'All Female Group,': 222,
     'All Male Group,': 119,
     'Couple,': 256,
     'Female,': 1738,
     'Male,': 2077,
     'Mixed Group,': 212,
     'NA': 16})

I want to put this dict into a pandas Dataframe. I have used pd.series(Convert Python dict into a dataframe):

s = pd.Series(gender_count, name='gender count')
s.index.name = 'gender'
s.reset_index()

Which gives me the dataframe I want, but I don't know how to save these steps into a pandas DataFrame.
I also tried using DataFrame.from_dict()

s2 = pd.DataFrame.from_dict(gender_count, orient='index')

But this creates a dataframe with the categories of gender as the index.

I eventually want to use gender categories and the count for a piechart.

Body:
Skip the intermediate step

gender = ['2',
          'Female',
          'All Female Group',
          'All Male Group',
          'Female',
          'Couple',
          'Mixed Group']

pd.value_counts(gender)

Female              2
2                   1
Couple              1
Mixed Group         1
All Female Group    1
All Male Group      1
dtype: int64


问:
Method in button onclick is running even if button is not clicked
I am trying to delete or set node values to null in my firebase database, but the the method inside my onClick listener is running without me pressing the button.</p>

```<code> btn_cancel.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) {

                     DatabaseReference myRef = database.getReference("Orders").child(user_id);

                     myRef.addValueEventListener(new ValueEventListener()
                    {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot)
                        {

                            myRef.child("Session").setValue(null);
                          //  myRef.child("Dabba Type").removeValue();
                          //  myRef.child("Start date").removeValue();
                          //  myRef.child("End date").removeValue();
                           // myRef.child("Address").removeValue();

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError)
                        {

                        }
                    });
</code>```

答:
If you only want to change/modify data, then setValue() alone is enough. You don't need to attach addValueEventListener. Like this:

```<code>public void onClick(View v) {
    database.getReference("Orders").child(user_id).child).child("Session").setValue(null);
}
</code>```

Additional info (maybe will not work if applied to the code in question, but this information likely to be useful)

If you also want to read the value first before committing any change (like confirming if is true then change it to false and otherwise), then you should consider using addListenerForSingleValueEvent instead of addValueEventListener. Because it only do your code once while the later is keep listening to any data change that happen until you remove/detach the listener. And in this case, you should do it like this:

```<code>@Override
public void onClick(View v) {
    DatabaseReference myRef = database.getReference("Orders").child(user_id);
    myRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue(Boolean.class)) {
                // if value is true, change data
                myRef.setValue(false);
    ...
</code>```

Hope this helps

Body:
I am trying to delete or set node values to null in my firebase database, but the the method inside my onClick listener is running without me pressing the button.

 btn_cancel.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v) {

                     DatabaseReference myRef = database.getReference("Orders").child(user_id);

                     myRef.addValueEventListener(new ValueEventListener()
                    {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot)
                        {

                            myRef.child("Session").setValue(null);
                          //  myRef.child("Dabba Type").removeValue();
                          //  myRef.child("Start date").removeValue();
                          //  myRef.child("End date").removeValue();
                           // myRef.child("Address").removeValue();

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError)
                        {

                        }
                    });

Body:
If you only want to change/modify data, then setValue() alone is enough. You don't need to attach addValueEventListener. Like this:

public void onClick(View v) {
    database.getReference("Orders").child(user_id).child).child("Session").setValue(null);
}

Additional info (maybe will not work if applied to the code in question, but this information likely to be useful)

If you also want to read the value first before committing any change (like confirming if is true then change it to false and otherwise), then you should consider using addListenerForSingleValueEvent instead of addValueEventListener. Because it only do your code once while the later is keep listening to any data change that happen until you remove/detach the listener. And in this case, you should do it like this:

@Override
public void onClick(View v) {
    DatabaseReference myRef = database.getReference("Orders").child(user_id);
    myRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue(Boolean.class)) {
                // if value is true, change data
                myRef.setValue(false);
    ...

Hope this helps


问:
Writing to DB failed?
I'm trying to write 2 data to db.

```<code>  @IBAction func show(button: UIButton) {

        let userRef = self.dataBaseRef.child("users/\(FIRAuth.auth()!.currentUser!.uid)")
        userRef.observe(.value, with: { (snapshot) in
            let user = User(snapshot: snapshot)
            let currentUser = user.email
            let request = Requests(requestBy: user.email!,
                                   requestTo: self.email!)

            let contactRef = self.ref.child(currentUser! + "--" + self.email!)
            contactRef.setValue(request.toAnyObject())
            self.items.append(request)
            print(request)
        }) { (error ) in
            print(error.localizedDescription)
        }

        self.dismiss(animated: true, completion: nil);

}
</code>```

items is an array

```<code>var items: [Requests] = []
</code>```

user.email and self.email! isn't empty I printed it.

request file looks

```<code>struct Requests {

let key: String
let requestBy: String
let requestTo: String
let ref: FIRDatabaseReference?

init(requestBy: String, requestTo: String, key: String = "") {
    self.key = key
    self.requestBy = requestBy
    self.requestTo = requestTo
    self.ref = nil
}

init(snapshot: FIRDataSnapshot) {
    key = snapshot.key
    let snapshotValue = snapshot.value as! [String: AnyObject]
    requestBy = snapshotValue["requestBy"] as! String
    requestTo = snapshotValue["requestTo"] as! String
    ref = snapshot.ref
}

func toAnyObject() -> Any {
    return [
        "requestBy": requestBy,
        "requestTo": requestTo
    ]
}
</code>```

}

and I'm getting error - unexpectedly found nil while unwrapping an Optional value

答:
```<code>let currentUser = user.email  //this is not an optional
let request = Requests(requestBy: user.email!,
                                   requestTo: self.email!)

contactRef = self.ref.child(currentUser! + "--" + self.email!)
</code>```

currentUser! doesn't need to be unwrapped.

Title: Writing to DB failed?

Body:
I'm trying to write 2 data to db.

  @IBAction func show(button: UIButton) {

        let userRef = self.dataBaseRef.child("users/\(FIRAuth.auth()!.currentUser!.uid)")
        userRef.observe(.value, with: { (snapshot) in
            let user = User(snapshot: snapshot)
            let currentUser = user.email
            let request = Requests(requestBy: user.email!,
                                   requestTo: self.email!)

            let contactRef = self.ref.child(currentUser! + "--" + self.email!)
            contactRef.setValue(request.toAnyObject())
            self.items.append(request)
            print(request)
        }) { (error ) in
            print(error.localizedDescription)
        }

        self.dismiss(animated: true, completion: nil);

}

items is an array

var items: [Requests] = []

user.email and self.email! isn't empty I printed it.

request file looks

struct Requests {

let key: String
let requestBy: String
let requestTo: String
let ref: FIRDatabaseReference?

init(requestBy: String, requestTo: String, key: String = "") {
    self.key = key
    self.requestBy = requestBy
    self.requestTo = requestTo
    self.ref = nil
}

init(snapshot: FIRDataSnapshot) {
    key = snapshot.key
    let snapshotValue = snapshot.value as! [String: AnyObject]
    requestBy = snapshotValue["requestBy"] as! String
    requestTo = snapshotValue["requestTo"] as! String
    ref = snapshot.ref
}

func toAnyObject() -> Any {
    return [
        "requestBy": requestBy,
        "requestTo": requestTo
    ]
}

}

and I'm getting error - unexpectedly found nil while unwrapping an Optional value

Body:
let currentUser = user.email  //this is not an optional
let request = Requests(requestBy: user.email!,
                                   requestTo: self.email!)

contactRef = self.ref.child(currentUser! + "--" + self.email!)

currentUser! doesn't need to be unwrapped.


问:
How to extract row based on list of hex interval with awk?

Input file

```<code>U+3400  qiū
U+3401  tiàn
…
U+4E00  yī
U+4E01  dīng
…
U+2B5E7 sù
U+2B5EE huáng
</code>```

List of intervals

List of unicode codepoint

```<code>4E00-9FFF
3400-4DBF
20000-2A6DF
2A700-2B73F
2B740-2B81F
2B820-2CEAF
F900-FAFF
</code>```

Question

How do I print only the row that belong to one of the hexadecimal interval?

答:
chinese.awk

```<code>#!/usr/bin/env awk

BEGIN {
    split(toggleValues, boundaries, ",")
    start=0
    end=start+1
}

/U\+/ && /kMandarin/ {
    row = toHex($1);
    if (toHex(boundaries[start]) <= row && row <= toHex(boundaries[end])) print $1"\t"$3
    if (row >= toHex(boundaries[end])) {start+=2; end=start+1}
}

function toHex(field) { return strtonum("0x" substr(field, 3)) };
</code>```

Usage

```<code>toggleValues="U+4E00,U+9FFF,U+3400,U+4DBF,U+20000,U+2A6DF,U+2A700,U+2B73F,U+2B740,U+2B81F,U+2B820,U+2CEAF,U+F900,U+FAFF"
awk -f src/chinese.awk \
    -v toggleValues="$toggleValues" src/Unihan_Readings.txt
> src/codepoint-ruby.tsv
</code>```

Body:
Input file

U+3400  qiū
U+3401  tiàn
…
U+4E00  yī
U+4E01  dīng
…
U+2B5E7 sù
U+2B5EE huáng

List of intervals

List of unicode codepoint

4E00-9FFF
3400-4DBF
20000-2A6DF
2A700-2B73F
2B740-2B81F
2B820-2CEAF
F900-FAFF

Question

How do I print only the row that belong to one of the hexadecimal interval?

Body:
chinese.awk

#!/usr/bin/env awk

BEGIN {
    split(toggleValues, boundaries, ",")
    start=0
    end=start+1
}

/U\+/ && /kMandarin/ {
    row = toHex($1);
    if (toHex(boundaries[start]) <= row && row <= toHex(boundaries[end])) print $1"\t"$3
    if (row >= toHex(boundaries[end])) {start+=2; end=start+1}
}

function toHex(field) { return strtonum("0x" substr(field, 3)) };

Usage

toggleValues="U+4E00,U+9FFF,U+3400,U+4DBF,U+20000,U+2A6DF,U+2A700,U+2B73F,U+2B740,U+2B81F,U+2B820,U+2CEAF,U+F900,U+FAFF"
awk -f src/chinese.awk \
    -v toggleValues="$toggleValues" src/Unihan_Readings.txt
> src/codepoint-ruby.tsv


问:
Printing byte array containing EBCDIC values doesnt give expected value
I created a string converted got a  byte array using EBCDIC encoding from it. When I printed the array the value of H it is not the same found in EBCDIC chart.

Expected output

EBCDIC Value for "H"-->200 as per link EBCDIC 1047 chart

Actual output

EBCDIC Value for "H"-->[-56]

```<code>public static void main(String[] args) throws UnsupportedEncodingException {
    String str = "H";
    byte[] b1 = new byte[10];
    b1 = str.getBytes("Cp1047");
    System.out.println(Arrays.toString(b1));

    for (byte b : b1) {
        System.out.println(b);
    }

    b1 = str.getBytes("UTF-16");
    System.out.println(Arrays.toString(b1));

    b1 = str.getBytes();
    System.out.println(Arrays.toString(b1));
}
</code>```

答:
In your loop

```<code>for (byte b : b1)
   System.out.println(b);
</code>```

Java is sign extending b (a byte) when it promotes it to an integer which results in the value of 0xFFFFFFC8 being printed.  0xFFFFFFC8 is the two's complement representation of the signed number -56.  See this. You can prevent the sign extension by doing this:

```<code>for (byte b  :b1)
  System.out.println(b & 0xFF);
</code>```

This will cause the value 0xC8 (200 in decimal) to get printed.

Body:
I created a string converted got a  byte array using EBCDIC encoding from it. When I printed the array the value of H it is not the same found in EBCDIC chart.

Expected output

EBCDIC Value for "H"-->200 as per link EBCDIC 1047 chart

Actual output

EBCDIC Value for "H"-->[-56]

public static void main(String[] args) throws UnsupportedEncodingException {
    String str = "H";
    byte[] b1 = new byte[10];
    b1 = str.getBytes("Cp1047");
    System.out.println(Arrays.toString(b1));

    for (byte b : b1) {
        System.out.println(b);
    }

    b1 = str.getBytes("UTF-16");
    System.out.println(Arrays.toString(b1));

    b1 = str.getBytes();
    System.out.println(Arrays.toString(b1));
}

Body:
In your loop

for (byte b : b1)
   System.out.println(b);

Java is sign extending b (a byte) when it promotes it to an integer which results in the value of 0xFFFFFFC8 being printed.  0xFFFFFFC8 is the two's complement representation of the signed number -56.  See this. You can prevent the sign extension by doing this:

for (byte b  :b1)
  System.out.println(b & 0xFF);

This will cause the value 0xC8 (200 in decimal) to get printed.


问:
Google SDTT error: "All values provided for http://www.example.com/ must have the same domain."
When I copy/paste JSON-LD example from Google Documentation (code-snippet below) I get an error in the Structured Data Testing Tool:

http://www.your-company-site.com (All values provided for
  http://www.example.com/ must have the same domain.)

Why is Google's own documentation example giving an error?

Code snippet from Google’s documentation:

```

答:
If you change your URL to "https://search.google.com/structured-data/testing-tool/", the tool will drop the error, just make sure before you put the code on your website that you update it. </p>

<p>Also, checking Search Console is likely a more reliable way (currently) to see if your markup has an error. </p>

Body:
If you change your URL to "https://search.google.com/structured-data/testing-tool/", the tool will drop the error, just make sure before you put the code on your website that you update it.

Also, checking Search Console is likely a more reliable way (currently) to see if your markup has an error.


问:
passing objects to return results in an error
I expected the following code to return the lower and upper bounds of a 95% confidence interval:

```<code>confint95 = function(mean, se)
{
  confint = abs(se*1.96)
  lower = abs(mean-cint)
  upper = abs(mean+cint)
  return(lower,upper)
}
</code>```

But this gives this message:

Error in return(lower, upper) : multi-argument returns are not permitted

How can I set function to return the lower and upper bounds of a 95% confidence interval?

答:
to reurn two or more results, use "c"</p>

```<code>dummy <- function(){
  a <- 1
  b <- 22
  return(a,b)
}

dummy()

# Error in return(a, b) : multi-argument returns are not permitted

dummy2 <- function(){
  a <- 1
  b <- 22
  return(c(a,b))
}

dummy2()
# [1]  1 22
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I expected the following code to return the lower and upper bounds of a 95% confidence interval:

confint95 = function(mean, se)
{
  confint = abs(se*1.96)
  lower = abs(mean-cint)
  upper = abs(mean+cint)
  return(lower,upper)
}

But this gives this message:

Error in return(lower, upper) : multi-argument returns are not permitted

How can I set function to return the lower and upper bounds of a 95% confidence interval?

Body:
to reurn two or more results, use "c"

dummy <- function(){
  a <- 1
  b <- 22
  return(a,b)
}

dummy()

# Error in return(a, b) : multi-argument returns are not permitted

dummy2 <- function(){
  a <- 1
  b <- 22
  return(c(a,b))
}

dummy2()
# [1]  1 22


问:
Changing a file extension using rename in OS X
I have a lots of file names under a folder '/files' ,the extesnions of these files are appended with timestamp when that file was created,somthing like abc.csv_20170329. I want to change the extension of all these files to abc.csv_20170330 using the rename command in OSX using the terminal.Can any one help me with the exact command to do that i tried using
$ rename -S  '.csv_'  .csv_20170330  '.csv'

but this does not work.

答:
```<code> for file in abc.csv*
 do
    mv "$file" "$file__20170330"
 done
</code>```


问:
Used jdbc connections seem to be leaking and I cannot figure out why
I have been fighting with this issue for ages and I cannot for the life of me figure out what the problem is. Let me set the stage for the stack we are using:

Web-based Java 8 application

GWT

Hibernate 4.3.11

MySQL

MongoDB

Spring

Tomcat 8 (incl Tomcat connection pooling instead of C3PO, for example)

Hibernate Search / Lucene

Terracotta and EhCache

The problem is that every couple of days (sometimes every second day, sometimes once every 10 days, it varies) in the early hours of the morning, our application "locks up". To clarify, it does not crash, you just cannot log in or do anything for that matter. All background tasks - everything - just halt. If we attempt to login when it is in this state, we can see in our log file that it is authenticating us as a valid user, but no response is ever sent so the application just "spins".

The only pattern we have found to date related to when these "lock ups" occur is that it happens when our morning scheduled tasks or SAP imports are running. It is not always the same process that is running though, sometimes the lock up happens during one of our SAP imports and sometimes during internal scheduled task execution. All that these things have in common are that they run outside of business hours (between 1am and 6am) and that they are quite intensive processes.

We are using JavaMelody for monitoring and what we see every time is that starting at different times in this 1 - 6am window, the number of used jdbc connections just start to spike (as per the attached image). Once that starts, it is just a matter of time before the lock up occurs and the only way to solve it is to bounce Tomcat thereby restarting the application.

As for as I can tell, memory, CPU, etc, are all fine when the lock up occurs the only thing that looks like it has an issue is the constantly increasing number of used jdbc connections.

I have checked the code for our transaction management so many times to ensure that transactions are being closed off correctly (the transaction management code is quite old fashioned: explicit begin and commit in try block, rollback in catch blocks and entity manager close in a finally block). It all seems correct to me so I am really, really stumped. In addition to this, I have also recently explicitly configured the Hibernate connection release mode properly to after_transaction, but the issue still occurs.

The other weird thing is that we run several instances of the same application for different clients and this issue only happens regularly for one client. They are our client with by far the most data to be processed though and although all clients run these scheduled tasks, this big client is the only one with SAP imports. That is why I originally thought that the SAP imports were the issue, but it locked up just after 1am this morning and that was a couple hours before the imports even start running. In this case it locked up during an internal scheduled task executing.

Does anyone have any idea what could be causing this strange behavior? I have looked into everything I can think of but to no avail.

答:
After some time and a lot of trial and error, my team and I managed to sort out this issue. Turns out that the spike in JDBC connections was not the cause of the lock-ups but was instead a consequence of the lock-ups. Apache Terracotta was the culprit. It was just becoming unresponsive it seems. It might have been a resource allocation issue, but I don't think so since this was happening on servers that were low usage as well and they had more than enough resources available.

Fortunately we actually no longer needed Terracotta so I removed it. As I said in the question, we were getting these lock-ups every couples of days - at least once per week, every week. Since removing it we have had no such lock-ups for 4 months and counting. So if anyone else experiences the same issue and you are using Terracotta, try dropping it and things might come right, as they did in my case.


问:
How to process POST data in Node.js?
How do you extract form data (form[method="post"]) and file uploads sent from the HTTP POST method in Node.js?

I've read the documentation, googled and found nothing.

```<code>function (request, response) {
    //request.post????
}
</code>```

Is there a library or a hack?

答:
You can use the querystring module:

```<code>var qs = require('querystring');

function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;

            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            // use post['blah'], etc.
        });
    }
}
</code>```

Now, for example, if you have an input field with name age, you could access it using the variable post:

```<code>console.log(post.age);
</code>```

Title: How to process POST data in Node.js?

Body:
How do you extract form data (form[method="post"]) and file uploads sent from the HTTP POST method in Node.js?

I've read the documentation, googled and found nothing.

function (request, response) {
    //request.post????
}

Is there a library or a hack?

Body:
You can use the querystring module:

var qs = require('querystring');

function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;

            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            // use post['blah'], etc.
        });
    }
}

Now, for example, if you have an input field with name age, you could access it using the variable post:

console.log(post.age);


问:
Query times out when executed from web, but super-fast when executed from SSMS
I'm trying to debug the source of a SQL timeout in a web application that I maintain.  I have the source code of the C# code behind, so I know exactly what code is running.  I have debugged the application right down to the line that executes the SQL code that times out, and I watch the query running in SQL profiler.

When this query executes from the web, it times out after 30 seconds.  However, when I cut/paste the query exactly as presented in Profiler, and I put it into SSMS and run it, it returns almost instantly.  I have traced the problem to ARITHABORT being set to OFF in the connection that the web is using (that is, if I turn ARITHABORT OFF in the SSMS session, it runs for a long time, and if I turn it back ON then it runs very quickly).  However, reading the description of ARITHABORT, it doesn't seem to apply...   I'm only doing a simple SELECT, and there is NO arithmetic being performed at all..   just a single INNER JOIN with a WHERE condition:

Why would ARITHABORT OFF be causing this behavior in this context??  Is there any way I can alter the ARITHABORT setting for that connection from SSMS?  I'm using SQL Server 2008.

答:
I have the same problem when trying to call SP from SMSS it took 2 sec, while from the webapp (ASP.NET) it took about 3 min.

I've tried all suggested solutions sp_recompile, DBCC FREEPROCCACHE and  DBCC DROPCLEANBUFFERS but nothing fixed my problem, but when tried parameter sniffing it did the trick, and worked just fine.


问:
pandas regex match all items between two sets of white spaces
How can I match everything to include special characters between exactly 3 white spaces to the left and exactly 3 white spaces to the right of a colon? Example denoted with W as a white space.

Example match:

```<code>\\s\\s\\sdata\\sstuff:\\s\\sfound\\ssome([%$)Data\\sas\\swhiteSpace\\s\\s\\s
   data stuff:  found some([%$)Data as whiteSpace
</code>```

Example nonMatch:

```<code>\\s\\sdata\sstuff:\\s\\sfound\\sno\\sdatacause\\sno\\s3\\sspaces\\sbefore\\sor\\safter\\s\\s
  data stuff:  found no datacause no 3 spaces before or after
</code>```

The intent is to expand this to seperate columns from a single column of a pandas dataframe.

Expected output:

```<code>data stuff                                data stuff 2
found some([%$)Data as whiteSpace         if i had more examples for data stuff 2 it would show here
extra random data to add into a outputdf  if i had more examples for data stuff 2 it would show here
</code>```

Original thought was to use something like this but this doesnt quite work.

```<code>"(\\s\\s\\s(.*?)\\:\\s\\s(.*?)\\s\\s\\s)"
</code>```

答:
Consider this df

```<code>    col
0   data stuff:   found   some([%$)Data as whiteSpace   1
</code>```

Regex1:

```<code>df.col.str.extract(':\\s{3}(.*)\s{3}')
</code>```

would return

```<code>0    found   some([%$)Data as whiteSpace
Name: col, dtype: object
</code>```

That is the content between three white spaces before found and three white spaces at the end before 1.

Where as

```<code>df.col.str.extract(':\\s{3}(.*?)\s{3}') #note the ? after .*
</code>```

will return

```<code>0    found
Name: col, dtype: object
</code>```

That is the content between the first and second instances of three white spaces.

If you provide more test cases, it would become clear as to what else do you need the regex to do.

Body:
How can I match everything to include special characters between exactly 3 white spaces to the left and exactly 3 white spaces to the right of a colon? Example denoted with W as a white space.

Example match:

\\s\\s\\sdata\\sstuff:\\s\\sfound\\ssome([%$)Data\\sas\\swhiteSpace\\s\\s\\s
   data stuff:  found some([%$)Data as whiteSpace

Example nonMatch:

\\s\\sdata\sstuff:\\s\\sfound\\sno\\sdatacause\\sno\\s3\\sspaces\\sbefore\\sor\\safter\\s\\s
  data stuff:  found no datacause no 3 spaces before or after

The intent is to expand this to seperate columns from a single column of a pandas dataframe.

Expected output:

data stuff                                data stuff 2
found some([%$)Data as whiteSpace         if i had more examples for data stuff 2 it would show here
extra random data to add into a outputdf  if i had more examples for data stuff 2 it would show here

Original thought was to use something like this but this doesnt quite work.

"(\\s\\s\\s(.*?)\\:\\s\\s(.*?)\\s\\s\\s)"

Body:
Consider this df

    col
0   data stuff:   found   some([%$)Data as whiteSpace   1

Regex1:

df.col.str.extract(':\\s{3}(.*)\s{3}')

would return

0    found   some([%$)Data as whiteSpace
Name: col, dtype: object

That is the content between three white spaces before found and three white spaces at the end before 1.

Where as

df.col.str.extract(':\\s{3}(.*?)\s{3}') #note the ? after .*

will return

0    found
Name: col, dtype: object

That is the content between the first and second instances of three white spaces.

If you provide more test cases, it would become clear as to what else do you need the regex to do.