答:
```<code>echo Mage::getBaseUrl ();
</code>```

will return the Store url only i.e. abc.com/store1.

In order to get the Main store URL (domain name), use the following code

```<code>echo Mage::getBaseUrl (Mage_Core_Model_Store::URL_TYPE_WEB);
</code>```

OR

you can get the current domain by the $_SERVER['HTTP_HOST'];

Title: Magento - Fetch current domain and not base domain

Body:
We are running one Magento install over multiple domains and are using a script to fetch information from the database to help users filter the products.

In our coding we have the $_SERVER function calling the store which seems to be store 1 (which is on domain 1), I was wondering what I would need to change to fetch the information from store 2 (which is on domain 2).

Body:
echo Mage::getBaseUrl ();

will return the Store url only i.e. abc.com/store1.

In order to get the Main store URL (domain name), use the following code

echo Mage::getBaseUrl (Mage_Core_Model_Store::URL_TYPE_WEB);

OR

you can get the current domain by the $_SERVER['HTTP_HOST'];


来源: stackexchange

问:
invoking lambda with boto doesn't respect timeout
I'm invoking a lambda function with boto3, with:

```<code>import boto3
import json

client = boto3.client('lambda')
response = client.invoke(
            InvocationType='RequestResponse',
            FunctionName=test_lambda_arn,
            LogType='Tail',
            Payload=json.dumps(data)
)
</code>```

It's raising a botocore.vendored.requests.exceptions.ReadTimeout exception after 626 seconds. I have configured this lambda to time out after 100 seconds. I did so when I created it with boto. When I go into the AWS console it says that this lambda has a timeout of 1 minute and 40 seconds.

So why does the invoke command timeout after 626 seconds, and not after 100 seconds?

Is it because of retries? If so, how can I disable retries?

Edit: In the CloudWatch logs I can see multiple invocations for each client.invoke call. Therefore there is some automatic retry thing happening. Here are the docs for client.invoke.

答:
I posted this issue on the boto3 git repo. They're going to add an option to client.invoke to disable automatic retries.

In the meantime, here's a workaround.

ContentLicense: CC BY-SA 3.0

Body:
I'm invoking a lambda function with boto3, with:

import boto3
import json

client = boto3.client('lambda')
response = client.invoke(
            InvocationType='RequestResponse',
            FunctionName=test_lambda_arn,
            LogType='Tail',
            Payload=json.dumps(data)
)

It's raising a botocore.vendored.requests.exceptions.ReadTimeout exception after 626 seconds. I have configured this lambda to time out after 100 seconds. I did so when I created it with boto. When I go into the AWS console it says that this lambda has a timeout of 1 minute and 40 seconds.

So why does the invoke command timeout after 626 seconds, and not after 100 seconds?

Is it because of retries? If so, how can I disable retries?

Edit: In the CloudWatch logs I can see multiple invocations for each client.invoke call. Therefore there is some automatic retry thing happening. Here are the docs for client.invoke.


问:
jquery attribute. jquery js

$(".dum").click(function() {
    document.getElementById("ev").value=$(this).attr("data-name");

    $("#test-form").dialog("open");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>// this is just the test

cell2.innerHTML = '<span  class="dum" style="color:'+testvalues[i]+'; font-size:20px;">'+testvalues[i + 2] || ''+'data-name=" '+testvalues[i+2] +'">'+ '</span>';

<div id="test-form" title="Event Information">
 <p>Event:</p>
 <input id= "ev" type="text"  name="fullname" disabled />
</div></code>```

I have a  where I have values from db. And I am trying to get those value to a input box using jquery attr but I am getting undefined. The attr name is "data-name". I do not know what I am doing wrong here. I will be very thankful for any help.

答:
1st: you need to rewrite the span

2nd: you need Event binding on dynamically created elements?

This is an example

$(document).ready(function(){
  var testvalues = ['red','no','Click Me','name'],
      i = 1;
  $('#cell2').html(''+testvalues[i+1] +'');

  $(document).on('click' , ".dum" , function() {
    $("#ev").val($(this).data("name"));
    //$( "#test-form").dialog("open");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="cell2"></div>

<div id="test-form" title="Event Information">
  <p >Event:</p>
  <input id= "ev" type="text"  name="fullname" disabled />
</div></code>```

Note: I don't prefer mixing jquery with pure js so I used jquery

Title: jquery attribute. jquery js

Body:
$(".dum").click(function() {
    document.getElementById("ev").value=$(this).attr("data-name");

    $("#test-form").dialog("open");
});

// this is just the test

cell2.innerHTML = ''+testvalues[i + 2] || ''+'data-name=" '+testvalues[i+2] +'">'+ '';

Event:

 <input id= "ev" type="text"  name="fullname" disabled />

I have a  where I have values from db. And I am trying to get those value to a input box using jquery attr but I am getting undefined. The attr name is "data-name". I do not know what I am doing wrong here. I will be very thankful for any help.

Body:
1st: you need to rewrite the span

2nd: you need Event binding on dynamically created elements?

This is an example

$(document).ready(function(){
  var testvalues = ['red','no','Click Me','name'],
      i = 1;
  $('#cell2').html('<span  class="dum" style="color:'+testvalues[i]+'; font-size:20px;" data-name="'+testvalues[i+2] +'">'+testvalues[i+1] +'</span>');

  $(document).on('click' , ".dum" , function() {
    $("#ev").val($(this).data("name"));
    //$( "#test-form").dialog("open");
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="cell2"></div>

<div id="test-form" title="Event Information">
  <p >Event:</p>
  <input id= "ev" type="text"  name="fullname" disabled />
</div>

Note: I don't prefer mixing jquery with pure js so I used jquery


问:
How to Combine Multiple Tableau Columns
Let's say I have two columns in the data called
        Functionality_First_Question and Functionality_Second_Question

Both columns have similar values
        "approve", "functionality unclear", "functionality broken", NULL, etc.

Each row corresponds with a single, distinct review ID.

I thought about using Tableau combined fields to aggregate the data but will it end up turning into "functionality unclear, functionality broken".

I instead want just a distinct count of how many review IDs are associated with each answer to each question.

Let me know if this is unclear!

答:
Depending on your data source, you can pivot the data in the data source tab:

highlight your First_Question, Second_Question, Nth_Question columns

right click

Pivot data

Now you have several records for each item (one record for each question) and you will be able to group all items by answer.

If this is not possible with your data source, one crude workaround would be:

Create a parameter Answer_param with the different possible answers

Create a calculated field that has a formula like

CONTAINS([First_Question], Answer_param) OR CONTAINS([Second_Question], Answer_param) OR ..

This will create a field that is True, if one of the answers contains the selected answer from your parameter.

Title: How to Combine Multiple Tableau Columns


问:
XHTML to Structured XML with XSLT 1.0
I have an XHTML document from a basic ePub output that I'm trying to convert into a structured XML document. The format of it shouldn't be too crazy in general and looks like the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<html>
<body>
  <h1>Topic 1</h1>
  <p>1.0.1</p>
  <p>1.0.2</p>

  <h2>Subtopic 1.1</h2>
  <p>1.1.1</p>
  <p>1.1.2</p>

  <h2>Subtopic 1.2</h2>
  <p>1.2.1</p>
  <p>1.2.2</p>

  <h1>Topic 2</h1>
  <p>2.0.1</p>
  <p>2.0.2</p>

  <h2>Subtopic 2.1</h2>
  <p>2.1.1</p>
  <p>2.1.2</p>

  <h2>Subtopic 2.2</h2>
  <p>2.2.1</p>
  <p>2.2.2</p>
</body>
</html>
</code>```

Ideally, I'd like to convert this into some structured code, based on the h1, h2, ... tags. The stuff after the first h1, but before the second should be contained inside its own container, and the stuff in the second h1 to the end of the document inside its own. Likewise, the stuff between h2's should also go into a container, thereby nesting it. The output should be something like this:

```<code><Root>
   <Topic>
      <Title>Topic 1</Title>
      <Paragraph>1.0.1</Paragraph>
      <Paragraph>1.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 1.1</Title>
         <Paragraph>1.1.1</Paragraph>
         <Paragraph>1.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 1.2</Title>
         <Paragraph>1.2.1</Paragraph>
         <Paragraph>1.2.2</Paragraph>
      </Topic>
   </Topic>
   <Topic>
      <Title>Topic 2</Title>
      <Paragraph>2.0.1</Paragraph>
      <Paragraph>2.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 2.1</Title>
         <Paragraph>2.1.1</Paragraph>
         <Paragraph>2.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 2.2</Title>
         <Paragraph>2.2.1</Paragraph>
         <Paragraph>2.2.2</Paragraph>
      </Topic>
   </Topic>
</Root>
</code>```

Even though the example only consists of p tags, it may also contain div's, and other elements, so don't count on it being just one node. It needs to be generic enough to not care what's between the header tags.

I'm familiar with Muenchian grouping, but this is a bit complex of a situation for me. I've tried using keys like this:

```<code><xsl:key name="kHeaders1" match="*[not(self::h1)]" use="generate-id(preceding-sibling::h1[1])"/>

<xsl:template match="h1">
  <Topic>
    <Title><xsl:apply-templates /></Title>
    <xsl:apply-templates select="key('kHeaders1', generate-id())" />
  </Topic>
</xsl:template>

<xsl:template match="html">
  <Root>
     <xsl:apply-templates select="body/h1" />
  </Root>
</xsl:template>

<xsl:template match="p">
   <Paragraph><xsl:apply-templates /></Paragraph>
</xsl:template>
</code>```

This works well enough for the first level, but then trying to repeat the process, but using h2, seems to break my mind. Since at the h2 level, the key for any node should be the first, h1 or h2 sibling. It almost seems like it could be combined into a single set of keys, where the id is whatever the last h* was that came before it, and where the h* elements are not listed in the grouping (so that they don't recurse). I would imagine something like:

```<code><xsl:key name="kHeaders" match="*[not(self::h1 or self::h2)]" use="generate-id(preceding-sibling::*[self::h1 or self::h2][1])"/>
</code>```

However, that leaves out the h2 elements from the list, which need to be present in the grouping for the previous h1. And if I relax the restrictions on the match to include the h1/h2 elements (and make the h1 templates also match h2), then I get the h2's re-listing the h1's and so on (somewhat expected).

An ideal solution is one that can be extended to work for h3, h4, and so on without a lot of effort. However, it does not need to include script elements for handling the generic h* elements. Simple instructions for how to add an additional layer would be sufficient.

Does anyone have some advice here?

答:
This will do the trick:</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <Root>
      <xsl:apply-templates select="//h1"/>
    </Root>
  </xsl:template>

  <xsl:template match="*[starts-with(local-name(), 'h')]">
    <xsl:variable name="lvl" select="number(substring-after(local-name(), 'h'))"/>
    <Topic>
      <Title>
        <xsl:value-of select="text()"/>
      </Title>
      <xsl:apply-templates select="//following-sibling::*[not(starts-with(local-name(), 'h'))
                           and preceding-sibling::*[starts-with(local-name(), 'h')][1] = current()]"/>
      <xsl:apply-templates select="//following-sibling::*[local-name() = concat('h', $lvl + 1)
                           and preceding-sibling::*[local-name() = concat('h', $lvl)][1] = current()]"/>
    </Topic>
  </xsl:template>

  <xsl:template match="*">
    <Paragraph>
      <xsl:value-of select="text()"/>
    </Paragraph>
  </xsl:template>
</xsl:stylesheet>
</code>```

Title: XHTML to Structured XML with XSLT 1.0

Body:
I have an XHTML document from a basic ePub output that I'm trying to convert into a structured XML document. The format of it shouldn't be too crazy in general and looks like the following:

<?xml version="1.0" encoding="utf-8"?>

Topic 1

1.0.1

1.0.2

Subtopic 1.1

1.1.1

1.1.2

Subtopic 1.2

1.2.1

1.2.2

Topic 2

2.0.1

2.0.2

Subtopic 2.1

2.1.1

2.1.2

Subtopic 2.2

2.2.1

2.2.2

Ideally, I'd like to convert this into some structured code, based on the h1, h2, ... tags. The stuff after the first h1, but before the second should be contained inside its own container, and the stuff in the second h1 to the end of the document inside its own. Likewise, the stuff between h2's should also go into a container, thereby nesting it. The output should be something like this:

<Root>
   <Topic>
      <Title>Topic 1</Title>
      <Paragraph>1.0.1</Paragraph>
      <Paragraph>1.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 1.1</Title>
         <Paragraph>1.1.1</Paragraph>
         <Paragraph>1.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 1.2</Title>
         <Paragraph>1.2.1</Paragraph>
         <Paragraph>1.2.2</Paragraph>
      </Topic>
   </Topic>
   <Topic>
      <Title>Topic 2</Title>
      <Paragraph>2.0.1</Paragraph>
      <Paragraph>2.0.2</Paragraph>
      <Topic>
         <Title>Subtopic 2.1</Title>
         <Paragraph>2.1.1</Paragraph>
         <Paragraph>2.1.2</Paragraph>
      </Topic>
      <Topic>
         <Title>Subtopic 2.2</Title>
         <Paragraph>2.2.1</Paragraph>
         <Paragraph>2.2.2</Paragraph>
      </Topic>
   </Topic>
</Root>

Even though the example only consists of p tags, it may also contain div's, and other elements, so don't count on it being just one node. It needs to be generic enough to not care what's between the header tags.

I'm familiar with Muenchian grouping, but this is a bit complex of a situation for me. I've tried using keys like this:

<xsl:key name="kHeaders1" match="*[not(self::h1)]" use="generate-id(preceding-sibling::h1[1])"/>

<xsl:template match="h1">
  <Topic>
    <Title><xsl:apply-templates /></Title>
    <xsl:apply-templates select="key('kHeaders1', generate-id())" />
  </Topic>
</xsl:template>

<xsl:template match="html">
  <Root>
     <xsl:apply-templates select="body/h1" />
  </Root>
</xsl:template>

<xsl:template match="p">
   <Paragraph><xsl:apply-templates /></Paragraph>
</xsl:template>

This works well enough for the first level, but then trying to repeat the process, but using h2, seems to break my mind. Since at the h2 level, the key for any node should be the first, h1 or h2 sibling. It almost seems like it could be combined into a single set of keys, where the id is whatever the last h* was that came before it, and where the h* elements are not listed in the grouping (so that they don't recurse). I would imagine something like:

<xsl:key name="kHeaders" match="*[not(self::h1 or self::h2)]" use="generate-id(preceding-sibling::*[self::h1 or self::h2][1])"/>

However, that leaves out the h2 elements from the list, which need to be present in the grouping for the previous h1. And if I relax the restrictions on the match to include the h1/h2 elements (and make the h1 templates also match h2), then I get the h2's re-listing the h1's and so on (somewhat expected).

An ideal solution is one that can be extended to work for h3, h4, and so on without a lot of effort. However, it does not need to include script elements for handling the generic h* elements. Simple instructions for how to add an additional layer would be sufficient.

Does anyone have some advice here?

Body:
This will do the trick:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/">
    <Root>
      <xsl:apply-templates select="//h1"/>
    </Root>
  </xsl:template>

  <xsl:template match="*[starts-with(local-name(), 'h')]">
    <xsl:variable name="lvl" select="number(substring-after(local-name(), 'h'))"/>
    <Topic>
      <Title>
        <xsl:value-of select="text()"/>
      </Title>
      <xsl:apply-templates select="//following-sibling::*[not(starts-with(local-name(), 'h'))
                           and preceding-sibling::*[starts-with(local-name(), 'h')][1] = current()]"/>
      <xsl:apply-templates select="//following-sibling::*[local-name() = concat('h', $lvl + 1)
                           and preceding-sibling::*[local-name() = concat('h', $lvl)][1] = current()]"/>
    </Topic>
  </xsl:template>

  <xsl:template match="*">
    <Paragraph>
      <xsl:value-of select="text()"/>
    </Paragraph>
  </xsl:template>
</xsl:stylesheet>


问:
Export selenium / junit test base using maven
I am working on a Selenium test base that will eventually be exported, and run on a specific machine.

The target machine has only a JRE, and no JDK.

How can I export my test base to be able to run the JUnit test classes on this target machine, without having a JDK available?

If I try running, from my local machine,

```<code>mvn package
</code>```

All the selenium tests are executed locally, and the package jar only contains src files, nothing from test.

Is it possible to package the existing maven project as a runnable jar while keeping the Test classes intact?

答: To compile your application's test code use compiler:testCompile as described here

Body:
I am working on a Selenium test base that will eventually be exported, and run on a specific machine.

The target machine has only a JRE, and no JDK.

How can I export my test base to be able to run the JUnit test classes on this target machine, without having a JDK available?

If I try running, from my local machine,

mvn package

All the selenium tests are executed locally, and the package jar only contains src files, nothing from test.

Is it possible to package the existing maven project as a runnable jar while keeping the Test classes intact?


问:
kubernetes cluster on CentOS Atomic Hosts
The CentOS Atomic Host is shipped without the kubernetes-master package built into the image. Instead, you need to run the master kubernetes components (apiserver, scheduler, and controller-manager) in containers, managed via systemd, using the service files. Do you have any good tutorials on how to form a kubernetes cluster of atomic hosts? the tutorials and the documentations I have seen so far was done on fedora atomic and centOS 7. </p>

答:
You can try Kubernetes the Hard Way on Github:

https://github.com/kelseyhightower/kubernetes-the-hard-way


问:
Oracle Subquery - How to?
I have 2 tables that look like:

```<code>GL_ROLLUP
Responsibility    Responsibility_L3
15500             15B
15445             15C
15515             15B
15494             15C
15600             15D

GL_Detail
Responsibility    Expense      Amount
15500             6501         30.51
15445             6508         75.60
15515             6535         45.68
15494             6508         65.50
15600             6505         84.39
</code>```

My query right now is pulling the data from the GL_Detail table; however what I want to be able to due is use the search parameter Responsibility_L3 found in GL_ROLLUP so I can query all Responsibilities within this rolled up value (instead of doing a range or a " = '15500' or....."). I tried doing this a few times, but my query seems to get stuck and never brings data back.

Any help would be greatly appreciated!

答:
```<code>SELECT d.Responsibility, r.Responsibility_L3, d.Expense, d.Amount
FROM GL_Detail d LEFT JOIN GL_ROLLUP r ON r.Responsibility = d.Responsibility
ORDER BY Responsibility_L3
</code>```

Does that get you what you are looking for?

Title: Oracle Subquery - How to?

Body:
I have 2 tables that look like:

GL_ROLLUP
Responsibility    Responsibility_L3
15500             15B
15445             15C
15515             15B
15494             15C
15600             15D

GL_Detail
Responsibility    Expense      Amount
15500             6501         30.51
15445             6508         75.60
15515             6535         45.68
15494             6508         65.50
15600             6505         84.39

My query right now is pulling the data from the GL_Detail table; however what I want to be able to due is use the search parameter Responsibility_L3 found in GL_ROLLUP so I can query all Responsibilities within this rolled up value (instead of doing a range or a " = '15500' or....."). I tried doing this a few times, but my query seems to get stuck and never brings data back.

Any help would be greatly appreciated!

Body:
SELECT d.Responsibility, r.Responsibility_L3, d.Expense, d.Amount
FROM GL_Detail d LEFT JOIN GL_ROLLUP r ON r.Responsibility = d.Responsibility
ORDER BY Responsibility_L3

Does that get you what you are looking for?


问:
Code to delete rows for a table not working Javascript / HTML
I have a problem with the following code. I am trying remove rows from a table if that row does not contain the meat in the td. To clarify, when the function is called, it takes in 2. (Which is where the word meat can be found in the table)
Some of the rows do not contain the word meat, x = rows[i].getElementsByTagName("td")[a]; The word meat can be found in [a] of the row. I think the problem is with x.innerHTML, as I don't think it returns a value to compare to b.
Any help or leads are appreciated. Right now when the button is clicked to call the function, nothing happens.

```<code>function clearTable(a) {
            var table, rows, switching, i, x, c, shouldSwitch;
            table = document.getElementById("Invtable");
            switching = true;
            var b = "meat";

            while (switching){

                switching = false;
                rows = table.getElementsByTagName("tr");

                for (i = 0; i < (rows.length); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("td")[a];

                    if(x.innerHTML.toLowerCase() !=  b){

                        shouldSwitch= true;
                        break;
                    }
                }
                if (shouldSwitch) {
                    table.deleteRow(i);
                    switching = true;
                }
            }
        }

 var table = "<tr>";
for (var i = 0; i < array.length; i++) {
    table += "<tr>";
    for (var j = 0; j < array[i].length; j++) {
        if (j == 6) {
            table += "<td> <img src='CSV_Photos/" + array[i][j] + "' style ='width:250px;height:250px'>" + "<br>" //every 6th column is a picture
            + "<center> " + '<button id="btn" onClick="clickMe(\''+ array[i][1] + ',' + array[i][5] + '\')"> Buy / Add To Cart </button> </td>' + "</center>"; //button onclick takes (name+price)
        } else {
            table += "<td>" + array[i][j] + "</td>";
        }
    }
  table += "</tr>";
}
</code>```

Edit: Starting from the var table, that's how the table was made in javascript in a function.

The table code in html looks like this :

```<code><tr><td>1000</td><td>Chicken</td><td>Meat</td><td>Perfect</td><td>Yes</td><td>$2.99</td><td>image</td> </tr>
</code>```

答:
The problem is you are passing the incorrect column number as the argument. You only have two td per row and the index starts at 0. So you have to pass 1 as your argument: clearTable(1).

I created a simple table so you can see your function works with the correct argument.

EDIT

I recreated my table to have 6 columns and I created a button that runs the function onClick.

var table = '

Food	chicken	Veggies	Ceral	Soda	Water

Food	water	Soda	Meat	Water	Ceral

Third-Food	Meat	Chicken	Ceral	Water	Soda

';
var btn = '<button onClick="clearTable(1)">Meat</button>';
document.body.innerHTML = table + btn;

//clearTable(1);

function clearTable(a) {
            var table, rows, switching, i, x, c, shouldSwitch;
            table = document.getElementById("Invtable");
            switching = true;
            var b = "meat";

            while (switching){

                switching = false;
                rows = table.getElementsByTagName("tr");
        console.log(rows);
                for (i = 0; i < (rows.length); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("td")[a];

                    if(x.innerHTML.toLowerCase() !=  b){

                        shouldSwitch= true;
                        break;
                    }
                }
                if (shouldSwitch) {
                    table.deleteRow(i);
                    switching = true;
                }
            }
        }```

Body:
I have a problem with the following code. I am trying remove rows from a table if that row does not contain the meat in the td. To clarify, when the function is called, it takes in 2. (Which is where the word meat can be found in the table)
Some of the rows do not contain the word meat, x = rows[i].getElementsByTagName("td")[a]; The word meat can be found in [a] of the row. I think the problem is with x.innerHTML, as I don't think it returns a value to compare to b.
Any help or leads are appreciated. Right now when the button is clicked to call the function, nothing happens.

function clearTable(a) {
            var table, rows, switching, i, x, c, shouldSwitch;
            table = document.getElementById("Invtable");
            switching = true;
            var b = "meat";

            while (switching){

                switching = false;
                rows = table.getElementsByTagName("tr");

                for (i = 0; i < (rows.length); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("td")[a];

                    if(x.innerHTML.toLowerCase() !=  b){

                        shouldSwitch= true;
                        break;
                    }
                }
                if (shouldSwitch) {
                    table.deleteRow(i);
                    switching = true;
                }
            }
        }

 var table = "
";
for (var i = 0; i < array.length; i++) {
    table += "
";
    for (var j = 0; j < array[i].length; j++) {
        if (j == 6) {
            table += " " + "
" //every 6th column is a picture
            + " " + '<button id="btn" onClick="clickMe(\''+ array[i][1] + ',' + array[i][5] + '\')"> Buy / Add To Cart </button> 	' + ""; //button onclick takes (name+price)
        } else {
            table += "" + array[i][j] + "	";
        }
    }
  table += "
";
}

Edit: Starting from the var table, that's how the table was made in javascript in a function.

The table code in html looks like this :

1000	Chicken	Meat	Perfect	Yes	$2.99	image

Body:
The problem is you are passing the incorrect column number as the argument. You only have two td per row and the index starts at 0. So you have to pass 1 as your argument: clearTable(1).

I created a simple table so you can see your function works with the correct argument.

EDIT

I recreated my table to have 6 columns and I created a button that runs the function onClick.

var table = '<table id="Invtable"><tr><td>Food</td><td>chicken</td><td>Veggies</td><td>Ceral</td><td>Soda</td><td>Water</td></tr><tr><td>Food</td><td>water</td><td>Soda</td><td>Meat</td><td>Water</td><td>Ceral</td></tr><tr><td>Third-Food</td><td>Meat</td><td>Chicken</td><td>Ceral</td><td>Water</td><td>Soda</td></tr></table>';
var btn = '<button onClick="clearTable(1)">Meat</button>';
document.body.innerHTML = table + btn;

//clearTable(1);

function clearTable(a) {
            var table, rows, switching, i, x, c, shouldSwitch;
            table = document.getElementById("Invtable");
            switching = true;
            var b = "meat";

            while (switching){

                switching = false;
                rows = table.getElementsByTagName("tr");
        console.log(rows);
                for (i = 0; i < (rows.length); i++) {
                    shouldSwitch = false;
                    x = rows[i].getElementsByTagName("td")[a];

                    if(x.innerHTML.toLowerCase() !=  b){

                        shouldSwitch= true;
                        break;
                    }
                }
                if (shouldSwitch) {
                    table.deleteRow(i);
                    switching = true;
                }
            }
        }


问:
Getting the date format in VBA in the correct form
I am trying to reference a file that has the date of the previous Friday at the end in the form of mm.dd.yy.

I need to now take that date and add it to the end of a string, to end of a string in order to open select the other workbook. This is what I have right now.

File Name:
Submittals Wk Ending 06.02.17.xlsx

This is what I have so far

```<code>Dim wrbk As String
Dim weekdate As String

range("a1").value="=TODAY()-WEEKDAY(TODAY())-1"
weekdate = Range("a1").Value
'range("b1").value="06.02.17"
'weekdate = Range("b1").Value

msgbox weekdate 'use to check what the date format is

wrbk = "Submittals Wk Ending " & weekdate

Windows(wrbk & ".xlsx").Activate
</code>```

When I read it from B2 with the typed in format of 06.02.17 it works, however no matter what I do, I cannot get it to read it from A1 because it changes the format to m/d/yyyy. I have tried to copy it and paste as value. Nothing seems to work.

I have the other workbook open as well when I try to run it.

Any ideas? Thanks!

答:
Try</p>

```<code>Range("A1").Value = Format$(Date - Weekday(Date) - 1, "MM.DD.YY")
</code>```

Body:
I am trying to reference a file that has the date of the previous Friday at the end in the form of mm.dd.yy.

I need to now take that date and add it to the end of a string, to end of a string in order to open select the other workbook. This is what I have right now.

File Name:
Submittals Wk Ending 06.02.17.xlsx

This is what I have so far

Dim wrbk As String
Dim weekdate As String

range("a1").value="=TODAY()-WEEKDAY(TODAY())-1"
weekdate = Range("a1").Value
'range("b1").value="06.02.17"
'weekdate = Range("b1").Value

msgbox weekdate 'use to check what the date format is

wrbk = "Submittals Wk Ending " & weekdate

Windows(wrbk & ".xlsx").Activate

When I read it from B2 with the typed in format of 06.02.17 it works, however no matter what I do, I cannot get it to read it from A1 because it changes the format to m/d/yyyy. I have tried to copy it and paste as value. Nothing seems to work.

I have the other workbook open as well when I try to run it.

Any ideas? Thanks!

Body:
Try

Range("A1").Value = Format$(Date - Weekday(Date) - 1, "MM.DD.YY")


问:
Microsoft.Data.Entity.Design, Visual Studio 2013 - error adding ADO.NET
I have this error while trying to add ADO.NET Entity Data Model. I'm targeting .NET 4.5.1, use Visual Studio 2013 and Windows 8.1. I tried reinstalling nuget, VS, frameworks and also this method. Nothing works : / Anyone having the same issue?

答: Solved: I changed the framework version, repaired, installed updates, copied the entity framework folder from other PC and nothing happened, eventually i run the setup and added the SQL components (Entity Framework Designer) and is fixed now.</p>


问:
How to get higher quality images from eBay API
I am currently working in Django and getting some data from eBay API. The API gives me image URL, but the problem is that the quality of image is 70px, which is low.

Is there any method where I can get image of higher quality? I need images with minimum 200px. eBay has higher quality images (same image with high quality which they gives in their API).

I am using getTopSellingProducts call to retrieve them.

Does anyone have a solution for this problem?
Thanks in advance.

答:
Sorry to break the bad news, but from eBay API getTopSellingProducts documentation:

Fully qualified URL for a stock image (if any) associated with the
  eBay catalog product. The URL is for the image eBay usually displays
  in product search results (usually 70px tall). It may be helpful
  to calculate the dimensions of the photo programmatically before
  displaying it. Only returned if a URL is available for the product.

ContentLicense: CC BY-SA 4.0


问:
Json conversion in ASP.NET for CQRS
I'm trying to overcome a problem with command handling, there are easier ways using flags and enums, but if I can make a magical class that stops coupling I want it.

Basically I have a simple class:

```<code>public class ServiceProperty<T>
{
    public T Value { get; set; }
}
</code>```

And all I want is to map the data simply. The reason behind this class is that we want the "update" command to be flexible (e.g. the client can update one attribute without being forced to send everything, risking reverting a change to another field that may have occurred during the process due to timing).

The problem is that null is acceptable for some fields, so we can't rely on nullable, we need a class that has the value (which can be null) and if the property is not included at all we then know they don't wish to update it.

the problem is the resulting JSON required (in this example we are updating the string "description"):

```<code>{
  "description": { "value": "lol" }
}
</code>```

I wish to change the required JSON to the following:

```<code>{
  "description": "lol"
}
</code>```

and use converters to go between. I've built the converter:

```<code>public class ServicePropertyConverter<T> : JsonConverter where T : class
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var str = reader.Value.ToString();

        return new ServiceProperty<T> { Value = string.IsNullOrEmpty(str) ? null : (T)JsonConvert.DeserializeObject(reader.Value.ToString(), typeof(T)) };
    }
    ... (other methods here)...
}
</code>```

So that should work fine, however swagger still asks for the first JSON example.

I've tried the following:

```<code>services.AddMvc(o =>
        {
            ...(Unimportant code here)...
        }).AddJsonOptions(x =>
        {
            x.SerializerSettings.ContractResolver = new ServicePropertyContractResolver();
            x.SerializerSettings.Converters.Add(new ServicePropertyConverter<string>());
        });
</code>```

The string implementation may seem silly, but it's just a first step to get the description example working, then I'll work on everything else, but it didn't work. As you can see I also created a custom 'ContractResolver':

```<code>    protected override JsonConverter ResolveContractConverter(Type objectType)
    {
        if (objectType == null || !objectType.IsAssignableFrom(typeof(ServiceProperty<>)))
        {
            return base.ResolveContractConverter(objectType);
        }

        return new ServicePropertyConverter<string>();
    }
</code>```

But this didn't make any difference either. At this point I'm a little desperate, I don't want to waste any more time, so if there isn't a simple solution I'll go back to the boilerplate solution and give up on this more elegant approach.

Any help is greatly appreciated - I am new to ASP.NET, so I'm learning as I go.

答:
What you want to do is to create a single converter ServicePropertyConverter that works for all ServiceProperty<T> for all T.  This is fairly simple to do with the following modifications to your type:

```<code>public abstract class ServicePropertyBase
{
    public abstract object GetValue();
}

// Possibly this class should be sealed.
public class ServiceProperty<T> : ServicePropertyBase
{
    public ServiceProperty() { }

    public ServiceProperty(T value) { this.Value = value; }

    public T Value { get; set; }

    public override object GetValue()
    {
        return Value;
    }
}
</code>```

Notice that:

There is an abstract base type that returns the value as an object.  The presence of this base type makes WriteJson() simpler.

The generic type now has both parameterized and parameterless constructors.  The presence of the parameterized constructor makes ReadJson() simpler.

Then, create the following converter:

```<code>public class ServicePropertyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.GetServicePropertyValueType() != null;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var valueType = objectType.GetServicePropertyValueType();
        var value = serializer.Deserialize(reader, valueType);
        // Use the parameterized constructor.
        return Activator.CreateInstance(objectType, value);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var baseValue = (ServicePropertyBase)value;
        serializer.Serialize(writer, baseValue.GetValue());
    }
}

internal static class ServicePropertyExtensions
{
    public static Type GetServicePropertyValueType(this Type objectType)
    {
        if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(ServiceProperty<>))
        {
            return objectType.GetGenericArguments()[0];
        }
        return null;
    }
}
</code>```

And, serialize and deserialize with the following settings:

```<code>var settings = new JsonSerializerSettings
{
    Converters = { new ServicePropertyConverter() },
    //NullValueHandling.Ignore cannot be used because ServicePropertyConverter.ReadJson()
    //will not get called during reading to allocate an empty ServiceProperty<T>.
    //NullValueHandling = NullValueHandling.Ignore,

    //Instead DefaultValueHandling.IgnoreAndPopulate must be used to skip serialization
    //of a null ServiceProperty<T> when serializing but force ServicePropertyConverter.ReadJson()
    //to be called when deserializing.
    DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
};
</code>```

Note the use of DefaultValueHandling.IgnoreAndPopulate.  Using this setting ensures that a property with a null value for a ServiceProperty<T> is completely skipped when serializing, but populated during deserialization when present.  (If NullValueHandling.Ignore were used instead, ServicePropertyConverter.ReadJson() would not get not called when a null value is encountered, breaking your design.)

If you cannot set DefaultValueHandling in settings, you could set it via a custom contract resolver:

```<code>public class ServicePropertyContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        if (property.DefaultValueHandling == null && property.PropertyType.GetServicePropertyValueType() != null)
        {
            property.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
        }

        return property;
    }
}
</code>```

And with settings:

```<code>var settings = new JsonSerializerSettings
{
    Converters = { new ServicePropertyConverter() },
    ContractResolver = new ServicePropertyContractResolver(),
};
</code>```

You may want to cache the contract resolver for best performance.

Sample fiddle.

Title: Json conversion in ASP.NET for CQRS

Body:
I'm trying to overcome a problem with command handling, there are easier ways using flags and enums, but if I can make a magical class that stops coupling I want it.

Basically I have a simple class:

public class ServiceProperty<T>
{
    public T Value { get; set; }
}

And all I want is to map the data simply. The reason behind this class is that we want the "update" command to be flexible (e.g. the client can update one attribute without being forced to send everything, risking reverting a change to another field that may have occurred during the process due to timing).

The problem is that null is acceptable for some fields, so we can't rely on nullable, we need a class that has the value (which can be null) and if the property is not included at all we then know they don't wish to update it.

the problem is the resulting JSON required (in this example we are updating the string "description"):

{
  "description": { "value": "lol" }
}

I wish to change the required JSON to the following:

{
  "description": "lol"
}

and use converters to go between. I've built the converter:

public class ServicePropertyConverter<T> : JsonConverter where T : class
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var str = reader.Value.ToString();

        return new ServiceProperty<T> { Value = string.IsNullOrEmpty(str) ? null : (T)JsonConvert.DeserializeObject(reader.Value.ToString(), typeof(T)) };
    }
    ... (other methods here)...
}

So that should work fine, however swagger still asks for the first JSON example.

I've tried the following:

services.AddMvc(o =>
        {
            ...(Unimportant code here)...
        }).AddJsonOptions(x =>
        {
            x.SerializerSettings.ContractResolver = new ServicePropertyContractResolver();
            x.SerializerSettings.Converters.Add(new ServicePropertyConverter<string>());
        });

The string implementation may seem silly, but it's just a first step to get the description example working, then I'll work on everything else, but it didn't work. As you can see I also created a custom 'ContractResolver':

    protected override JsonConverter ResolveContractConverter(Type objectType)
    {
        if (objectType == null || !objectType.IsAssignableFrom(typeof(ServiceProperty<>)))
        {
            return base.ResolveContractConverter(objectType);
        }

        return new ServicePropertyConverter<string>();
    }

But this didn't make any difference either. At this point I'm a little desperate, I don't want to waste any more time, so if there isn't a simple solution I'll go back to the boilerplate solution and give up on this more elegant approach.

Any help is greatly appreciated - I am new to ASP.NET, so I'm learning as I go.

Body:
What you want to do is to create a single converter ServicePropertyConverter that works for all ServiceProperty<T> for all T.  This is fairly simple to do with the following modifications to your type:

public abstract class ServicePropertyBase
{
    public abstract object GetValue();
}

// Possibly this class should be sealed.
public class ServiceProperty<T> : ServicePropertyBase
{
    public ServiceProperty() { }

    public ServiceProperty(T value) { this.Value = value; }

    public T Value { get; set; }

    public override object GetValue()
    {
        return Value;
    }
}

Notice that:

There is an abstract base type that returns the value as an object.  The presence of this base type makes WriteJson() simpler.

The generic type now has both parameterized and parameterless constructors.  The presence of the parameterized constructor makes ReadJson() simpler.

Then, create the following converter:

public class ServicePropertyConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.GetServicePropertyValueType() != null;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var valueType = objectType.GetServicePropertyValueType();
        var value = serializer.Deserialize(reader, valueType);
        // Use the parameterized constructor.
        return Activator.CreateInstance(objectType, value);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var baseValue = (ServicePropertyBase)value;
        serializer.Serialize(writer, baseValue.GetValue());
    }
}

internal static class ServicePropertyExtensions
{
    public static Type GetServicePropertyValueType(this Type objectType)
    {
        if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(ServiceProperty<>))
        {
            return objectType.GetGenericArguments()[0];
        }
        return null;
    }
}

And, serialize and deserialize with the following settings:

var settings = new JsonSerializerSettings
{
    Converters = { new ServicePropertyConverter() },
    //NullValueHandling.Ignore cannot be used because ServicePropertyConverter.ReadJson()
    //will not get called during reading to allocate an empty ServiceProperty<T>.
    //NullValueHandling = NullValueHandling.Ignore,

    //Instead DefaultValueHandling.IgnoreAndPopulate must be used to skip serialization
    //of a null ServiceProperty<T> when serializing but force ServicePropertyConverter.ReadJson()
    //to be called when deserializing.
    DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
};

Note the use of DefaultValueHandling.IgnoreAndPopulate.  Using this setting ensures that a property with a null value for a ServiceProperty<T> is completely skipped when serializing, but populated during deserialization when present.  (If NullValueHandling.Ignore were used instead, ServicePropertyConverter.ReadJson() would not get not called when a null value is encountered, breaking your design.)

If you cannot set DefaultValueHandling in settings, you could set it via a custom contract resolver:

public class ServicePropertyContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        if (property.DefaultValueHandling == null && property.PropertyType.GetServicePropertyValueType() != null)
        {
            property.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
        }

        return property;
    }
}

And with settings:

var settings = new JsonSerializerSettings
{
    Converters = { new ServicePropertyConverter() },
    ContractResolver = new ServicePropertyContractResolver(),
};

You may want to cache the contract resolver for best performance.

Sample fiddle.


问:
Faster Scramble Millions Numbers
I need to scramble HUGE integer arrays (from 1,000,000 to 80,000,000 elements).

These arrays are sequential created (1 to n step 1) and I need to ensure that no one sequential number is lost - and because of it I cannot create "random numbers" arrays.

So, I create them using a single FOR-NEXT (it takes very low time, about 2ms) and I utilize the Fisher-Yates-Durnstenfeld shuffle algorithm, as follows.

First I create the array:

```<code> dim Huge(0 to 80,000,000) as Integer
 For x as integer = 1 to 79,999,999
     Huge(x) = x
 Next
</code>```

It takes really few miliseconds to be created...

After, I scramble the numbers:

```<code>    Shuffle(Huge)
</code>```

where Shuffle is a routine called in a Parallel/Multitasking environment. Because of this, I need to LOCK the RANDOM function (to provide good entropy in swaping values and locations) utilized in Fisher-Yates-Durstenfeld routine :

The Fisher-Yates Shuffle

Friend Sub Shuffle(ByRef Buffer As Integer())
  For max As Integer = Buffer.Length - 1 To 1 Step -1
      ExtractRandomItem(Buffer, max)
  Next
End Sub

Friend Sub ExtractRandomItem(ByRef buffer As Integer(), max As Integer)
  Dim random As Integer = GetRandomNumber(max + 1)
  If random = max Then
     random -= 1
  End If

  Dim temp As Integer = buffer(max)
  buffer(max) = buffer(random)
  buffer(random) = temp
End Sub

Friend Function GetRandomNumber(max As Integer) As Integer
  Dim _random As New System.Random
  SyncLock _random
      Return _random.Next(1,max)
  End SyncLock
End Function
```

My problem

This shuffle routine is pretty good to scramble randomly the array, but, if it takes only 2ms to scramble 8192 elements, for 24,000,000 elements it takes 32 seconds - too much time for my needs.

Do you know any way to enhance this process and make it faster?

Or do you know another non-deterministic shuffle algorithm to work faster than that I have?

Note: I had already tried PARALLEL.FOR and I had no expressive gain anyway (just few miliseconds in fact).

And I don't really need "random-like" shuffle but just a non-deterministic  ordering.

Thanks for any help

UPDATE

Due to relevant comments of Jdweng and Hans, I feel it's interesting to make an appointment:

The routine works with 2 arrays at same time (an input and an output) and each of them may have until 32 mega-elements (> 33 millions each one), which cause .NET to allocate almost 1Gb of RAM. It's not my choice, but the system requirement, sometimes.

So, I need avoid to create a new array to substitute the SWAP operation to an  in -> out operation...

UPDATE II

Some guys had recommended good practices, but they are not eligible to solve the problem. Let me discuss each of them:

Using different arrays: this procedure may save some clocks-by-operation avoiding swap (3 ops) for using move between array A and B. But it will require to double the RAM request (two identical matrices). It's not an option using huge matrix over NET-Framework memory allocation schema (which require free consecutive blocks of memory).

Using MergedShuffle algorithm: it seems to be the most desirable solution but I'm affraid of having the shuffle separated "by pieces of the matrix", since this schema works on pieces of the matrix based on their middle points. I need to study it deeper to understand the whole process.

Using parallel on pieces of the main array: it is not an option since the shuffle will comply only the imposed range - in other words, I won't have the last elements shuffled with the initial elements of the array. It can be seen as a kind of deterministic schema (not an option).

答:
Most of your poor performance is because you're creating a new random number generator for every random number.  I got a 7x speed increase by only creating one.  I also merged all the code into a single function to maximize the optimization from .net.  The final result is just under 10x faster (117 seconds to 12 for 80,000,000 items on my 32-bit Win7 virtual machine).

```<code>Friend Sub Shuffle(ByRef Buffer As Integer())
    Dim _random As New System.Random
    For max As Integer = Buffer.Length - 1 To 1 Step -1
        Dim random As Integer = _random.Next(1, max)
        Dim temp As Integer = Buffer(max)
        Buffer(max) = Buffer(random)
        Buffer(random) = temp
    Next
End Sub
</code>```

Note a lock is not needed for the random number generator because each call to Shuffle has its own copy and isn't shared across threads.

70% of the time is spent reading the value from Buffer(random).  This is because it's likely not in the CPU cache and has to hit main memory whereas reading Buffer(max) is only .5% because it's being read sequentially descending and the CPU can pre-read it into cache.  20% is in calculating the random number so with a faster generator, you can save a little more time but not much.

The big win would be an algorithm that didn't randomly access the array for every element.  I followed the advice of Hans Passant in the question comments and googled MergeShuffle.  It seems to be just such an algorithm (multiple sequential accesses instead of a random single pass).  And in addition to allowing partitioning, it does not require more RAM.

I prototyped it and I saw a 20% speed up with 80M items switching to Fisher-Yates at 2.5M items.

Title: Faster Scramble Millions Numbers

Body:
I need to scramble HUGE integer arrays (from 1,000,000 to 80,000,000 elements).

These arrays are sequential created (1 to n step 1) and I need to ensure that no one sequential number is lost - and because of it I cannot create "random numbers" arrays.

So, I create them using a single FOR-NEXT (it takes very low time, about 2ms) and I utilize the Fisher-Yates-Durnstenfeld shuffle algorithm, as follows.

First I create the array:

 dim Huge(0 to 80,000,000) as Integer
 For x as integer = 1 to 79,999,999
     Huge(x) = x
 Next

It takes really few miliseconds to be created...

After, I scramble the numbers:

    Shuffle(Huge)

where Shuffle is a routine called in a Parallel/Multitasking environment. Because of this, I need to LOCK the RANDOM function (to provide good entropy in swaping values and locations) utilized in Fisher-Yates-Durstenfeld routine :

The Fisher-Yates Shuffle

Friend Sub Shuffle(ByRef Buffer As Integer())
  For max As Integer = Buffer.Length - 1 To 1 Step -1
      ExtractRandomItem(Buffer, max)
  Next
End Sub

Friend Sub ExtractRandomItem(ByRef buffer As Integer(), max As Integer)
  Dim random As Integer = GetRandomNumber(max + 1)
  If random = max Then
     random -= 1
  End If

  Dim temp As Integer = buffer(max)
  buffer(max) = buffer(random)
  buffer(random) = temp
End Sub

Friend Function GetRandomNumber(max As Integer) As Integer
  Dim _random As New System.Random
  SyncLock _random
      Return _random.Next(1,max)
  End SyncLock
End Function

My problem

This shuffle routine is pretty good to scramble randomly the array, but, if it takes only 2ms to scramble 8192 elements, for 24,000,000 elements it takes 32 seconds - too much time for my needs.

Do you know any way to enhance this process and make it faster?

Or do you know another non-deterministic shuffle algorithm to work faster than that I have?

Note: I had already tried PARALLEL.FOR and I had no expressive gain anyway (just few miliseconds in fact).

And I don't really need "random-like" shuffle but just a non-deterministic  ordering.

Thanks for any help

UPDATE

Due to relevant comments of Jdweng and Hans, I feel it's interesting to make an appointment:

The routine works with 2 arrays at same time (an input and an output) and each of them may have until 32 mega-elements (> 33 millions each one), which cause .NET to allocate almost 1Gb of RAM. It's not my choice, but the system requirement, sometimes.

So, I need avoid to create a new array to substitute the SWAP operation to an  in -> out operation...

UPDATE II

Some guys had recommended good practices, but they are not eligible to solve the problem. Let me discuss each of them:

Using different arrays: this procedure may save some clocks-by-operation avoiding swap (3 ops) for using move between array A and B. But it will require to double the RAM request (two identical matrices). It's not an option using huge matrix over NET-Framework memory allocation schema (which require free consecutive blocks of memory).

Using MergedShuffle algorithm: it seems to be the most desirable solution but I'm affraid of having the shuffle separated "by pieces of the matrix", since this schema works on pieces of the matrix based on their middle points. I need to study it deeper to understand the whole process.

Using parallel on pieces of the main array: it is not an option since the shuffle will comply only the imposed range - in other words, I won't have the last elements shuffled with the initial elements of the array. It can be seen as a kind of deterministic schema (not an option).

Body:
Most of your poor performance is because you're creating a new random number generator for every random number.  I got a 7x speed increase by only creating one.  I also merged all the code into a single function to maximize the optimization from .net.  The final result is just under 10x faster (117 seconds to 12 for 80,000,000 items on my 32-bit Win7 virtual machine).

Friend Sub Shuffle(ByRef Buffer As Integer())
    Dim _random As New System.Random
    For max As Integer = Buffer.Length - 1 To 1 Step -1
        Dim random As Integer = _random.Next(1, max)
        Dim temp As Integer = Buffer(max)
        Buffer(max) = Buffer(random)
        Buffer(random) = temp
    Next
End Sub

Note a lock is not needed for the random number generator because each call to Shuffle has its own copy and isn't shared across threads.

70% of the time is spent reading the value from Buffer(random).  This is because it's likely not in the CPU cache and has to hit main memory whereas reading Buffer(max) is only .5% because it's being read sequentially descending and the CPU can pre-read it into cache.  20% is in calculating the random number so with a faster generator, you can save a little more time but not much.

The big win would be an algorithm that didn't randomly access the array for every element.  I followed the advice of Hans Passant in the question comments and googled MergeShuffle.  It seems to be just such an algorithm (multiple sequential accesses instead of a random single pass).  And in addition to allowing partitioning, it does not require more RAM.

I prototyped it and I saw a 20% speed up with 80M items switching to Fisher-Yates at 2.5M items.


问:
Using C FILE stream in C sockets programming
Am back with a question on using C File stream in sockets programming. I was reading about it and saw mixed reviews - some people say it's not reliable (ie leaky abstraction?).

Has any one got a view about using C File stream in sockets programming?

答: It depends on the kind of application you're writing. FILE streams are not suitable for nonblocking, asynchronous, or select/poll-based IO. This may be no problem for a command line program that performs a sequential task of connecting to a server, making some request, and getting the results. It also works alright for a run-from-inetd-only server process. But if your application will be doing anything event-based, you're in trouble. If you really want to use FILE streams with sockets in an event-based application, you can make it possible using threads, but I doubt it's a good idea...

ContentLicense: CC BY-SA 2.5


问:
iOS Run errors s Xamarin Live Player and Hanselman.Forms
I created an app based off the Hanselman Forms app.  I'm trying to get it to run with the new Xamarin iOS Live Player and i'm getting runtime build errors.

To make sure it wasn't something i broke i did a fresh install of Hanselman Forms and Visual Studio 2017 Preview and connected the iPhone live player.

The build compiles fine with VS.
Trying to run the debug app with Live Player on iPhone gives the following errors.

The following errors were encountered when building and running your app:

• TweetStore.cs: The type or namespace name 'ITweetStore' could not be found (are you missing a using directive or an assembly reference?)
• TweetStore.cs: The type or namespace name 'Tweet' does not exist in the namespace 'Hanselman.Portable' (are you missing an assembly reference?)
• LaunchTwitter.cs: The type or namespace name 'ILaunchTwitter' could not be found (are you missing a using directive or an assembly reference?)

• AppDelegate.cs: The type or namespace name 'App' could not be found (are you missing a using directive or an assembly reference?)

OK

The packets have been refreshed.
I've removed the bin/obj files to do a fresh build.

I've removed the reference, built clean, got similar errors in VS, added the reference back in and the VS build succeeds.

Android works fine.

Any ideas as to what i'm missing?

答:
This is a known issue and is being worked on by the Xamarin folks.

Details at the following link.  https://forums.xamarin.com/discussion/95825/ios-run-time-errors-type-or-namespace-name-not-found-with-xamarin-live-player-and-hanselman-forms/p1?new=1


问:
How to create pages in react
I am creating a really simple app in react. It will have a number of pages with minimum data on it. I am looking for the simplest method to switch between the pages with as little complexities as possible.

This is my current code:

```<code>render() {
    return (
        <div className="App test">
        <nav className="navbar pure-menu pure-menu-horizontal">
          <a href="#" className="pure-menu-heading pure-menu-link">
             Page 1
          </a>
          {
          }<ul className="pure-menu-list">
              <li className="pure-menu-item"><a href="#" className="pure-menu-link">Page 2</a></li>
              <li className="pure-menu-item"><a href="#" className="pure-menu-link">Page 3</a></li>
              <li className="pure-menu-item"><a href="#" className="pure-menu-link">Page 4</a></li>
              </ul>
          }
          </nav>
          <main className="container">
              <div className="pure-g">
                <div className="pure-u-1-1">
                  <p>
                    Page 1 text
                  </p>
                  <p>
                    Page 2 text
                  </p>
                  <p>
                    Page 3 text
                  </p>
                  <p>
                    Page 4 text
                  </p>

                </div>
              </div>
          </main>
        </div>);
  }
}
</code>```

Is there a standard to switch between the content? (Page text 1,2,3,4).

答:
The better way is to add onClickLink function to the link of pages, and put all your pages in an array, and in the place where you want it to be have something like this:

```<code>    onClickLink = (pageNumber, event) => {
            this.setState({ pageNumber });
        }

    render() {
            <ul className="pure-menu-list">
                <li className="pure-menu-item"><a href="#" className="pure-menu-link" onClick=onClickLink.bind(null, 2)>Page 2</a></li>
             </ul>

            <div className="pure-u-1-1">
                <p>arrayOfPageComponents[this.state.pageNumber]</p>
            </div>
        }
</code>```

So the function is bound to the link with the value of page number (in my example 2), when it's called, it's called with 2, so state will be changed to 2, this change will be detected by React and the component will be re-rendered, now reading 2nd value from the array of pages.

Title: How to create pages in react

Body:
I am creating a really simple app in react. It will have a number of pages with minimum data on it. I am looking for the simplest method to switch between the pages with as little complexities as possible.

This is my current code:

render() {
    return (

             Page 1

          {
          }

Page 2

Page 3

Page 4

          }

                    Page 1 text

                    Page 2 text

                    Page 3 text

                    Page 4 text

);
  }
}

Is there a standard to switch between the content? (Page text 1,2,3,4).

Body:
The better way is to add onClickLink function to the link of pages, and put all your pages in an array, and in the place where you want it to be have something like this:

    onClickLink = (pageNumber, event) => {
            this.setState({ pageNumber });
        }

    render() {
            <ul className="pure-menu-list">
                <li className="pure-menu-item"><a href="#" className="pure-menu-link" onClick=onClickLink.bind(null, 2)>Page 2</a></li>
             </ul>

            <div className="pure-u-1-1">
                <p>arrayOfPageComponents[this.state.pageNumber]</p>
            </div>
        }

So the function is bound to the link with the value of page number (in my example 2), when it's called, it's called with 2, so state will be changed to 2, this change will be detected by React and the component will be re-rendered, now reading 2nd value from the array of pages.


问:
How to correctly recover date from SQL Server?
I created a simple CRUD using ASP.NET MVC and I can save my registers normally.
If I look in the Data Base my date was stored like that:

2017-06-01 00:01:23.750

But when I try to Edit the same register whith an async method created by MVC Scaffolding the date appears to bel null:

01/01/0001 00:00:00

Then (of course) I get an error:

The conversion of a datetime2 data type to a datetime data type
  resulted in an out-of-range value.

Thats the async method:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ArtigoId,Titulo,Texto,DataPublicacao,UltimaModificacao,UsuarioModificacao,DataCriacao,UsuarioCriacao")] Artigo artigo)
{
    if (ModelState.IsValid)
    {
        db.Entry(artigo).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(artigo);
}
</code>```

Why does it happen? How to correctly recover the date from data base?

EDIT:

I changed in Data Base for datetime2(0-7) but that made it accept the value 01/01/0001 00:00:00 and what I want is to know why this value appears instead of 2017-06-01 00:01:23.750.

All the others values in the data base is recovered normally, but not this date.

答:
The problem occurred because I removed my field in the View and there is nothing to do with the date format in SQL Server.

I put the field back in the view as readyonly:

```<code><div class="form-group">
    @Html.LabelFor(model => model.DataCriacao, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DataCriacao, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
        @Html.ValidationMessageFor(model => model.DataCriacao, "", new { @class = "text-danger" })
    </div>
</div>
</code>```

The search of the field in the DB is done in the GET method:

```<code>// GET: Artigos/Edit/5
public async Task<ActionResult> Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Artigo artigo = await db.Artigoes.FindAsync(id);
    if (artigo == null)
    {
        return HttpNotFound();
    }
    return View(artigo);
}
</code>```

The method I posted was POST after the submit of my button to save the changes and no searches were done on the database.

Body:
I created a simple CRUD using ASP.NET MVC and I can save my registers normally.
If I look in the Data Base my date was stored like that:

2017-06-01 00:01:23.750

But when I try to Edit the same register whith an async method created by MVC Scaffolding the date appears to bel null:

01/01/0001 00:00:00

Then (of course) I get an error:

The conversion of a datetime2 data type to a datetime data type
  resulted in an out-of-range value.

Thats the async method:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ArtigoId,Titulo,Texto,DataPublicacao,UltimaModificacao,UsuarioModificacao,DataCriacao,UsuarioCriacao")] Artigo artigo)
{
    if (ModelState.IsValid)
    {
        db.Entry(artigo).State = EntityState.Modified;
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    return View(artigo);
}

Why does it happen? How to correctly recover the date from data base?

EDIT:

I changed in Data Base for datetime2(0-7) but that made it accept the value 01/01/0001 00:00:00 and what I want is to know why this value appears instead of 2017-06-01 00:01:23.750.

All the others values in the data base is recovered normally, but not this date.

Body:
The problem occurred because I removed my field in the View and there is nothing to do with the date format in SQL Server.

I put the field back in the view as readyonly:

<div class="form-group">
    @Html.LabelFor(model => model.DataCriacao, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DataCriacao, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
        @Html.ValidationMessageFor(model => model.DataCriacao, "", new { @class = "text-danger" })
    </div>
</div>

The search of the field in the DB is done in the GET method:

// GET: Artigos/Edit/5
public async Task<ActionResult> Edit(Guid? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Artigo artigo = await db.Artigoes.FindAsync(id);
    if (artigo == null)
    {
        return HttpNotFound();
    }
    return View(artigo);
}

The method I posted was POST after the submit of my button to save the changes and no searches were done on the database.


问:
Why does setState take a closure?
What's the benefit of having setState() accept a function just to immediately call it and then request rebuild? In particular, what's the advantage over having users explicitly call a "rebuild" type function?

答:
When Flutter had a "markNeedsBuild" function, developers ended up just sort of calling it at random times. When the syntax switched to setState(() { ... }), developers were much more likely to use the API correctly. They are functionally equivalent from the machine's point of view, but they seem to evoke different code from developers.

If you follow the convention of only mutating member variables inside a setState closure, you'll avoid a situation you're refactoring some code and accidentally remove the call to setState, or call setState unnecessarily. And if your State is unmounted, Flutter can fail an assertion so you know something is wrong as soon as you begin trying to mutate members, instead of at the end.

Eventually there will probably be an analyzer warning enforcing that setState is always called when mutating members of a State, so any member variable mutation that happens outside of initState or a setState callback will be flagged as suspect.

If you're just getting started with state in Flutter, check out the Flutter widgets tour. I've found that a lot of cases where I was calling setState can be handled more elegantly with FutureBuilder, StreamBuilder, AnimatedWidget, or AnimatedBuilder, so don't forget to consider those alternatives if you find yourself calling setState a lot.

Adam Barth and Yaroslav Volovich contributed to this question/answer.

Title: Why does setState take a closure?


问:
Matching Latin Letters, including Serbo-Croatian characters
I am trying to write a regex (regular expression) in PHP to match all Latin letters, including those specific to Serbo-Croatian, such as "ćčđšž"

Here is my code:

```<code>public function alpha_space( $str )
{
    return ( ! preg_match( "/^([-a-z0-9_ ])+$/i", $str ) ) ? FALSE : TRUE;
}
</code>```

How should I modify this snippet so that the regex applies as well to Serbo-Croatian letters?

Thank you for any thoughts you wish to offer.

答:
You can use the regex \p{L} to match any Unicode letter.

This changes your regex to: ^([-\p{L}0-9_ ])+$

```<code>public function alpha_space($str)
{
return ( ! preg_match("/^([-\p{L}0-9_ ])+$/i", $str)) ? FALSE : TRUE;
}
</code>```

Here's a fiddle.

Body:
I am trying to write a regex (regular expression) in PHP to match all Latin letters, including those specific to Serbo-Croatian, such as "ćčđšž"

Here is my code:

public function alpha_space( $str )
{
    return ( ! preg_match( "/^([-a-z0-9_ ])+$/i", $str ) ) ? FALSE : TRUE;
}

How should I modify this snippet so that the regex applies as well to Serbo-Croatian letters?

Thank you for any thoughts you wish to offer.

Body:
You can use the regex \p{L} to match any Unicode letter.

This changes your regex to: ^([-\p{L}0-9_ ])+$

public function alpha_space($str)
{
return ( ! preg_match("/^([-\p{L}0-9_ ])+$/i", $str)) ? FALSE : TRUE;
}

Here's a fiddle.


问:
Showing JSON in html with javascript
i am new with JSON. I am using a api which using JSON for response. I am calling the api url by simple xhr method. The code is working and i am getting 200 status but

how do i able to retrieve the JSON in the html?

I was able to show the JSON by printing xhr.responseText in innerHTML. But i need to show the data so i can use them in html.

Can you suggest how i can present the data in html when i have the json data in xhr.responseText.

Please let me know if you need more info.

Can anyone guide me how to do it via jquery also?

答:
If you add JSON2.js (from https://github.com/douglascrockford/JSON-js/blob/master/json2.js) to your page, then you can parse the JSON into a JavaScript object by using:

```<code>var parsedData = JSON.parse(xhr.responseText);
</code>```

If you completely trust your JSON source, you can also do it very quickly and without using JSON2.js by simply evaling it thus:

```<code>var parsedData = eval('(' + xhr.responseText + ')');
</code>```

but this will run any code embedded in the response and so isn't secure and generally wouldn't be recommended.

Title: Showing JSON in html with javascript

Body:
If you add JSON2.js (from https://github.com/douglascrockford/JSON-js/blob/master/json2.js) to your page, then you can parse the JSON into a JavaScript object by using:

var parsedData = JSON.parse(xhr.responseText);

If you completely trust your JSON source, you can also do it very quickly and without using JSON2.js by simply evaling it thus:

var parsedData = eval('(' + xhr.responseText + ')');

but this will run any code embedded in the response and so isn't secure and generally wouldn't be recommended.


问:
Make a child view match the width of a parent scrollview
I have a horizontal scrollview with many EditText children. I want each of these children to be the same width of the visible area of the parent scrollview. Is this possible in XML? </p>

答:
I found some edge cases where the FullWidthEditText posted by rupps didn't work, so I modified it to work in all the cases I've found:

```<code>public class FullWidthTextView extends android.support.v7.widget.AppCompatTextView
{
    public FullWidthTextView( final Context context )
    {
        super( context );
    }

    public FullWidthTextView( final Context context, @Nullable final AttributeSet attrs )
    {
        super( context, attrs );
    }

    public FullWidthTextView( final Context context, @Nullable final AttributeSet attrs, final int defStyleAttr )
    {
        super( context, attrs, defStyleAttr );
    }

    @Override
    protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec )
    {
        View parentScrollView = ((View) (getParent().getParent()));

        boolean needsRemeassure = false;

        if( parentScrollView != null )
        {
            // check the container of the container is an HorizontallScrollView
            if( parentScrollView instanceof HorizontalScrollView )
            {
                // Yes it is, so change width to HSV's width
                int parentWidth = parentScrollView.getMeasuredWidth();
                if( parentWidth > 0 )
                {
                    widthMeasureSpec = parentWidth;
                }
                // It's possible for the parent to still have ZERO width
                // in this case we must request to be remeassured
                else
                {
                    needsRemeassure = true;
                }
            }
        }

        super.onMeasure( widthMeasureSpec, heightMeasureSpec );

        setMeasuredDimension( View.MeasureSpec.makeMeasureSpec( widthMeasureSpec, MeasureSpec.EXACTLY ),
                              View.MeasureSpec.makeMeasureSpec( getMeasuredHeight(), MeasureSpec.EXACTLY ) );

        if( needsRemeassure )
        {
            post( new Runnable()
            {
                @Override
                public void run()
                {
                    requestLayout();
                }
            } );
        }
    }
}
</code>```

Body:
I found some edge cases where the FullWidthEditText posted by rupps didn't work, so I modified it to work in all the cases I've found:

public class FullWidthTextView extends android.support.v7.widget.AppCompatTextView
{
    public FullWidthTextView( final Context context )
    {
        super( context );
    }

    public FullWidthTextView( final Context context, @Nullable final AttributeSet attrs )
    {
        super( context, attrs );
    }

    public FullWidthTextView( final Context context, @Nullable final AttributeSet attrs, final int defStyleAttr )
    {
        super( context, attrs, defStyleAttr );
    }

    @Override
    protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec )
    {
        View parentScrollView = ((View) (getParent().getParent()));

        boolean needsRemeassure = false;

        if( parentScrollView != null )
        {
            // check the container of the container is an HorizontallScrollView
            if( parentScrollView instanceof HorizontalScrollView )
            {
                // Yes it is, so change width to HSV's width
                int parentWidth = parentScrollView.getMeasuredWidth();
                if( parentWidth > 0 )
                {
                    widthMeasureSpec = parentWidth;
                }
                // It's possible for the parent to still have ZERO width
                // in this case we must request to be remeassured
                else
                {
                    needsRemeassure = true;
                }
            }
        }

        super.onMeasure( widthMeasureSpec, heightMeasureSpec );

        setMeasuredDimension( View.MeasureSpec.makeMeasureSpec( widthMeasureSpec, MeasureSpec.EXACTLY ),
                              View.MeasureSpec.makeMeasureSpec( getMeasuredHeight(), MeasureSpec.EXACTLY ) );

        if( needsRemeassure )
        {
            post( new Runnable()
            {
                @Override
                public void run()
                {
                    requestLayout();
                }
            } );
        }
    }
}


问:
I created my own CA to sign localhost certs. Why does Chrome reject it?
I created my own CA to sign localhost certs.  Why does Chromium reject it?  I have imported the cert into Chromium.

The output of openssl x509 -text on the signed cert:

```<code>Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 10 (0xa)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = US, ST = Tennessee, L = Knoxville, O = Demi Obenour, OU = Demi Obenour, CN = localhost, emailAddress = demiobenour@gmail.com
        Validity
            Not Before: Jun  4 03:19:59 2017 GMT
            Not After : Jun  4 03:19:59 2018 GMT
        Subject: C = US, ST = Tennessee, O = Demi Obenour, OU = Demi Obenour, CN = localhost
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (4096 bit)
                Modulus:
                    00:d1:7f:58:b7:e8:d2:ea:31:29:bd:89:f8:ce:23:
                    9a:39:63:f5:67:7f:93:a9:35:cf:d7:8e:c7:0e:58:
                    90:28:f3:95:f8:a1:24:72:b5:36:9b:3a:e5:72:35:
                    f5:6a:6a:22:20:1b:35:6c:25:43:84:fa:fa:b0:0c:
                    a6:23:79:55:48:41:de:2f:17:16:51:8c:3a:20:69:
                    ce:56:35:61:bf:35:2f:8f:dc:d1:5f:ca:56:86:b8:
                    0f:df:56:0a:2b:a0:21:e8:76:fe:59:f1:65:63:04:
                    63:eb:42:19:bc:30:aa:e9:67:cc:95:c3:74:43:62:
                    ba:2d:18:54:bd:68:c9:a4:59:03:98:ba:f4:d4:ab:
                    7b:9d:8a:36:dc:14:a9:d7:26:46:c3:c3:4b:9d:95:
                    8c:5b:0e:3d:b9:81:dd:b5:f8:37:b3:a8:9f:1c:93:
                    9a:37:d8:e1:ac:6d:a6:59:15:60:94:58:16:8b:18:
                    41:c6:1f:3a:f6:ce:e6:13:15:8d:54:63:ef:ad:32:
                    1f:21:a6:7b:05:6d:56:db:5f:a6:65:92:bd:ca:a8:
                    79:e1:5f:95:2b:1c:d3:15:cf:4d:0e:f0:be:2f:de:
                    47:e9:ca:b6:f6:85:a0:0a:af:f6:58:00:f2:9b:08:
                    47:4b:84:26:ba:1c:f8:93:8f:55:d7:31:5b:24:87:
                    a7:61:ef:f3:48:c9:cc:26:e3:37:3e:10:db:be:f4:
                    8a:8f:27:ff:35:76:ef:0b:11:c6:61:94:d3:e5:d2:
                    28:bf:2d:64:f0:75:9a:df:08:08:d4:1f:49:b8:9d:
                    66:64:43:86:50:01:0e:19:96:cf:89:3e:83:ca:40:
                    92:9c:d1:3f:d9:c9:ce:43:05:0b:0c:ce:4f:8e:3f:
                    6e:66:65:bc:1d:c7:26:81:93:5b:4b:29:97:4e:ca:
                    21:86:31:98:93:3b:9b:c7:11:0e:d5:6a:67:6a:48:
                    4c:62:c5:99:ae:41:a1:d2:8c:0e:25:50:dd:b4:6e:
                    00:8a:99:a6:e7:4c:2b:4d:ca:21:13:b6:fa:78:4b:
                    b7:12:fa:bb:70:c9:f0:5a:c5:dd:b5:fa:35:9c:10:
                    cd:6e:74:ce:97:12:07:e1:30:9f:f2:f3:bc:9f:5e:
                    41:40:66:e3:e2:95:d9:3c:76:80:8e:57:cf:7c:1e:
                    ba:2d:24:f0:a1:7e:c5:6f:aa:de:6c:1c:89:ac:7c:
                    3a:d5:10:72:82:67:b2:31:a0:c3:e3:7a:50:61:81:
                    80:44:1c:c7:fc:ed:bd:4b:38:42:87:a0:1e:db:d9:
                    c2:61:f8:95:78:9a:05:2a:5b:a9:4d:bf:81:e2:d0:
                    4e:5d:9e:98:29:0d:6f:d2:1e:12:17:05:43:93:82:
                    1d:0c:bf
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Cert Type:
                SSL Client, S/MIME, Object Signing
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                8A:A9:62:8B:12:CE:43:8E:FB:36:60:90:C3:C9:26:91:B2:3E:7A:C6
            X509v3 Authority Key Identifier:
                keyid:43:6F:BC:BE:10:86:DE:AF:A9:39:65:5D:29:3C:10:47:F3:30:34:B4

            X509v3 Subject Alternative Name:
                DNS:localhost, DNS:localhost
    Signature Algorithm: sha256WithRSAEncryption
         c3:bc:ee:e2:de:64:53:2b:3a:54:4f:ba:dd:45:14:a2:99:f6:
         00:95:3e:d5:05:b1:97:27:0b:40:d0:95:51:72:63:c4:89:22:
         d9:3d:1d:0a:77:ec:82:93:93:45:43:81:b1:3e:3e:6c:9c:60:
         b8:00:c1:c1:7c:07:f0:e4:79:6f:d9:14:1d:e6:61:62:c6:32:
         00:15:63:60:6b:ab:58:7c:8e:6f:5e:a9:38:c4:4b:2c:ae:bb:
         35:b8:53:e1:d7:88:96:35:b7:f5:d8:3a:cd:b2:bf:6f:32:0f:
         f5:ea:36:85:60:fa:24:b6:f1:ed:2f:af:fc:af:51:65:2f:b0:
         e6:cd:28:22:26:27:ec:2d:e5:f4:fd:b1:55:3f:2d:4c:03:2a:
         65:a4:4c:af:d1:4c:d0:0f:52:d0:54:c5:5a:0c:28:3e:69:19:
         7b:40:a2:e4:fd:55:57:f7:0d:2e:3f:a4:2f:48:97:55:df:21:
         f9:c8:8a:44:63:e4:c8:8b:5e:2b:87:07:a3:a6:df:b4:77:26:
         bf:bf:76:00:32:99:87:dc:c5:8c:b2:28:3a:62:e3:8d:f4:4e:
         34:e0:7d:89:f6:d6:93:03:df:05:73:86:d6:43:e7:db:be:66:
         de:cd:3b:72:99:a7:cd:b7:e6:a7:86:75:5d:c1:dc:80:ba:b0:
         50:86:21:1a
</code>```

The output of openssl x509 -text on the CA cert

```<code>Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            db:5f:d9:ca:98:3e:71:43
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = US, ST = Tennessee, L = Knoxville, O = Demi Obenour, OU = Demi Obenour, CN = localhost, emailAddress = demiobenour@gmail.com
        Validity
            Not Before: Jun  2 14:46:38 2017 GMT
            Not After : May 31 14:46:38 2027 GMT
        Subject: C = US, ST = Tennessee, L = Knoxville, O = Demi Obenour, OU = Demi Obenour, CN = localhost, emailAddress = demiobenour@gmail.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:de:7d:fe:44:3b:04:d0:57:f3:44:1f:49:2e:d1:
                    a6:10:df:cb:98:e2:6a:b3:e7:5e:8a:6e:58:a8:5f:
                    23:8d:40:53:cf:bc:3d:9d:e7:7d:db:59:16:0c:53:
                    0e:f1:56:4f:b0:9a:bb:64:f4:be:76:e2:fc:79:5f:
                    c8:2d:eb:0b:ec:a9:58:b6:4a:17:57:6d:1d:d4:c6:
                    d8:e4:3b:4c:24:7b:ba:fa:4f:c5:95:af:c8:cc:38:
                    81:08:3a:09:d6:98:88:27:9f:9f:4f:ac:36:bd:4c:
                    fa:8c:65:43:f6:57:03:78:2c:c0:b1:69:2c:6a:76:
                    a3:e4:fc:f7:0c:c7:2c:79:7e:0e:1e:c9:c4:88:65:
                    60:27:78:ca:02:32:04:03:ab:1a:de:42:c7:d1:58:
                    89:31:af:f2:47:ac:e7:e4:c4:47:2f:22:91:16:64:
                    dc:b8:34:5f:6f:24:6e:e8:80:ed:ca:1a:7c:7a:81:
                    6a:fe:a6:6c:27:af:7e:4e:92:76:81:fd:d0:32:a4:
                    7b:ca:19:21:c6:a1:ad:4a:ca:52:60:00:70:14:82:
                    eb:22:74:d4:d6:a2:6d:c8:2b:cd:9a:cb:7a:03:74:
                    7e:f6:85:1e:03:29:34:1f:c5:32:bf:c1:e0:0e:b0:
                    1b:41:56:10:a0:1f:5f:b8:2d:b0:16:fb:aa:81:f6:
                    cf:2b
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                43:6F:BC:BE:10:86:DE:AF:A9:39:65:5D:29:3C:10:47:F3:30:34:B4
            X509v3 Authority Key Identifier:
                keyid:43:6F:BC:BE:10:86:DE:AF:A9:39:65:5D:29:3C:10:47:F3:30:34:B4

            X509v3 Basic Constraints: critical
                CA:TRUE
    Signature Algorithm: sha256WithRSAEncryption
         02:0f:a6:1b:bb:89:dd:7f:15:5a:65:a9:f1:ed:19:07:db:63:
         6e:f5:68:d0:10:97:8d:9c:86:94:ba:5b:e7:a5:43:7a:65:fc:
         0c:88:03:ec:7e:be:25:bc:82:56:bb:a5:ce:a2:82:21:42:4e:
         db:58:d3:d4:62:67:cd:86:18:3d:ca:af:de:7a:e8:13:53:b7:
         61:0c:0c:b8:01:54:1e:58:67:54:0e:e8:d8:cd:25:5b:01:94:
         00:28:5c:80:02:f1:56:53:9e:32:de:d8:73:6f:e2:b1:2e:b5:
         f1:15:f9:c4:8b:b2:54:0d:59:79:b0:d3:d8:b8:3b:03:47:b4:
         c5:55:38:19:b6:d8:cc:a8:5e:10:42:5e:a7:e3:cf:8d:bb:e4:
         ff:c8:e0:2f:2b:67:3e:95:db:10:0f:7f:7b:83:51:2c:c4:f3:
         49:ff:3c:21:33:14:aa:cf:77:28:29:91:04:3c:d8:49:e9:00:
         82:f2:51:5e:da:74:3f:b8:99:8f:b8:54:b4:11:d6:4c:1e:98:
         84:a5:e0:91:85:90:0d:95:3f:94:b2:a4:d3:d5:31:ec:f7:3d:
         88:dd:54:3c:26:1a:35:12:b7:14:ce:86:7b:0a:a5:f3:eb:1a:
         05:49:ad:b0:2e:ca:6c:65:b8:bd:59:76:82:2a:49:7f:79:99:
         01:b1:c5:cb
</code>```

Edit: The error is NET::ERR_CERT_INVALID

答:
Server Certificate:

```<code>X509v3 Key Usage:
    Digital Signature, Non Repudiation, Key Encipherment
</code>```

Key Encipherment is RSA key transport. Key transport is now frowned upon, and the move is towards algorithms with forward secrecy. Chrome may be having trouble with it.

The server's certificate also lacks Extended Key Usage (EKU) of Server Authentication. I seem to recall the CA/B Baseline Requirements require it. Chrome may be having trouble with it.

This looks unusual, but I don't think its causing the failure:

```<code>X509v3 Subject Alternative Name:
    DNS:localhost, DNS:localhost
</code>```

CA Certificate:

The CA certificate is missing required Key Usage, so the problem could be the CA is not allowed to issue certificates. Effectively you have a CA that can't do anything.

Its unusual to place a hostname in the CA's subject common name. I'm guessing there's something not quite right in your openssl.conf file:

```<code> Issuer: C = US, ST = Tennessee, ..., CN = localhost, emailAddress = demiobenour@gmail.com
</code>```

Also see see How do you sign Certificate Signing Request with your Certification Authority and How to create a self-signed certificate with openssl? The answers detail the bits you need in your certificates and the standard they come from.

Body:
I created my own CA to sign localhost certs.  Why does Chromium reject it?  I have imported the cert into Chromium.

The output of openssl x509 -text on the signed cert:

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 10 (0xa)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = US, ST = Tennessee, L = Knoxville, O = Demi Obenour, OU = Demi Obenour, CN = localhost, emailAddress = demiobenour@gmail.com
        Validity
            Not Before: Jun  4 03:19:59 2017 GMT
            Not After : Jun  4 03:19:59 2018 GMT
        Subject: C = US, ST = Tennessee, O = Demi Obenour, OU = Demi Obenour, CN = localhost
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (4096 bit)
                Modulus:
                    00:d1:7f:58:b7:e8:d2:ea:31:29:bd:89:f8:ce:23:
                    9a:39:63:f5:67:7f:93:a9:35:cf:d7:8e:c7:0e:58:
                    90:28:f3:95:f8:a1:24:72:b5:36:9b:3a:e5:72:35:
                    f5:6a:6a:22:20:1b:35:6c:25:43:84:fa:fa:b0:0c:
                    a6:23:79:55:48:41:de:2f:17:16:51:8c:3a:20:69:
                    ce:56:35:61:bf:35:2f:8f:dc:d1:5f:ca:56:86:b8:
                    0f:df:56:0a:2b:a0:21:e8:76:fe:59:f1:65:63:04:
                    63:eb:42:19:bc:30:aa:e9:67:cc:95:c3:74:43:62:
                    ba:2d:18:54:bd:68:c9:a4:59:03:98:ba:f4:d4:ab:
                    7b:9d:8a:36:dc:14:a9:d7:26:46:c3:c3:4b:9d:95:
                    8c:5b:0e:3d:b9:81:dd:b5:f8:37:b3:a8:9f:1c:93:
                    9a:37:d8:e1:ac:6d:a6:59:15:60:94:58:16:8b:18:
                    41:c6:1f:3a:f6:ce:e6:13:15:8d:54:63:ef:ad:32:
                    1f:21:a6:7b:05:6d:56:db:5f:a6:65:92:bd:ca:a8:
                    79:e1:5f:95:2b:1c:d3:15:cf:4d:0e:f0:be:2f:de:
                    47:e9:ca:b6:f6:85:a0:0a:af:f6:58:00:f2:9b:08:
                    47:4b:84:26:ba:1c:f8:93:8f:55:d7:31:5b:24:87:
                    a7:61:ef:f3:48:c9:cc:26:e3:37:3e:10:db:be:f4:
                    8a:8f:27:ff:35:76:ef:0b:11:c6:61:94:d3:e5:d2:
                    28:bf:2d:64:f0:75:9a:df:08:08:d4:1f:49:b8:9d:
                    66:64:43:86:50:01:0e:19:96:cf:89:3e:83:ca:40:
                    92:9c:d1:3f:d9:c9:ce:43:05:0b:0c:ce:4f:8e:3f:
                    6e:66:65:bc:1d:c7:26:81:93:5b:4b:29:97:4e:ca:
                    21:86:31:98:93:3b:9b:c7:11:0e:d5:6a:67:6a:48:
                    4c:62:c5:99:ae:41:a1:d2:8c:0e:25:50:dd:b4:6e:
                    00:8a:99:a6:e7:4c:2b:4d:ca:21:13:b6:fa:78:4b:
                    b7:12:fa:bb:70:c9:f0:5a:c5:dd:b5:fa:35:9c:10:
                    cd:6e:74:ce:97:12:07:e1:30:9f:f2:f3:bc:9f:5e:
                    41:40:66:e3:e2:95:d9:3c:76:80:8e:57:cf:7c:1e:
                    ba:2d:24:f0:a1:7e:c5:6f:aa:de:6c:1c:89:ac:7c:
                    3a:d5:10:72:82:67:b2:31:a0:c3:e3:7a:50:61:81:
                    80:44:1c:c7:fc:ed:bd:4b:38:42:87:a0:1e:db:d9:
                    c2:61:f8:95:78:9a:05:2a:5b:a9:4d:bf:81:e2:d0:
                    4e:5d:9e:98:29:0d:6f:d2:1e:12:17:05:43:93:82:
                    1d:0c:bf
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Basic Constraints:
                CA:FALSE
            Netscape Cert Type:
                SSL Client, S/MIME, Object Signing
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment
            Netscape Comment:
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier:
                8A:A9:62:8B:12:CE:43:8E:FB:36:60:90:C3:C9:26:91:B2:3E:7A:C6
            X509v3 Authority Key Identifier:
                keyid:43:6F:BC:BE:10:86:DE:AF:A9:39:65:5D:29:3C:10:47:F3:30:34:B4

            X509v3 Subject Alternative Name:
                DNS:localhost, DNS:localhost
    Signature Algorithm: sha256WithRSAEncryption
         c3:bc:ee:e2:de:64:53:2b:3a:54:4f:ba:dd:45:14:a2:99:f6:
         00:95:3e:d5:05:b1:97:27:0b:40:d0:95:51:72:63:c4:89:22:
         d9:3d:1d:0a:77:ec:82:93:93:45:43:81:b1:3e:3e:6c:9c:60:
         b8:00:c1:c1:7c:07:f0:e4:79:6f:d9:14:1d:e6:61:62:c6:32:
         00:15:63:60:6b:ab:58:7c:8e:6f:5e:a9:38:c4:4b:2c:ae:bb:
         35:b8:53:e1:d7:88:96:35:b7:f5:d8:3a:cd:b2:bf:6f:32:0f:
         f5:ea:36:85:60:fa:24:b6:f1:ed:2f:af:fc:af:51:65:2f:b0:
         e6:cd:28:22:26:27:ec:2d:e5:f4:fd:b1:55:3f:2d:4c:03:2a:
         65:a4:4c:af:d1:4c:d0:0f:52:d0:54:c5:5a:0c:28:3e:69:19:
         7b:40:a2:e4:fd:55:57:f7:0d:2e:3f:a4:2f:48:97:55:df:21:
         f9:c8:8a:44:63:e4:c8:8b:5e:2b:87:07:a3:a6:df:b4:77:26:
         bf:bf:76:00:32:99:87:dc:c5:8c:b2:28:3a:62:e3:8d:f4:4e:
         34:e0:7d:89:f6:d6:93:03:df:05:73:86:d6:43:e7:db:be:66:
         de:cd:3b:72:99:a7:cd:b7:e6:a7:86:75:5d:c1:dc:80:ba:b0:
         50:86:21:1a

The output of openssl x509 -text on the CA cert

Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number:
            db:5f:d9:ca:98:3e:71:43
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C = US, ST = Tennessee, L = Knoxville, O = Demi Obenour, OU = Demi Obenour, CN = localhost, emailAddress = demiobenour@gmail.com
        Validity
            Not Before: Jun  2 14:46:38 2017 GMT
            Not After : May 31 14:46:38 2027 GMT
        Subject: C = US, ST = Tennessee, L = Knoxville, O = Demi Obenour, OU = Demi Obenour, CN = localhost, emailAddress = demiobenour@gmail.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:de:7d:fe:44:3b:04:d0:57:f3:44:1f:49:2e:d1:
                    a6:10:df:cb:98:e2:6a:b3:e7:5e:8a:6e:58:a8:5f:
                    23:8d:40:53:cf:bc:3d:9d:e7:7d:db:59:16:0c:53:
                    0e:f1:56:4f:b0:9a:bb:64:f4:be:76:e2:fc:79:5f:
                    c8:2d:eb:0b:ec:a9:58:b6:4a:17:57:6d:1d:d4:c6:
                    d8:e4:3b:4c:24:7b:ba:fa:4f:c5:95:af:c8:cc:38:
                    81:08:3a:09:d6:98:88:27:9f:9f:4f:ac:36:bd:4c:
                    fa:8c:65:43:f6:57:03:78:2c:c0:b1:69:2c:6a:76:
                    a3:e4:fc:f7:0c:c7:2c:79:7e:0e:1e:c9:c4:88:65:
                    60:27:78:ca:02:32:04:03:ab:1a:de:42:c7:d1:58:
                    89:31:af:f2:47:ac:e7:e4:c4:47:2f:22:91:16:64:
                    dc:b8:34:5f:6f:24:6e:e8:80:ed:ca:1a:7c:7a:81:
                    6a:fe:a6:6c:27:af:7e:4e:92:76:81:fd:d0:32:a4:
                    7b:ca:19:21:c6:a1:ad:4a:ca:52:60:00:70:14:82:
                    eb:22:74:d4:d6:a2:6d:c8:2b:cd:9a:cb:7a:03:74:
                    7e:f6:85:1e:03:29:34:1f:c5:32:bf:c1:e0:0e:b0:
                    1b:41:56:10:a0:1f:5f:b8:2d:b0:16:fb:aa:81:f6:
                    cf:2b
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                43:6F:BC:BE:10:86:DE:AF:A9:39:65:5D:29:3C:10:47:F3:30:34:B4
            X509v3 Authority Key Identifier:
                keyid:43:6F:BC:BE:10:86:DE:AF:A9:39:65:5D:29:3C:10:47:F3:30:34:B4

            X509v3 Basic Constraints: critical
                CA:TRUE
    Signature Algorithm: sha256WithRSAEncryption
         02:0f:a6:1b:bb:89:dd:7f:15:5a:65:a9:f1:ed:19:07:db:63:
         6e:f5:68:d0:10:97:8d:9c:86:94:ba:5b:e7:a5:43:7a:65:fc:
         0c:88:03:ec:7e:be:25:bc:82:56:bb:a5:ce:a2:82:21:42:4e:
         db:58:d3:d4:62:67:cd:86:18:3d:ca:af:de:7a:e8:13:53:b7:
         61:0c:0c:b8:01:54:1e:58:67:54:0e:e8:d8:cd:25:5b:01:94:
         00:28:5c:80:02:f1:56:53:9e:32:de:d8:73:6f:e2:b1:2e:b5:
         f1:15:f9:c4:8b:b2:54:0d:59:79:b0:d3:d8:b8:3b:03:47:b4:
         c5:55:38:19:b6:d8:cc:a8:5e:10:42:5e:a7:e3:cf:8d:bb:e4:
         ff:c8:e0:2f:2b:67:3e:95:db:10:0f:7f:7b:83:51:2c:c4:f3:
         49:ff:3c:21:33:14:aa:cf:77:28:29:91:04:3c:d8:49:e9:00:
         82:f2:51:5e:da:74:3f:b8:99:8f:b8:54:b4:11:d6:4c:1e:98:
         84:a5:e0:91:85:90:0d:95:3f:94:b2:a4:d3:d5:31:ec:f7:3d:
         88:dd:54:3c:26:1a:35:12:b7:14:ce:86:7b:0a:a5:f3:eb:1a:
         05:49:ad:b0:2e:ca:6c:65:b8:bd:59:76:82:2a:49:7f:79:99:
         01:b1:c5:cb

Edit: The error is NET::ERR_CERT_INVALID

Body:
Server Certificate:

X509v3 Key Usage:
    Digital Signature, Non Repudiation, Key Encipherment

Key Encipherment is RSA key transport. Key transport is now frowned upon, and the move is towards algorithms with forward secrecy. Chrome may be having trouble with it.

The server's certificate also lacks Extended Key Usage (EKU) of Server Authentication. I seem to recall the CA/B Baseline Requirements require it. Chrome may be having trouble with it.

This looks unusual, but I don't think its causing the failure:

X509v3 Subject Alternative Name:
    DNS:localhost, DNS:localhost

CA Certificate:

The CA certificate is missing required Key Usage, so the problem could be the CA is not allowed to issue certificates. Effectively you have a CA that can't do anything.

Its unusual to place a hostname in the CA's subject common name. I'm guessing there's something not quite right in your openssl.conf file:

 Issuer: C = US, ST = Tennessee, ..., CN = localhost, emailAddress = demiobenour@gmail.com

Also see see How do you sign Certificate Signing Request with your Certification Authority and How to create a self-signed certificate with openssl? The answers detail the bits you need in your certificates and the standard they come from.


问:
Using ASCIIMath, how can we align variables in proper order in a system of linear equations
For instance how can we display folliwing in MathJax using ASCIIMath:

答:
This is as close as I could come:

```<code>{
  [      -x_1, ,   , ,   ,+,x_4,=,\qquad 130],
  [          , ,   , ,x_3,-,x_4,=,\qquad\quad 60],
  [          , ,x_2,-,x_3, ,   ,=,-240],
  [\qquad x_1,-,x_2, ,   , ,   ,=,\qquad\quad 50]
:}
</code>```

The spacing is a bit ad hoc, but perhaps it is good enough for you.

Body:
This is as close as I could come:

{
  [      -x_1, ,   , ,   ,+,x_4,=,\qquad 130],
  [          , ,   , ,x_3,-,x_4,=,\qquad\quad 60],
  [          , ,x_2,-,x_3, ,   ,=,-240],
  [\qquad x_1,-,x_2, ,   , ,   ,=,\qquad\quad 50]
:}

The spacing is a bit ad hoc, but perhaps it is good enough for you.


问:
How to update field value by determining each digit in field?
Although I saw update statements to update field based on existing values, I could not find anything similar to this scenario:

Suppose you have a table with only one column of number(4) type.  The value in the first record is 1010.

```<code>create table stab(
  nmbr number(4)
);

insert into stab values(1010);

For each digit
   When the digit is 1 -- add 3 to the digit
   When the digit is 0 -- add four to the digit
end
</code>```

This operations needs to be completed in a single statement without using pl/sql.

I think substr function need to be used but don't know how to go about completing this.

Thanks in advance.

答:
```<code>SELECT DECODE(SUBSTR(nmbr,1,1), '1', 1 + 3, '0', 0 + 4) AS Decoded_Nmbr
FROM stab
ORDER BY Decoded_Nmbr
</code>```

Is that what you are after?

Body:
Although I saw update statements to update field based on existing values, I could not find anything similar to this scenario:

Suppose you have a table with only one column of number(4) type.  The value in the first record is 1010.

create table stab(
  nmbr number(4)
);

insert into stab values(1010);

For each digit
   When the digit is 1 -- add 3 to the digit
   When the digit is 0 -- add four to the digit
end

This operations needs to be completed in a single statement without using pl/sql.

I think substr function need to be used but don't know how to go about completing this.

Thanks in advance.

Body:
SELECT DECODE(SUBSTR(nmbr,1,1), '1', 1 + 3, '0', 0 + 4) AS Decoded_Nmbr
FROM stab
ORDER BY Decoded_Nmbr

Is that what you are after?