问:
html page not getting cookies through libcurl
i modified my previous code. you can see my previous post if your intersted setting cookie through curl
But here is a fresh beginning my new code looks linke this
i have a php file using curl like this

```<code><?php
$ch=curl_init();
$url="http://localhost/javascript%20cookies/test_cookies.php";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_COOKIEFILE,dirname(__FILE__) . "/cookie.txt");
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_exec($ch);
curl_close($ch);
?>
</code>```

the file test_cookies.php looks like this

```<code><?php
if($_COOKIE['user']==1)
{
header("Set-Cookie:user=1; color=blue");
header("Location:http://localhost/javascript%20cookies/test_cookies.html");
}
?>
</code>```

the file test_cookies.html has some javascript that checks for  cookies and if it finds those cookies then it displays the text accordingly.
the php file with curl code is sending the cookies and the test_cookies.php is setting the cookie and redirecting to the page test_cookies.html but this page is not receiving the cookies and thus it is not not showing the content accordingly.
can somebody tell me whats the problem now?

here are the headers i get displayed in firefox on setting CURLOPT_HEADER to true

```<code>HTTP/1.1 302 Found Date: Mon, 16 May 2011 15:03:59 GMT Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1 X-Powered-By: PHP/5.3.1 Set-Cookie: user=1; color=blue Location: http://localhost/javascript%20cookies/test_cookies.html Content-Length: 0 Content-Type: text/html HTTP/1.1 200 OK Date: Mon, 16 May 2011 15:03:59 GMT Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1 Last-Modified: Mon, 16 May 2011 12:13:24 GMT ETag: "11000000013d0c-493-4a363950a70f3" Accept-Ranges: bytes Content-Length: 1171 Content-Type: text/html
</code>```

you can see that there are two set of headers displayed.is this because i am making 2 calls to header?

答:
It is not clear what you are trying to achieve with the code. You'd get better help if you explain why you are doing this. It is probable that your approach is wrong and you could get the ultimate result with a different/simpler approach.

And now to answer your question, this is what happens:

From your browser, you send a GET request to curl.php (the name I use for your first file),

curl in that file checks cookie.txt and finds user=1, so it sends a GET request to test_cookies.php and sends the cookie with the request

test_cookies.php sees that user=1 is true, so it sends a header to  curl.php and asks it to set two cookies: user=1 and color=blue (for the first cookie this is pointless, user=1 is already set, but let's ignore this as no harm is done)

You have not set CURLOPT_COOKIEJAR option, so when curl.php receives the set cookie header it does not give a damn (nothing happens)

Next, test_cookies.php sends a redirect header to curl.php, since you have set CURLOPT_FOLLOWLOCATION,1, curl.php sends another GET request, this time to get test_cookies.html

Content of test_cookies.html is returned to curl.php,

curl_exec($ch); causes the returned content (source of test_cookies.html) be echoed back to your browser,

Your browser parses what it received and the javascript is executed. It checks for a cookie named user and does not find one, so it displays content for when there is no cookie (because there isn't).

Now, you may wonder what happens if you add:

```<code>curl_setopt($ch,CURLOPT_COOKIEJAR,dirname(__FILE__) . "/cookie.txt");
</code>```

What happens is that your cookie.txt will be updated in step 4 and will have two cookies; user=1 and color=blue. But this does NOT give you the result you expect. Because header("Set-Cookie:user=1; color=blue"); is instructing curl to set the cookie, and curl does this by storing the cookies in the file you specified in CURLOPT_COOKIEJAR option. So, even though you added that option, when you reach step 8 javascript will not find that cookie, because the browser you use does not know or care about your cookie.txt, it looks somewhere else to check if a cookie exists. In Google Chrome for instance the format is SQLite and for XP the cookies are stored in %USERPROFILE%\Local Settings\Application Data\Google\Chrome\User Data\Default\Cookies.

Body:
i modified my previous code. you can see my previous post if your intersted setting cookie through curl
But here is a fresh beginning my new code looks linke this
i have a php file using curl like this

<?php
$ch=curl_init();
$url="http://localhost/javascript%20cookies/test_cookies.php";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_COOKIEFILE,dirname(__FILE__) . "/cookie.txt");
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_exec($ch);
curl_close($ch);
?>

the file test_cookies.php looks like this

<?php
if($_COOKIE['user']==1)
{
header("Set-Cookie:user=1; color=blue");
header("Location:http://localhost/javascript%20cookies/test_cookies.html");
}
?>

the file test_cookies.html has some javascript that checks for  cookies and if it finds those cookies then it displays the text accordingly.
the php file with curl code is sending the cookies and the test_cookies.php is setting the cookie and redirecting to the page test_cookies.html but this page is not receiving the cookies and thus it is not not showing the content accordingly.
can somebody tell me whats the problem now?

here are the headers i get displayed in firefox on setting CURLOPT_HEADER to true

HTTP/1.1 302 Found Date: Mon, 16 May 2011 15:03:59 GMT Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1 X-Powered-By: PHP/5.3.1 Set-Cookie: user=1; color=blue Location: http://localhost/javascript%20cookies/test_cookies.html Content-Length: 0 Content-Type: text/html HTTP/1.1 200 OK Date: Mon, 16 May 2011 15:03:59 GMT Server: Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1 Last-Modified: Mon, 16 May 2011 12:13:24 GMT ETag: "11000000013d0c-493-4a363950a70f3" Accept-Ranges: bytes Content-Length: 1171 Content-Type: text/html

you can see that there are two set of headers displayed.is this because i am making 2 calls to header?

Body:
It is not clear what you are trying to achieve with the code. You'd get better help if you explain why you are doing this. It is probable that your approach is wrong and you could get the ultimate result with a different/simpler approach.

And now to answer your question, this is what happens:

From your browser, you send a GET request to curl.php (the name I use for your first file),

curl in that file checks cookie.txt and finds user=1, so it sends a GET request to test_cookies.php and sends the cookie with the request

test_cookies.php sees that user=1 is true, so it sends a header to  curl.php and asks it to set two cookies: user=1 and color=blue (for the first cookie this is pointless, user=1 is already set, but let's ignore this as no harm is done)

You have not set CURLOPT_COOKIEJAR option, so when curl.php receives the set cookie header it does not give a damn (nothing happens)

Next, test_cookies.php sends a redirect header to curl.php, since you have set CURLOPT_FOLLOWLOCATION,1, curl.php sends another GET request, this time to get test_cookies.html

Content of test_cookies.html is returned to curl.php,

curl_exec($ch); causes the returned content (source of test_cookies.html) be echoed back to your browser,

Your browser parses what it received and the javascript is executed. It checks for a cookie named user and does not find one, so it displays content for when there is no cookie (because there isn't).

Now, you may wonder what happens if you add:

curl_setopt($ch,CURLOPT_COOKIEJAR,dirname(__FILE__) . "/cookie.txt");

What happens is that your cookie.txt will be updated in step 4 and will have two cookies; user=1 and color=blue. But this does NOT give you the result you expect. Because header("Set-Cookie:user=1; color=blue"); is instructing curl to set the cookie, and curl does this by storing the cookies in the file you specified in CURLOPT_COOKIEJAR option. So, even though you added that option, when you reach step 8 javascript will not find that cookie, because the browser you use does not know or care about your cookie.txt, it looks somewhere else to check if a cookie exists. In Google Chrome for instance the format is SQLite and for XP the cookies are stored in %USERPROFILE%\Local Settings\Application Data\Google\Chrome\User Data\Default\Cookies.


来源: stackexchange

问:
jQuery .attribute for p tags in HTML
I want to add an attribute of 'data-class' to every paragraph in an HTML element, the 'data-class' should be set to the value of the class. I have used .attr but not able to assign the same value.
There are currently 9 paragraphs on the page with a numbered class of

p1, p2, p3 etc...

How would I just set the data-class to the same p-tag as well?

I have jQuery like this so far:

```<code>$('p').attr('data-class', 'p'}
</code>```

答:
You can use the .each(fn(index, element){}) method to iterate and set the value indiviually.

$('p').each(function(index, element) {
  $(this).attr("data-class", "p" + (index+1));
  //or
  //$(this).attr("data-class", "p" + $(this).index());

  //For Demonstartion
  $(this).text("p" + (index+1));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p></p>
<p></p>
<p></p></code>```

As an alternative .attr(key, func) can also be used.

$('p').attr("data-class", function(index, element) {
  var v = "p" + (index + 1);
  //For Demonstartion
  $(this).text(v);

  return v;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p></p>
<p></p>
<p></p></code>```

ContentLicense: CC BY-SA 4.0

Title: jQuery .attribute for p tags in HTML

Body:
I want to add an attribute of 'data-class' to every paragraph in an HTML element, the 'data-class' should be set to the value of the class. I have used .attr but not able to assign the same value.
There are currently 9 paragraphs on the page with a numbered class of

p1, p2, p3 etc...

How would I just set the data-class to the same p-tag as well?

I have jQuery like this so far:

$('p').attr('data-class', 'p'}

Body:
You can use the .each(fn(index, element){}) method to iterate and set the value indiviually.

$('p').each(function(index, element) {
  $(this).attr("data-class", "p" + (index+1));
  //or
  //$(this).attr("data-class", "p" + $(this).index());

  //For Demonstartion
  $(this).text("p" + (index+1));
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p></p>
<p></p>
<p></p>

As an alternative .attr(key, func) can also be used.

$('p').attr("data-class", function(index, element) {
  var v = "p" + (index + 1);
  //For Demonstartion
  $(this).text(v);

  return v;
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p></p>
<p></p>
<p></p>


问:
How could I upload an icon I made in Adobe Illustrator to my HTML document?
I can export the file as an SVG, but how would I actually customize it with a hover effect afterwards? I use FontAwesome for most of my icons, but I'm not sure how I'd get my own icon to carry the  tag so that I could modify it the same way as the others.

答:
I believe you can do something like this:

Possibly, you can use SVG in an ordinary IMG tag:

https://caniuse.com/svg-img

You can then add event handlers to the icon:

https://developer.mozilla.org/en-US/docs/Web/Events

I believe it's supported now.

Body:
I believe you can do something like this:

Possibly, you can use SVG in an ordinary IMG tag:

https://caniuse.com/svg-img

<img src="/static/image.svg">

You can then add event handlers to the icon:

https://developer.mozilla.org/en-US/docs/Web/Events

I believe it's supported now.


问:
Sorting Javascript Array with Split Function
I have an array that looks like this

```<code>var testArray = ['name1:13', 'name2:15', 'name3:13'];
</code>```

I would like to sort the array by the number to the right of the colon.

So far I have this:

```<code>var converted = testArray.map(
            function (item) {
                return item.split(':').map(
            function (num) {
                return parseInt(num);
          });
        })

        alert(converted)
        var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
        alert(sorted);
</code>```

That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.

Right now it returns: NAN,13,NAN,13,NAN,15

答:
Make a helper function to access the [1]st index of the split result, then in the sort callback, call that function for both and return the difference:

var testArray = ['name1:13', 'name2:15', 'name3:13'];
const getVal = str => str.split(':')[1];
testArray.sort((a, b) => getVal(a) - getVal(b));
console.log(testArray);```

Body:
I have an array that looks like this

var testArray = ['name1:13', 'name2:15', 'name3:13'];

I would like to sort the array by the number to the right of the colon.

So far I have this:

var converted = testArray.map(
            function (item) {
                return item.split(':').map(
            function (num) {
                return parseInt(num);
          });
        })

        alert(converted)
        var sorted = converted.sort(function (a, b) { return a[1] - b[1] })
        alert(sorted);

That sorts them in the correct order but I'm not sure how to pass over the first part of each string, the part to the left of the colon.

Right now it returns: NAN,13,NAN,13,NAN,15


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答:
Know your delegates. Every .Net interview I've been on has asked me about delegates. Know why they exist, know how to declare them, and how to consume them, understand what multicast delegate is. Understand how to use a multicast delegate when one of the handlers throws an exception. Know what the compiler does with a delegate. Understand how delegates can give you "automatic" asynchronous APIs. Get familiar with the newer more convenient generic delegates - Action and Func.

Bonus: delegates vs events. What are the differences? When would you use one over the other?

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: Scott Weinstein

LastEditorDisplayName: siz


问:
Complex JS onclick events from multiple elements
Ok ( the title may be misleading ) however it is the best i can come up with.

What we want to achieve ?

Ok we have an svg map, of Australia.

On click of a state on that map, the map state changes colour to selected. ( in our case Pink )
At the same time ( a useless button ) which is on page load blank, changes its value to that of the state.
Simultaneously a drop down menu, with the state names in, which on page load has the value , Please Select , changes its value to that of the state.

So : here is what happens.

User visits page and sees map. They also see drop down select box.

They can choose to either click the select dropdown, or click the map.

Scenario 1.
They click the map, and click on the state QUEENSLAND , which has a value of QLD.

On clicking the state, the state changes from grey to pink.
The select drop down, changes from Please select, to Queensland
The gray button changes from blank to QLD

Here is an image:

Ok what we have working is.

The map click events work, and propagate the grey button values, so thats all fine.
The select element works, in so far as if we select a state on the map it changes select box value.

What we dont have working is.

on click of map, we cannot propagate BOTH the select drop down and the gray button values.

we cannot on using the select drop down box, change the "select" state of the map , ie, doesnt change from grey to pink. Also it doesnt change the value of the button from its current value.

So here is some code:

Its SVG so here is the wrap element for the map.

```<code><a xlink:href="javascript:void goToOption(document.australia.state,'WA')" target="_top">
    <path
        id="WA"
        class="territory"
        fill="#a9a9a9"
        onmouseup="clickTerritory(evt)"
        d="m 38.318056,168.24244 c -4.79245,0.99662 -8.64245,1.61598 l -7,1.12612 -8.18526,4.91727 -8.18526,4.91727 -5.31474,-0.0902 c -2.92311,-0.0496 -6.88974,-0.54005 -8.81474,-1.08988 z"/></a>
</code>```

Here is the JS that controls the map click events:

```<code>function prepare(){}
function ready(){
    svgdoc = document.sv.getSVGDocument();
    svgRoot = svgdoc.documentElement;
}
function onTerritoryClick(territory){
    document.getElementById("territory-name").innerHTML=territory;
}

var selected_territory = "None";

  function init(evt) {
    if (window.svgDocument == null)
    {
        svgDocument = evt.target.ownerDocument;
    }
  }

  function clickTerritory(evt) {
    var clicked_territory;

    if (evt.target.parentNode.getAttributeNS(null, "id") != "australia-map")
    {
        // Hack to deal with groups
        clicked_territory = evt.target.parentNode;
    } else {
        clicked_territory = evt.target;
    }

    if (selected_territory != clicked_territory) {
        if (selected_territory != "None") {
            // Unselect previous territory
            selected_territory.setAttributeNS(null, "fill", "#a9a9a9");
        }
        selected_territory = clicked_territory;
        selected_territory.setAttributeNS(null, "fill", "#ec008c");
        top.onTerritoryClick(selected_territory.getAttributeNS(null, "id"));
    }
  }
</code>```

Here is the JS to handle the select box, which fires the href.

```<code>function goToOption(sel, val) {
  var opt, o = 0;
  while (opt = sel[o++]) if (opt.value == val) sel.selectedIndex = o - 1;
}
</code>```

Here is the button html:

```<code><div class="selected-state left">
    <button id="territory-name" class="mystate grayNohover button" style="position:absolute;top:250px;left:50px">ALL</button>
</div>
</code>```

Here is the select menu html:

```<code><select name="state" id="speedF" style="width:180px;">
<option value="">Please Select</option>
<option value="QLD">Queensland</option>
<option value="NT">Northern Territory</option>
<option value="WA">Western Australia</option>
<option value="SA">South Australia</option>
<option value="NSW">New South Wales</option>
<option value="VIC">Victoria</option>
<option value="ACT">A.C.T.</option>
<option value="TAS">Tasmania</option>
</select>
</code>```

sample: http://sitehelp.com.au/demos/svgmap2/

Version 2: http://dev.30.com.au/422-svg/

答:
Well, I sort of got it to work hackily by adding this function and invoking this function when the select box value changes as,

```<code><select onchange="selectChanged(this)">
</code>```

Here's the function,

```<code>function selectChanged(el) {
    var selectedState = el.value;

    var event = document.createEvent('MouseEvents');
    event.initMouseEvent("mouseup", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

    var groups = document.getElementsByTagName('g');
    for (var i = 0; i < groups.length; i++) {
        if (groups[i].id == selectedState) {
            var path = groups[i].getElementsByTagName('path')[0];
            path.dispatchEvent(event);
            return;
        }
    }
}
</code>```

It creates a mouseup event programmatically and triggers it against the <path> element that represents that state.

However, this is a very bad way to keep things in-sync. You might want to look into custom-events. With custom events, think of the DOM items as self-contained components that respond to events. The only event of interest here is the changing the state. So, the high-level interactions would be,

when select box changes, fire the stateChanged event with the value of the selected state

when user clicks on a map, fire the stateChanged event with the value of the selected state

Now the map, the gray button, and the select box, all listen to the stateChanged event. Whenever the state changes, they update themselves with the selected state. You could also provide yourself with programmatic access to change the state easily.

```<code>function changeState(newState) {
    // update map
    // update button
    // update select list
}

// add an app level event handler to listen for change of a state
app.handleEvent('stateChanged', changeState);
</code>```

Then hook the map click, and select change actions back into this changeState function.

```<code>map.onclick = function(event) {
    var stateId = // get state-code of clicked portion
    app.triggerEvent('stateChanged', stateId);
}

selectList.onchange = function(event) {
    var stateId = this.value;
    app.triggerEvent('stateChanged', stateId);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ok ( the title may be misleading ) however it is the best i can come up with.

What we want to achieve ?

Ok we have an svg map, of Australia.

On click of a state on that map, the map state changes colour to selected. ( in our case Pink )
At the same time ( a useless button ) which is on page load blank, changes its value to that of the state.
Simultaneously a drop down menu, with the state names in, which on page load has the value , Please Select , changes its value to that of the state.

So : here is what happens.

User visits page and sees map. They also see drop down select box.

They can choose to either click the select dropdown, or click the map.

Scenario 1.
They click the map, and click on the state QUEENSLAND , which has a value of QLD.

On clicking the state, the state changes from grey to pink.
The select drop down, changes from Please select, to Queensland
The gray button changes from blank to QLD

Here is an image:

Ok what we have working is.

The map click events work, and propagate the grey button values, so thats all fine.
The select element works, in so far as if we select a state on the map it changes select box value.

What we dont have working is.

on click of map, we cannot propagate BOTH the select drop down and the gray button values.

we cannot on using the select drop down box, change the "select" state of the map , ie, doesnt change from grey to pink. Also it doesnt change the value of the button from its current value.

So here is some code:

Its SVG so here is the wrap element for the map.

    <path
        id="WA"
        class="territory"
        fill="#a9a9a9"
        onmouseup="clickTerritory(evt)"
        d="m 38.318056,168.24244 c -4.79245,0.99662 -8.64245,1.61598 l -7,1.12612 -8.18526,4.91727 -8.18526,4.91727 -5.31474,-0.0902 c -2.92311,-0.0496 -6.88974,-0.54005 -8.81474,-1.08988 z"/>

Here is the JS that controls the map click events:

function prepare(){}
function ready(){
    svgdoc = document.sv.getSVGDocument();
    svgRoot = svgdoc.documentElement;
}
function onTerritoryClick(territory){
    document.getElementById("territory-name").innerHTML=territory;
}

var selected_territory = "None";

  function init(evt) {
    if (window.svgDocument == null)
    {
        svgDocument = evt.target.ownerDocument;
    }
  }

  function clickTerritory(evt) {
    var clicked_territory;

    if (evt.target.parentNode.getAttributeNS(null, "id") != "australia-map")
    {
        // Hack to deal with groups
        clicked_territory = evt.target.parentNode;
    } else {
        clicked_territory = evt.target;
    }

    if (selected_territory != clicked_territory) {
        if (selected_territory != "None") {
            // Unselect previous territory
            selected_territory.setAttributeNS(null, "fill", "#a9a9a9");
        }
        selected_territory = clicked_territory;
        selected_territory.setAttributeNS(null, "fill", "#ec008c");
        top.onTerritoryClick(selected_territory.getAttributeNS(null, "id"));
    }
  }

Here is the JS to handle the select box, which fires the href.

function goToOption(sel, val) {
  var opt, o = 0;
  while (opt = sel[o++]) if (opt.value == val) sel.selectedIndex = o - 1;
}

Here is the button html:

    <button id="territory-name" class="mystate grayNohover button" style="position:absolute;top:250px;left:50px">ALL</button>

Here is the select menu html:

<select name="state" id="speedF" style="width:180px;">
<option value="">Please Select</option>
<option value="QLD">Queensland</option>
<option value="NT">Northern Territory</option>
<option value="WA">Western Australia</option>
<option value="SA">South Australia</option>
<option value="NSW">New South Wales</option>
<option value="VIC">Victoria</option>
<option value="ACT">A.C.T.</option>
<option value="TAS">Tasmania</option>
</select>

sample: http://sitehelp.com.au/demos/svgmap2/

Version 2: http://dev.30.com.au/422-svg/

Body:
Well, I sort of got it to work hackily by adding this function and invoking this function when the select box value changes as,

<select onchange="selectChanged(this)">

Here's the function,

function selectChanged(el) {
    var selectedState = el.value;

    var event = document.createEvent('MouseEvents');
    event.initMouseEvent("mouseup", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

    var groups = document.getElementsByTagName('g');
    for (var i = 0; i < groups.length; i++) {
        if (groups[i].id == selectedState) {
            var path = groups[i].getElementsByTagName('path')[0];
            path.dispatchEvent(event);
            return;
        }
    }
}

It creates a mouseup event programmatically and triggers it against the <path> element that represents that state.

However, this is a very bad way to keep things in-sync. You might want to look into custom-events. With custom events, think of the DOM items as self-contained components that respond to events. The only event of interest here is the changing the state. So, the high-level interactions would be,

when select box changes, fire the stateChanged event with the value of the selected state

when user clicks on a map, fire the stateChanged event with the value of the selected state

Now the map, the gray button, and the select box, all listen to the stateChanged event. Whenever the state changes, they update themselves with the selected state. You could also provide yourself with programmatic access to change the state easily.

function changeState(newState) {
    // update map
    // update button
    // update select list
}

// add an app level event handler to listen for change of a state
app.handleEvent('stateChanged', changeState);

Then hook the map click, and select change actions back into this changeState function.

map.onclick = function(event) {
    var stateId = // get state-code of clicked portion
    app.triggerEvent('stateChanged', stateId);
}

selectList.onchange = function(event) {
    var stateId = this.value;
    app.triggerEvent('stateChanged', stateId);
}


问:
How can I determine installed SQL Server instances and their versions?
I'm trying to determine what instances of sql server/sql express I have installed (either manually or programmatically) but all of the examples are telling me to run a SQL query to determine this which assumes I'm already connected to a particular instance.</p>

答:
Will get the instances of SQL server
reg query "HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL"

or Use
SQLCMD -L

OwnerDisplayName: Luke

LastEditorDisplayName: Nigel Campbell


问:
Open Form and Close Form with Checkbox
So I'm trying to open and close/show and hide a form named "InfoOverLay" using a metro checkbox.
But every time the box gets checked it creates a new version of its self.

How could I change this to open and close only one version of itself?

```<code>    private void metroChecker1_CheckedChanged(object sender, bool isChecked)
    {
        if (metroChecker1.Checked == true)
        {
            InfoOverLay f = new InfoOverLay();
            f.Show();
        }
        if (metroChecker1.Checked == false)
        {
            InfoOverLay f = new InfoOverLay();
            f.Hide();
        }
</code>```

答:
```<code>private InfoOverLay f = new InfoOverLay();
private void metroChecker1_CheckedChanged(object sender, bool isChecked)
{
    if (metroChecker1.Checked == true)
    {
         f.Show();
    }
    if (metroChecker1.Checked == false)
    {
        f.Hide();
    }
}
</code>```

Title: Open Form and Close Form with Checkbox

Body:
So I'm trying to open and close/show and hide a form named "InfoOverLay" using a metro checkbox.
But every time the box gets checked it creates a new version of its self.

How could I change this to open and close only one version of itself?

    private void metroChecker1_CheckedChanged(object sender, bool isChecked)
    {
        if (metroChecker1.Checked == true)
        {
            InfoOverLay f = new InfoOverLay();
            f.Show();
        }
        if (metroChecker1.Checked == false)
        {
            InfoOverLay f = new InfoOverLay();
            f.Hide();
        }


问:
PDO: MySQL server has gone away
I have a script that does a lot of legwork nightly.

It uses a PDO prepared statement that executes in a loop.

The first few are running fine, but then I get to a point where they all fail with the error:
"MySQL server has gone away".

We run MySQL 5.0.77.

PHP Version 5.2.12

The rest of the site runs fine.

答:
I got this same error this morning after changing my DB properties in Laravel.  I'd commented out the old settings and pasted in new ones.  The problem was that the new settings where missing the DB_CONNECTION variable:

```<code>DB_CONNECTION=pgsql
</code>```

Obviously you need to add whatever connection type you are using: sqlite, mysql, ...

Title: PDO: MySQL server has gone away

Body:
I got this same error this morning after changing my DB properties in Laravel.  I'd commented out the old settings and pasted in new ones.  The problem was that the new settings where missing the DB_CONNECTION variable:

DB_CONNECTION=pgsql

Obviously you need to add whatever connection type you are using: sqlite, mysql, ...


问:
how to push UIImagePickerController into UINavigationController?
I have following coding in my Program, in AppDelegate

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    myList = [[List alloc] init];
    mySettings = [[Settings alloc] init];
    myCriteria = [[Criteria alloc] initWithStyle:UITableViewStyleGrouped];

    first = [[UINavigationController alloc] initWithRootViewController:myList];
    second = [[UINavigationController alloc] initWithRootViewController:mySettings];
    third = [[UINavigationController alloc] initWithRootViewController:myCriteria];

    myTabBar = [[UITabBarController alloc] init];

    myTabBar.view.frame = CGRectMake(0,20,320,460);

    UITabBarItem *first1 = [[UITabBarItem alloc] initWithTitle:@"List" image:[UIImage imageNamed:@"list.png"] tag:0];
    UITabBarItem *second2 = [[UITabBarItem alloc] initWithTitle:@"My Profile" image:[UIImage imageNamed:@"settings.png"] tag:1];
    UITabBarItem *third3 = [[UITabBarItem alloc] initWithTitle:@"Criteria" image:[UIImage imageNamed:@"Criteria.png"] tag:2];

    UINavigationController *localNavigationController = [[UINavigationController alloc] initWithRootViewController:myTabBar];

    first.tabBarItem = first1;
    second.tabBarItem = second2;
    third.tabBarItem = third3;

    myControllerArray = [[NSArray alloc] initWithObjects:first, second, third, nil];

    [myTabBar setViewControllers:myControllerArray];
    [myTabBar setCustomizableViewControllers:myControllerArray];

    [self.window addSubview:myTabBar.view];

    // Add the view controller's view to the window and display.
   // [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}
</code>```

Where these three are different classes, now I want to use camera and album, so when I write coding as below on a button target, it won't work

```<code>    - (void) useCamera
{

    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeCamera])
    {
        NSLog(@"If is true");
        UIImagePickerController *imagePicker =
        [[UIImagePickerController alloc] init];

    //  [self.navigationController pushViewController:imagePicker animated:YES];

        imagePicker.delegate = self;
        imagePicker.sourceType =
        UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes = [NSArray arrayWithObjects:
                                  (NSString *) kUTTypeImage,
                                  nil];
        imagePicker.allowsEditing = NO;

        [self.tabBarController setCustomizableViewControllers:[[NSArray alloc]initWithObjects:imagePicker,self,nil]];
        [self.tabBarController setViewControllers:[[NSArray alloc]initWithObjects:imagePicker,self,nil]];

        //[self presentModalViewController:imagePicker animated:YES]; I tried

        //[self.view addSubview:imagePicker.view]; I tried
        //self.view=imagePicker.view; I tried

        //[myScrollView addSubview:imagePicker]; I tried
        //[myView addSubview:imagePicker]; I tried

        [imagePicker release];

        newMedia = YES;
    }
}
</code>```

I tried all the above ways but they are not working and showing UIImagePickerController,

now what should I do

if anyone in not clear from my question, can ask me again.....

答:
Did you try presenting the UIImagePickerController through the tabBarController (UITabBarController inherits from UIViewController)? Assuming that you created a singleton for for your AppDelegate and that the tabBarController is a property of the AppController (for your convenience I added a sample code for the singleton below), the code would look something like this:

AppController.h

```<code>#import <UIKit/UIKit.h>

@interface AppController : NSObject <UIApplicationDelegate> {
  UITabBarController *tabBarController;
}
// Class methods for convenience
+ (AppController *)sharedAppController;

// *** Properties
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) UITabBarController *tabBarController;

@end
</code>```

AppController.m

```<code>#import "AppController.h"

static AppController *sharedInstance;

@implementation AppController

@synthesize window=_window;
@synthesize tabBarController;

#pragma mark - Initialization
- (id)init
{
  // Create the sharedInstance of the application
  if (sharedInstance) {
    NSLog(@"Error: You are creating a second AppController");
  }
  [super init];
  sharedInstance = self;

  return self;
}

+ (AppController *)sharedAppController
{
  return sharedInstance;
}

- (void)dealloc
{
  [_window release];
  [tabBarController release];
  [super dealloc];
}
</code>```

Now in your class, on the useCamera method call the imagePicker by doing this:

```<code>- (void)useCamera
{
  // YOUR CODE ...

  // Place image picker
  [[[AppController sharedAppController] tabBarController]
   presentModalViewController:imagePicker animated:YES];

  // YOUR RELEASE CODE ...
}
</code>```

Good luck and happy coding!

Body:
I have following coding in my Program, in AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    myList = [[List alloc] init];
    mySettings = [[Settings alloc] init];
    myCriteria = [[Criteria alloc] initWithStyle:UITableViewStyleGrouped];

    first = [[UINavigationController alloc] initWithRootViewController:myList];
    second = [[UINavigationController alloc] initWithRootViewController:mySettings];
    third = [[UINavigationController alloc] initWithRootViewController:myCriteria];

    myTabBar = [[UITabBarController alloc] init];

    myTabBar.view.frame = CGRectMake(0,20,320,460);

    UITabBarItem *first1 = [[UITabBarItem alloc] initWithTitle:@"List" image:[UIImage imageNamed:@"list.png"] tag:0];
    UITabBarItem *second2 = [[UITabBarItem alloc] initWithTitle:@"My Profile" image:[UIImage imageNamed:@"settings.png"] tag:1];
    UITabBarItem *third3 = [[UITabBarItem alloc] initWithTitle:@"Criteria" image:[UIImage imageNamed:@"Criteria.png"] tag:2];

    UINavigationController *localNavigationController = [[UINavigationController alloc] initWithRootViewController:myTabBar];

    first.tabBarItem = first1;
    second.tabBarItem = second2;
    third.tabBarItem = third3;

    myControllerArray = [[NSArray alloc] initWithObjects:first, second, third, nil];

    [myTabBar setViewControllers:myControllerArray];
    [myTabBar setCustomizableViewControllers:myControllerArray];

    [self.window addSubview:myTabBar.view];

    // Add the view controller's view to the window and display.
   // [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

Where these three are different classes, now I want to use camera and album, so when I write coding as below on a button target, it won't work

    - (void) useCamera
{

    if ([UIImagePickerController isSourceTypeAvailable:
         UIImagePickerControllerSourceTypeCamera])
    {
        NSLog(@"If is true");
        UIImagePickerController *imagePicker =
        [[UIImagePickerController alloc] init];

    //  [self.navigationController pushViewController:imagePicker animated:YES];

        imagePicker.delegate = self;
        imagePicker.sourceType =
        UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes = [NSArray arrayWithObjects:
                                  (NSString *) kUTTypeImage,
                                  nil];
        imagePicker.allowsEditing = NO;

        [self.tabBarController setCustomizableViewControllers:[[NSArray alloc]initWithObjects:imagePicker,self,nil]];
        [self.tabBarController setViewControllers:[[NSArray alloc]initWithObjects:imagePicker,self,nil]];

        //[self presentModalViewController:imagePicker animated:YES]; I tried

        //[self.view addSubview:imagePicker.view]; I tried
        //self.view=imagePicker.view; I tried

        //[myScrollView addSubview:imagePicker]; I tried
        //[myView addSubview:imagePicker]; I tried

        [imagePicker release];

        newMedia = YES;
    }
}

I tried all the above ways but they are not working and showing UIImagePickerController,

now what should I do

if anyone in not clear from my question, can ask me again.....

Body:
Did you try presenting the UIImagePickerController through the tabBarController (UITabBarController inherits from UIViewController)? Assuming that you created a singleton for for your AppDelegate and that the tabBarController is a property of the AppController (for your convenience I added a sample code for the singleton below), the code would look something like this:

AppController.h

#import <UIKit/UIKit.h>

@interface AppController : NSObject <UIApplicationDelegate> {
  UITabBarController *tabBarController;
}
// Class methods for convenience
+ (AppController *)sharedAppController;

// *** Properties
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) UITabBarController *tabBarController;

@end

AppController.m

#import "AppController.h"

static AppController *sharedInstance;

@implementation AppController

@synthesize window=_window;
@synthesize tabBarController;

#pragma mark - Initialization
- (id)init
{
  // Create the sharedInstance of the application
  if (sharedInstance) {
    NSLog(@"Error: You are creating a second AppController");
  }
  [super init];
  sharedInstance = self;

  return self;
}

+ (AppController *)sharedAppController
{
  return sharedInstance;
}

- (void)dealloc
{
  [_window release];
  [tabBarController release];
  [super dealloc];
}

Now in your class, on the useCamera method call the imagePicker by doing this:

- (void)useCamera
{
  // YOUR CODE ...

  // Place image picker
  [[[AppController sharedAppController] tabBarController]
   presentModalViewController:imagePicker animated:YES];

  // YOUR RELEASE CODE ...
}

Good luck and happy coding!


问:
Angular Routing symbol '=' was ignored in the matched URL
I have set the Routes as below in app-routing.module.ts

```<code>{ path: 'token/:token', component: AppComponent }
</code>```

The destination URL is

```<code>localhost:4200/token/23s893rhjkdsdfhjk234=
</code>```

But when I enter this url into browser and get the final url is

```<code>localhost:4200/token/23s893rhjkdsdfhjk234
</code>```

the '=' is missing,

could I know why the '=' is ignored and how to keep it in url?

Thanks

答: The solution to my answer based on ngShravil.py's link is that encode the token part of the URL which is 23s893rhjkdsdfhjk234= here by using encodeURIComponent, and decode it when route received it by using decodeURIComponent.

Body:
I have set the Routes as below in app-routing.module.ts

{ path: 'token/:token', component: AppComponent }

The destination URL is

localhost:4200/token/23s893rhjkdsdfhjk234=

But when I enter this url into browser and get the final url is

localhost:4200/token/23s893rhjkdsdfhjk234

the '=' is missing,

could I know why the '=' is ignored and how to keep it in url?

Thanks


答:
You can iterate over each p element with .each, setting the data-class attribute to the value of the class attribute (inspect the elements after running the snippet to see the change):

$(document).ready(function() {
  $('p').each(function() {
    $(this).attr('data-class', $(this).attr('class'));
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="p1">P1</p>
<p class="p2">P2</p>
<p class="p3">P3</p></code>```

Title: jQuery .attribute for p tags in HTML

Body:
You can iterate over each p element with .each, setting the data-class attribute to the value of the class attribute (inspect the elements after running the snippet to see the change):

$(document).ready(function() {
  $('p').each(function() {
    $(this).attr('data-class', $(this).attr('class'));
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="p1">P1</p>
<p class="p2">P2</p>
<p class="p3">P3</p>


问:
Delphi opencv ocvFFMpegIPCamSource to a bitmap?
There is a way to a capture/convert ocvFFMpegIPCamSource stream to a bitmap?

First I try to do this:

```<code>FrameBitmap := TBitmap.Create;
FrameBitmap.PixelFormat := pf24bit;

Image5.Picture.Graphic := IplImage2Bitmap(ocvView1.Image, FrameBitmap);
</code>```

// Image5 is my bitmap.

Obviously is geting a error, because "ocvView1.Image" is of type  "IocvImage" and the first parameter of the function IplImage2Bitmap needs a type "pIpIImage"

I missed something in the middle of the process..

Second i try using "cvImage2Bitmap":

```<code>FrameBitmap := TBitmap.Create;
FrameBitmap.PixelFormat := pf24bit;

Image5.Picture.Graphic := cvImage2Bitmap(ocvView1.Image, FrameBitmap);
</code>```

Again, needs a type "pIpIImage" and i am trying to pass a "IocvImage"

I cannot see what is missing.

There is a way to make this conversion?

I need to do this directly from ocvFFMpegIPCamSource component, or from ocvView component?

答:
I can see in sources:

```<code>IocvImage = interface
...
property IpImage: pIplImage Read GetIplImage;
</code>```

so you have to use ocvView1.Image.IpImage

Body:
There is a way to a capture/convert ocvFFMpegIPCamSource stream to a bitmap?

First I try to do this:

FrameBitmap := TBitmap.Create;
FrameBitmap.PixelFormat := pf24bit;

Image5.Picture.Graphic := IplImage2Bitmap(ocvView1.Image, FrameBitmap);

// Image5 is my bitmap.

Obviously is geting a error, because "ocvView1.Image" is of type  "IocvImage" and the first parameter of the function IplImage2Bitmap needs a type "pIpIImage"

I missed something in the middle of the process..

Second i try using "cvImage2Bitmap":

FrameBitmap := TBitmap.Create;
FrameBitmap.PixelFormat := pf24bit;

Image5.Picture.Graphic := cvImage2Bitmap(ocvView1.Image, FrameBitmap);

Again, needs a type "pIpIImage" and i am trying to pass a "IocvImage"

I cannot see what is missing.

There is a way to make this conversion?

I need to do this directly from ocvFFMpegIPCamSource component, or from ocvView component?

Body:
I can see in sources:

IocvImage = interface
...
property IpImage: pIplImage Read GetIplImage;

so you have to use ocvView1.Image.IpImage


问:
Why does moving around ios_base::sync_with_stdio(false), cin.tie(NULL) result in a memory error?
I was solving a competitive programming task when I made a bug. I placed ios_base::sync_with_stdio(false), cin.tie(NULL) into solve() instead of main().

#include <bits/stdc++.h>
using namespace std;

void solve(){
    ios_base::sync_with_stdio(false), cin.tie(NULL);
    // implementation not important
}

int main() {
    int t;
    cin >> t;
    while(t--)
        solve();
}
```

<p>This resulted in a memory error. However when I move it into the <code>main()</code> I pass with no issues:</p>

<pre class="lang-cpp prettyprint-override"><code>#include <bits/stdc++.h>
using namespace std;

void solve(){
    // implementation not important
}

int main() {
    ios_base::sync_with_stdio(false), cin.tie(NULL);
    int t;
    cin >> t;
    while(t--)
        solve();
}
</code>```

My understanding from this answer is that this disables the synchronization between C and C++ streams, and then unties cin and cout. Especially since I'm only using cin / cout, why does moving that line around cause such a drastic difference?

(in case you want the actual source)

Memory error submission

Passing submission

答:
From [ios.members.static]/2:

Effects: If any input or output operation has occurred using the standard streams prior to the call, the effect is implementation-defined. Otherwise, called with a false argument, it allows the standard streams to operate independently of the standard C streams.

Furthermore, the cppreference page notes that

If this function is called after I/O has occurred on the standard stream, the behavior is implementation-defined: implementations range from no effect to destroying the read buffer.

I'm not entirely sure what exactly happened in your case. Reading the source of libstdc++ (e.g., here), which I assume is the standard library being used, it seems that it clears the buffers. This means that it's possible that some input you were waiting for was buffered, and your program either started reading from a strange spot or the reads just failed entirely. But the precise details and why that would have caused an out of memory error is beyond me.

(It's also worth noting that the fact you're calling it in a loop doesn't seem to be the problem in this implementation, as libstdc++ only clears the buffers if you're already unsynchronised with stdio.)

Body:
I was solving a competitive programming task when I made a bug. I placed ios_base::sync_with_stdio(false), cin.tie(NULL) into solve() instead of main().

#include <bits/stdc++.h>
using namespace std;

void solve(){
    ios_base::sync_with_stdio(false), cin.tie(NULL);
    // implementation not important
}

int main() {
    int t;
    cin >> t;
    while(t--)
        solve();
}

This resulted in a memory error. However when I move it into the main() I pass with no issues:

#include <bits/stdc++.h>
using namespace std;

void solve(){
    // implementation not important
}

int main() {
    ios_base::sync_with_stdio(false), cin.tie(NULL);
    int t;
    cin >> t;
    while(t--)
        solve();
}

My understanding from this answer is that this disables the synchronization between C and C++ streams, and then unties cin and cout. Especially since I'm only using cin / cout, why does moving that line around cause such a drastic difference?

(in case you want the actual source)

Memory error submission

Passing submission


问:
Tkinter grid question
I have this code:

```<code>from Tkinter import *

class App:
    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.e = Entry(frame)
        self.e.grid(row=0, column=0)

        b = Button(frame, text='Search', command=self.well)
        b.grid(row=0, column=1)
def well(self):
    l0 = Label(Admin, text='first line')
    l0.grid(row=1)

    b0 = Button(Admin, text='F line S col')

    b0.grid(row=1, column=1)
Admin = Tk()

app = App(Admin)
Admin.mainloop()
</code>```

The ouput i get is THe Label and the Button on top of the Entry box. Does anyone know why this is? And how could i fix it to make it so that it is under the entry box?

答: What you want is to tie the label and button to the frame you've created in init, not the global Admin object. Replace frame = Frame(master) with self.frame = Frame(master), then in well(), change references of Admin to self.frame.

Title: Tkinter grid question

Body:
I have this code:

from Tkinter import *

class App:
    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.e = Entry(frame)
        self.e.grid(row=0, column=0)

        b = Button(frame, text='Search', command=self.well)
        b.grid(row=0, column=1)
def well(self):
    l0 = Label(Admin, text='first line')
    l0.grid(row=1)

    b0 = Button(Admin, text='F line S col')

    b0.grid(row=1, column=1)
Admin = Tk()

app = App(Admin)
Admin.mainloop()

The ouput i get is THe Label and the Button on top of the Entry box. Does anyone know why this is? And how could i fix it to make it so that it is under the entry box?


问:
Most common number in list from user input in for loop - Python
Here's the thing:

I want to print the most common number in a list from user input in a for loop.
The thing is that the most common number that is returned is from the last loop, not from other inputs in the loop.

How can I do so?
Here's what I tried:

```<code>import statistics
from statistics import mode

def num():
    def most_common(num):
        return (mode(num))

    grid = int(input('Number of grids: '))

    for i in range(grid):

        print('grid n°',i + 1)
        num = [int(input('1st number: ')), int(input('2nd number: ')), int(input('3rd number: '))]

    print(most_common(num))
</code>```

答:
You need to store each num you generate in a list. Here I've used grid_nums

import statistics
from statistics import mode

def num():
    def most_common(num):
        return (mode(num))

    grid = int(input('Number of grids: '))

    grid_nums = []

    for i in range(grid):
        print('grid n°',i + 1)
        num = [int(input('1st number: ')), int(input('2nd number: ')), int(input('3rd number: '))]
        grid_nums += num

    print(most_common(grid_nums))
```

Body:
Here's the thing:

I want to print the most common number in a list from user input in a for loop.
The thing is that the most common number that is returned is from the last loop, not from other inputs in the loop.

How can I do so?
Here's what I tried:

import statistics
from statistics import mode

def num():
    def most_common(num):
        return (mode(num))

    grid = int(input('Number of grids: '))

    for i in range(grid):

        print('grid n°',i + 1)
        num = [int(input('1st number: ')), int(input('2nd number: ')), int(input('3rd number: '))]

    print(most_common(num))


问:
Format for multi-level json and data extraction method with javascript
My apologies, but I am not well versed in json.  We are currently using a single level json file for date information, one file per tour package.  These are fetched via js then processed and inserted into the appropriate spots on the webpage.  What we would like to do is combined all the tours date information, plus some additional details, into a single json file that once fetched is cached on the browser for a few hours.  Basically ending up with a local flat file "database" with all tours for js to access.

Doing the single level json was fairly straight forward, but combining it into multiple levels is more daunting.  I am wondering:
  1) if there is a specific format for the data as outlined below?
  2) how to use js to extract the data from that format?

Each tour is designated by a numerical id and has number of values.  So should this first level be one or two levels (this is only the data concept, not json code):

```<code>tours -> tour_id, price1, price2, price3, duration, level, dates

tours -> tour_id -> price1, price2, price3, duration, level, dates
</code>```

The dates value will have multiple dates each with several values:

```<code>dates -> date1, date2, date3, date4, etc

each date has -> trip_code, start_date, end_date, price, spaces
</code>```

The basic functionality will be, when the page is loaded js will read the tour value from the page, then find the appropriate tour within the json file. The general values will be extracted by one function and simply inserted into the page as is using innerHTML.  The date values will be used by a different function to build strings and then those strings likewise inserted into the page.

As I read through available info, I find some folks use only braces, some use braces & brackets, various suggestions for extraction, etc. I appreciate any help towards which format / extraction method would be preferable.  And by preferrable, I mean whichever format / method puts the least workload on the browser.  Having a slightly larger file size due to extra braces or brackets is fine if it reduces the js overhead and speeds up the finished page.

While it is probably of no consequence to the answer, the json file will be built by PHP and saved as a static file on the server.

答:
You can make the multi-level object in the form

multiLevel = { [tour_id]: yourOriginal1LevelObject}

For retrieving the tour you can use

const tour = multiLevel[tour_id]

or using destructuring

const {tour_id: tour} = multiLevel

Body:
My apologies, but I am not well versed in json.  We are currently using a single level json file for date information, one file per tour package.  These are fetched via js then processed and inserted into the appropriate spots on the webpage.  What we would like to do is combined all the tours date information, plus some additional details, into a single json file that once fetched is cached on the browser for a few hours.  Basically ending up with a local flat file "database" with all tours for js to access.

Doing the single level json was fairly straight forward, but combining it into multiple levels is more daunting.  I am wondering:
  1) if there is a specific format for the data as outlined below?
  2) how to use js to extract the data from that format?

Each tour is designated by a numerical id and has number of values.  So should this first level be one or two levels (this is only the data concept, not json code):

tours -> tour_id, price1, price2, price3, duration, level, dates

tours -> tour_id -> price1, price2, price3, duration, level, dates

The dates value will have multiple dates each with several values:

dates -> date1, date2, date3, date4, etc

each date has -> trip_code, start_date, end_date, price, spaces

The basic functionality will be, when the page is loaded js will read the tour value from the page, then find the appropriate tour within the json file. The general values will be extracted by one function and simply inserted into the page as is using innerHTML.  The date values will be used by a different function to build strings and then those strings likewise inserted into the page.

As I read through available info, I find some folks use only braces, some use braces & brackets, various suggestions for extraction, etc. I appreciate any help towards which format / extraction method would be preferable.  And by preferrable, I mean whichever format / method puts the least workload on the browser.  Having a slightly larger file size due to extra braces or brackets is fine if it reduces the js overhead and speeds up the finished page.

While it is probably of no consequence to the answer, the json file will be built by PHP and saved as a static file on the server.


问:
Touch behavior not behaving the same as pressing A and D
so I have this game where you move a car left and right with "A" and "D". I use the following code to do this:
on "A" press:

```<code>characterBody.AddForce(-moveSpeed, 0, 0, ForceMode.Impulse);
</code>```

on "D" press:

```<code>characterBody.AddForce(moveSpeed, 0, 0, ForceMode.Impulse);
</code>```

I am now trying to transfer this game to mobile, using touch on both sides of the screen. Here is my code for that, using the same concepts:

```<code>void Update()
{
    int i = 0;
    //loop over every touch found
    while (i*2 < Input.touchCount)
    {
        if (Input.GetTouch(i).position.x > ScreenWidth / 2)
        {
            //move right
            //RunCharacter(1.0f);
            characterBody.velocity = Vector3.zero;

            characterBody.AddForce(moveSpeed, 0, 0, ForceMode.Impulse);
        }
        if (Input.GetTouch(i).position.x < ScreenWidth / 2)
        {
            //move left
            //RunCharacter(-1.0f);
            characterBody.velocity = Vector3.zero;
            characterBody.AddForce(-moveSpeed, 0, 0, ForceMode.Impulse);
        }
        ++i;
    }
}
</code>```

When I do this code, no matter how high or low I set the moveSpeed variable, it does not have the same effect. Here is what it is with arrow keys/"A" and "D": https://infinitecarspeeder.netlify.com.  I want it to have that effect, but however it doesn't have the ForceMode.Impulse effect, and is extremely slow to switch directions. Thank you so much!

EDIT:

Here's my code that I use for keyboard movement (works fine):

```<code>void FixedUpdate(){
    transform.Translate (Vector3.forward * Time.deltaTime * forwardSpeed);
    if(Input.GetKey(KeyCode.A)||Input.GetKey(KeyCode.LeftArrow)){

        MoveLeft();
    }
    if(Input.GetKey(KeyCode.D)||Input.GetKey(KeyCode.RightArrow)){

        MoveRight();
    }
}

public void MoveLeft()
{

    rb.AddForce(-10.75f, 0, 0, ForceMode.Impulse);
}
public void MoveRight()
{

    rb.AddForce(10.75f, 0, 0, ForceMode.Impulse);
}
</code>```

答: When using the keyboard, do you reset the character velocity to 0? That may make a difference in feeling if you don't. If you reset the velocity to zero at each update the max speed the car can move is 1.0f since it cannot accelerate. If you don't, the car can move faster than only 1.0f which would explain the difference in speed.</p>

Body:
so I have this game where you move a car left and right with "A" and "D". I use the following code to do this:
on "A" press:

characterBody.AddForce(-moveSpeed, 0, 0, ForceMode.Impulse);

on "D" press:

characterBody.AddForce(moveSpeed, 0, 0, ForceMode.Impulse);

I am now trying to transfer this game to mobile, using touch on both sides of the screen. Here is my code for that, using the same concepts:

void Update()
{
    int i = 0;
    //loop over every touch found
    while (i*2 < Input.touchCount)
    {
        if (Input.GetTouch(i).position.x > ScreenWidth / 2)
        {
            //move right
            //RunCharacter(1.0f);
            characterBody.velocity = Vector3.zero;

            characterBody.AddForce(moveSpeed, 0, 0, ForceMode.Impulse);
        }
        if (Input.GetTouch(i).position.x < ScreenWidth / 2)
        {
            //move left
            //RunCharacter(-1.0f);
            characterBody.velocity = Vector3.zero;
            characterBody.AddForce(-moveSpeed, 0, 0, ForceMode.Impulse);
        }
        ++i;
    }
}

When I do this code, no matter how high or low I set the moveSpeed variable, it does not have the same effect. Here is what it is with arrow keys/"A" and "D": https://infinitecarspeeder.netlify.com.  I want it to have that effect, but however it doesn't have the ForceMode.Impulse effect, and is extremely slow to switch directions. Thank you so much!

EDIT:

Here's my code that I use for keyboard movement (works fine):

void FixedUpdate(){
    transform.Translate (Vector3.forward * Time.deltaTime * forwardSpeed);
    if(Input.GetKey(KeyCode.A)||Input.GetKey(KeyCode.LeftArrow)){

        MoveLeft();
    }
    if(Input.GetKey(KeyCode.D)||Input.GetKey(KeyCode.RightArrow)){

        MoveRight();
    }
}

public void MoveLeft()
{

    rb.AddForce(-10.75f, 0, 0, ForceMode.Impulse);
}
public void MoveRight()
{

    rb.AddForce(10.75f, 0, 0, ForceMode.Impulse);
}


问:
Fixing "State for CSRF is not correct" with Python flask-awscognito and boto3/request
I am trying to use flask-awscognito to create a simple example server and client that authenticates with AWS Cognito but I am getting an error that I cannot find documentation on how to fix.

The server is crashing with this error:

```<code>flask_awscognito.exceptions.FlaskAWSCognitoError: State for CSRF is not correct
</code>```

This is the server code:

```<code>from flask import request, jsonify
import flask.json
from flask_awscognito import AWSCognitoAuthentication

app = flask.Flask(__name__)

app.config['AWS_DEFAULT_REGION'] = '...' # from the user pool console page
app.config['AWS_COGNITO_DOMAIN'] = '...' # just used the domain name of eventual app's domain here but I don't know if it's associate with the pool in any way. This might as well be a random string.
app.config['AWS_COGNITO_USER_POOL_ID'] = '...' # from the user pool console page
app.config['AWS_COGNITO_USER_POOL_CLIENT_ID'] = '...' # from the user pool console page
app.config['AWS_COGNITO_USER_POOL_CLIENT_SECRET'] = '' # from the user pool console page
app.config['AWS_COGNITO_REDIRECT_URL'] = 'http://localhost:5000/aws_cognito_redirect' # left this from the docs but not sure what I'll have it as in the future.

aws_auth = AWSCognitoAuthentication(app)

@app.route("/auth_test")
@aws_auth.authentication_required
def auth_test ():
    print (request.args)
    return jsonify({
        "claims" : aws_auth.claims,
        "token" : aws_auth.get_access_token(request.args)
    })

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

This is the client code:

```<code>import requests
import boto3

host = "http://127.0.0.1:5000"
region = '...' # same as in server
user_pool_id = '...' # same as in server
username = '...' # a user that is in the pool
password = '...' # correct password from the pool
app_client_id = '...' # same as in server
client = boto3.client('cognito-idp', region_name = region)
route = "/auth_test"

auth_response = client.admin_initiate_auth(
    UserPoolId = user_pool_id,
    ClientId = app_client_id,
    AuthFlow = 'ADMIN_NO_SRP_AUTH',
    AuthParameters = {
        'USERNAME' : username,
        'PASSWORD' : password
    }
)
print (auth_response)
id_token = auth_response['AuthenticationResult']['IdToken']
response = requests.get(host + route , headers = { 'Authorization': "Bearer " + id_token })
print(response.json())
</code>```

Notice I'm not passing STATE=whatever in my client as post arg. Not sure what it would be. I have Googled around for whether or not it's included in the auth response I get back. Perhaps that's required. I'm not sure I even need CSRF in my single page app with Cognito managing sessions. I'm fine disabling the server needing it or including in all clients that send the data. I just want it to work properly.

Anyone know how to fix this error? Thank you!

I've attempted to add add the following lines after Googling around for similar problems and it did not change the error message.

```<code>from flask_cors import CORS
CORS(app)
</code>```

答:
The correct value of state needs to be generated on flask server-side, and passed to AWS Cognito and then back.

You need to configure both app.config['AWS_COGNITO_DOMAIN'] and app.config['AWS_COGNITO_REDIRECT_URL'] and then you can use aws_auth.get_sign_in_url() to generate url to AWS Cognito with proper state value. For example:

```<code>@app.route('/sign_in')
def sign_in():
    return redirect(aws_auth.get_sign_in_url())
</code>```

See this example.

Body:
I am trying to use flask-awscognito to create a simple example server and client that authenticates with AWS Cognito but I am getting an error that I cannot find documentation on how to fix.

The server is crashing with this error:

flask_awscognito.exceptions.FlaskAWSCognitoError: State for CSRF is not correct

This is the server code:

from flask import request, jsonify
import flask.json
from flask_awscognito import AWSCognitoAuthentication

app = flask.Flask(__name__)

app.config['AWS_DEFAULT_REGION'] = '...' # from the user pool console page
app.config['AWS_COGNITO_DOMAIN'] = '...' # just used the domain name of eventual app's domain here but I don't know if it's associate with the pool in any way. This might as well be a random string.
app.config['AWS_COGNITO_USER_POOL_ID'] = '...' # from the user pool console page
app.config['AWS_COGNITO_USER_POOL_CLIENT_ID'] = '...' # from the user pool console page
app.config['AWS_COGNITO_USER_POOL_CLIENT_SECRET'] = '' # from the user pool console page
app.config['AWS_COGNITO_REDIRECT_URL'] = 'http://localhost:5000/aws_cognito_redirect' # left this from the docs but not sure what I'll have it as in the future.

aws_auth = AWSCognitoAuthentication(app)

@app.route("/auth_test")
@aws_auth.authentication_required
def auth_test ():
    print (request.args)
    return jsonify({
        "claims" : aws_auth.claims,
        "token" : aws_auth.get_access_token(request.args)
    })

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

This is the client code:

import requests
import boto3

host = "http://127.0.0.1:5000"
region = '...' # same as in server
user_pool_id = '...' # same as in server
username = '...' # a user that is in the pool
password = '...' # correct password from the pool
app_client_id = '...' # same as in server
client = boto3.client('cognito-idp', region_name = region)
route = "/auth_test"

auth_response = client.admin_initiate_auth(
    UserPoolId = user_pool_id,
    ClientId = app_client_id,
    AuthFlow = 'ADMIN_NO_SRP_AUTH',
    AuthParameters = {
        'USERNAME' : username,
        'PASSWORD' : password
    }
)
print (auth_response)
id_token = auth_response['AuthenticationResult']['IdToken']
response = requests.get(host + route , headers = { 'Authorization': "Bearer " + id_token })
print(response.json())

Notice I'm not passing STATE=whatever in my client as post arg. Not sure what it would be. I have Googled around for whether or not it's included in the auth response I get back. Perhaps that's required. I'm not sure I even need CSRF in my single page app with Cognito managing sessions. I'm fine disabling the server needing it or including in all clients that send the data. I just want it to work properly.

Anyone know how to fix this error? Thank you!

I've attempted to add add the following lines after Googling around for similar problems and it did not change the error message.

from flask_cors import CORS
CORS(app)

Body:
The correct value of state needs to be generated on flask server-side, and passed to AWS Cognito and then back.

You need to configure both app.config['AWS_COGNITO_DOMAIN'] and app.config['AWS_COGNITO_REDIRECT_URL'] and then you can use aws_auth.get_sign_in_url() to generate url to AWS Cognito with proper state value. For example:

@app.route('/sign_in')
def sign_in():
    return redirect(aws_auth.get_sign_in_url())

See this example.


问:
Finding the turning point (inflection point) of COVID-19 infections using inflection package
I am not sure if I have done my inflection point calculation correctly. Based on lab confirmed cumulative case data in the epicenter of the current epidemic, we have tried to identify the inflection point. I used the inflection package and calculated the inflection point as "08 Feb 2020". I have also tried to calculate the first and second directives as estimated increase each and changing rate.

Are those results from the following graphs consistent?

df<-structure(list(date = structure(c(18277, 18278, 18279, 18280,
18281, 18282, 18283, 18284, 18285, 18286, 18287, 18288, 18289,
18290, 18291, 18292, 18293, 18294, 18295, 18296, 18297, 18298,
18299, 18300, 18301, 18302, 18303, 18304, 18305, 18306, 18307),
class = "Date"),
cases = c(45, 62, 121, 198, 258, 363, 425,
        495, 572, 618, 698, 1590, 1905, 2261, 2639, 3125, 4109, 5142,
        6384, 8351, 10117, 11618, 13603, 14982, 16903, 18454, 19558,
       20630, 21960, 22961, 23621)),
class = "data.frame", row.names = c(NA, -31L))
xlb_0<- structure(c(18281, 18285, 18289, 18293,
                    18297, 18301, 18305,
                    18309), class = "Date")
library(tidyverse)
# Smooth cumulative cases over time
df$x = as.numeric(df$date)
fit_1<- loess(cases ~ x, span = 1/3, data = df)
df$case_sm <-fit_1$fitted

# use inflection to obtain inflection point
library(inflection)
guai_0 <- check_curve(df$x, df$case_sm)
check_curve(df$x, df$cases)
#> $ctype
#> [1] "convex_concave"
#>
#> $index
#> [1] 0
guai_1 <- bese(df$x, df$cases, guai_0$index)
structure(guai_1$iplast, class = "Date")
#> [1] "2020-02-08"

# Plot cumulativew numbers of cases
df %>%
  ggplot(aes(x = date, y = cases ))+
  geom_line(aes(y = case_sm), color = "red") +
  geom_point() +
  geom_vline(xintercept = guai_1$iplast) +
  labs(y = "Cumulative lab confirmed infections")
```
<p><img src="https://i.imgur.com/7JN0ufQ.png" alt="" /></p>
<pre class="lang-r prettyprint-override"><code># Daily new cases (first derivative) and changing rate (second derivative)
df$dt1 = c(0, diff(df$case_sm)/diff(df$x))
fit_2<- loess(dt1 ~ x, span = 1/3, data = df)
df$change_sm <-fit_2$fitted
df$dt2 <- c(NA, diff(df$change_sm)/diff(df$x))

df %>%
  ggplot(aes(x = date, y = dt1))+
  geom_line(aes(y = dt1,
                color = "Estimated number of new cases")) +
  geom_point(aes(y = dt2*2, color = "Changing rate")) +
  geom_line(aes(y = dt2*2, color = "Changing rate"))+
  geom_vline(xintercept = guai_1$iplast) +
  labs(y = "Estimatede number of new cases") +
  scale_x_date(breaks = xlb_0,
               date_labels = "%b%d") +
  theme(legend.title = element_blank())
#> Warning: Removed 1 rows containing missing values (geom_point).
#> Warning: Removed 1 row(s) containing missing values (geom_path).
</code>```

Created on 2020-02-17 by the reprex package (v0.3.0)

答:
I was gonna write a comment, but I was pushing the character limit.

I am not familiar with the inflection package so I am not one to judge if the 2020-02-08 is the true inflection. However, I will say this is difficult to answer with R because R is not necessarily good at calculating derivatives. If you had an estimated line equation - then you could potentially use this to plot first and second derivatives. Calculating rough delta's by doing the difference in (Y_n+1-Y_n)/(X_n+1-X_n) is never optimal because a derivate in theory is the delta of two points infinitesimally close to each other. You fundamentally cannot get a great estimate of the derivative. You can even see this because you are forced to shift this estimate to either n or n+1. Furthermore,  you would expect the inflection point of x_0 to be a local min/max in the first derivative and equal to zero in the second derivative. So I don't think your second plot helps. But this could just be due to the delta's calculated.

What I would do is first fit your data to some type of model.
In this example I'm going to use the package dr4pl to model your data to the 4 parameter logistic model.
Since the function of the 4 parameter model is well known, I can write what the first and second derivative functions should be, then plot those values using stat_function in the ggplot2 package.

```<code>library(ggplot2)
library(dr4pl)
df<-structure(list(date = structure(c(18277, 18278, 18279, 18280,
                                      18281, 18282, 18283, 18284, 18285, 18286, 18287, 18288, 18289,
                                      18290, 18291, 18292, 18293, 18294, 18295, 18296, 18297, 18298,
                                      18299, 18300, 18301, 18302, 18303, 18304, 18305, 18306, 18307),
                                    class = "Date"),
                   cases = c(45, 62, 121, 198, 258, 363, 425,
                             495, 572, 618, 698, 1590, 1905, 2261, 2639, 3125, 4109, 5142,
                             6384, 8351, 10117, 11618, 13603, 14982, 16903, 18454, 19558,
                             20630, 21960, 22961, 23621)),
              class = "data.frame", row.names = c(NA, -31L))
xlb_0<- structure(c(18281, 18285, 18289, 18293,
                    18297, 18301, 18305,
                    18309), class = "Date")

df$dat_as_num <- as.numeric(df$date)

dr4pl_obj <- dr4pl(cases~dat_as_num, data = df, init.parm = c(30000, 18300, 2, 0))
#first derivative derivation
d1_dr4pl <- function(x, theta, scale = F){
  if (any(is.na(theta))) {
    stop("One of the parameter values is NA.")
  }
  if (theta[2] <= 0) {
    stop("An IC50 estimate should always be positive.")
  }
  f <- -theta[3]*((theta[4]-theta[1])/((1+(x/theta[2])^theta[3])^2))*((x/theta[2])^(theta[3]-1))
  if(scale) {
    f <- scales::rescale(x = f, to = c(theta[4],theta[1]))
  }
  return(f)
}
#Second derivative derivation
d2_dr4pl <- function(x, theta, scale = F){
  if (any(is.na(theta))) {
    stop("One of the parameter values is NA.")
  }
  if (theta[2] <= 0) {
    stop("An IC50 estimate should always be positive.")
  }
  f <- 2*((theta[3]*(x/theta[2])^(theta[3]-1))^2)*((theta[4]-theta[1])/((1+(x/theta[2])^(theta[3]))^3))-theta[3]*(theta[3]-1)*((x/theta[2])^(theta[3]-2))*((theta[4]-theta[1])/((1+(x/theta[2])^theta[3])^2))
  if(scale) {
    f <- scales::rescale(x = f, to = c(theta[4],theta[1]))
    f <- f - f[1]
  }
  return(f)
}

ggplot(df, aes(x = dat_as_num)) +
  geom_hline(yintercept = 0) +
  [![enter image description here][1]][1]geom_point(aes(y = cases), color = "grey", alpha = .6, size = 5) +
  stat_function(fun = d1_dr4pl, args = list(theta = dr4pl_obj$parameters, scale = T), color = "red") +
  stat_function(fun = d2_dr4pl, args = list(theta = dr4pl_obj$parameters, scale = T), color = "blue") +
  stat_function(fun = dr4pl::MeanResponse, args = list(theta = dr4pl_obj$parameters), color = "gold") +
  geom_vline(xintercept = dr4pl_obj$parameters[2], linetype = "dotted") +
  theme_classic()
</code>```

As you can see, the inflection point, which is the IC50 value (theta 2) of the 4 parameter logistic model, lines up well when we approach it this way.

```<code>summary(dr4pl_obj)
#$call
#dr4pl.formula(formula = cases ~ dat_as_num, data = df, init.parm = c(30000, 18300, 2, 0))
#
#$coefficients
#               Estimate       StdErr       2.5 %      97.5 %
#Upper limit 25750.61451 4.301008e-05 25750.59681 25750.63221
#Log10(IC50) 18298.75347 4.301008e-09 18298.67889 18298.82806
#Slope        5154.35449 4.301008e-05  5154.33678  5154.37219
#Lower limit    58.48732 4.301008e-05    58.46962    58.50503
#
#attr(,"class")
#[1] "summary.dr4pl"
</code>```

Furthermore, using dr4pl, it says the IC50 value is roughly 18298.8, which is late 2020-02-06. Not too far off from the inflection value. I'm sure there may be a better model to use than the 4pl, but it was just the one that I knew I could write first and second derivatives for the purposes of answering this question.

I'm sure other coding languages are more specialized when it comes to derivatives, and can even calculate them for you so long as you start with an initial function. I think one of these languages is mathematica.

A disclaimer, I ended up scaling the first and second derivatives so that they could be plotted together. Their actual values are much larger than shown here.

Body:
I am not sure if I have done my inflection point calculation correctly. Based on lab confirmed cumulative case data in the epicenter of the current epidemic, we have tried to identify the inflection point. I used the inflection package and calculated the inflection point as "08 Feb 2020". I have also tried to calculate the first and second directives as estimated increase each and changing rate.

Are those results from the following graphs consistent?

df<-structure(list(date = structure(c(18277, 18278, 18279, 18280,
18281, 18282, 18283, 18284, 18285, 18286, 18287, 18288, 18289,
18290, 18291, 18292, 18293, 18294, 18295, 18296, 18297, 18298,
18299, 18300, 18301, 18302, 18303, 18304, 18305, 18306, 18307),
class = "Date"),
cases = c(45, 62, 121, 198, 258, 363, 425,
        495, 572, 618, 698, 1590, 1905, 2261, 2639, 3125, 4109, 5142,
        6384, 8351, 10117, 11618, 13603, 14982, 16903, 18454, 19558,
       20630, 21960, 22961, 23621)),
class = "data.frame", row.names = c(NA, -31L))
xlb_0<- structure(c(18281, 18285, 18289, 18293,
                    18297, 18301, 18305,
                    18309), class = "Date")
library(tidyverse)
# Smooth cumulative cases over time
df$x = as.numeric(df$date)
fit_1<- loess(cases ~ x, span = 1/3, data = df)
df$case_sm <-fit_1$fitted

# use inflection to obtain inflection point
library(inflection)
guai_0 <- check_curve(df$x, df$case_sm)
check_curve(df$x, df$cases)
#> $ctype
#> [1] "convex_concave"
#>
#> $index
#> [1] 0
guai_1 <- bese(df$x, df$cases, guai_0$index)
structure(guai_1$iplast, class = "Date")
#> [1] "2020-02-08"

# Plot cumulativew numbers of cases
df %>%
  ggplot(aes(x = date, y = cases ))+
  geom_line(aes(y = case_sm), color = "red") +
  geom_point() +
  geom_vline(xintercept = guai_1$iplast) +
  labs(y = "Cumulative lab confirmed infections")

# Daily new cases (first derivative) and changing rate (second derivative)
df$dt1 = c(0, diff(df$case_sm)/diff(df$x))
fit_2<- loess(dt1 ~ x, span = 1/3, data = df)
df$change_sm <-fit_2$fitted
df$dt2 <- c(NA, diff(df$change_sm)/diff(df$x))

df %>%
  ggplot(aes(x = date, y = dt1))+
  geom_line(aes(y = dt1,
                color = "Estimated number of new cases")) +
  geom_point(aes(y = dt2*2, color = "Changing rate")) +
  geom_line(aes(y = dt2*2, color = "Changing rate"))+
  geom_vline(xintercept = guai_1$iplast) +
  labs(y = "Estimatede number of new cases") +
  scale_x_date(breaks = xlb_0,
               date_labels = "%b%d") +
  theme(legend.title = element_blank())
#> Warning: Removed 1 rows containing missing values (geom_point).
#> Warning: Removed 1 row(s) containing missing values (geom_path).

Created on 2020-02-17 by the reprex package (v0.3.0)

Body:
I was gonna write a comment, but I was pushing the character limit.

I am not familiar with the inflection package so I am not one to judge if the 2020-02-08 is the true inflection. However, I will say this is difficult to answer with R because R is not necessarily good at calculating derivatives. If you had an estimated line equation - then you could potentially use this to plot first and second derivatives. Calculating rough delta's by doing the difference in (Y_n+1-Y_n)/(X_n+1-X_n) is never optimal because a derivate in theory is the delta of two points infinitesimally close to each other. You fundamentally cannot get a great estimate of the derivative. You can even see this because you are forced to shift this estimate to either n or n+1. Furthermore,  you would expect the inflection point of x_0 to be a local min/max in the first derivative and equal to zero in the second derivative. So I don't think your second plot helps. But this could just be due to the delta's calculated.

What I would do is first fit your data to some type of model.
In this example I'm going to use the package dr4pl to model your data to the 4 parameter logistic model.
Since the function of the 4 parameter model is well known, I can write what the first and second derivative functions should be, then plot those values using stat_function in the ggplot2 package.

library(ggplot2)
library(dr4pl)
df<-structure(list(date = structure(c(18277, 18278, 18279, 18280,
                                      18281, 18282, 18283, 18284, 18285, 18286, 18287, 18288, 18289,
                                      18290, 18291, 18292, 18293, 18294, 18295, 18296, 18297, 18298,
                                      18299, 18300, 18301, 18302, 18303, 18304, 18305, 18306, 18307),
                                    class = "Date"),
                   cases = c(45, 62, 121, 198, 258, 363, 425,
                             495, 572, 618, 698, 1590, 1905, 2261, 2639, 3125, 4109, 5142,
                             6384, 8351, 10117, 11618, 13603, 14982, 16903, 18454, 19558,
                             20630, 21960, 22961, 23621)),
              class = "data.frame", row.names = c(NA, -31L))
xlb_0<- structure(c(18281, 18285, 18289, 18293,
                    18297, 18301, 18305,
                    18309), class = "Date")

df$dat_as_num <- as.numeric(df$date)

dr4pl_obj <- dr4pl(cases~dat_as_num, data = df, init.parm = c(30000, 18300, 2, 0))
#first derivative derivation
d1_dr4pl <- function(x, theta, scale = F){
  if (any(is.na(theta))) {
    stop("One of the parameter values is NA.")
  }
  if (theta[2] <= 0) {
    stop("An IC50 estimate should always be positive.")
  }
  f <- -theta[3]*((theta[4]-theta[1])/((1+(x/theta[2])^theta[3])^2))*((x/theta[2])^(theta[3]-1))
  if(scale) {
    f <- scales::rescale(x = f, to = c(theta[4],theta[1]))
  }
  return(f)
}
#Second derivative derivation
d2_dr4pl <- function(x, theta, scale = F){
  if (any(is.na(theta))) {
    stop("One of the parameter values is NA.")
  }
  if (theta[2] <= 0) {
    stop("An IC50 estimate should always be positive.")
  }
  f <- 2*((theta[3]*(x/theta[2])^(theta[3]-1))^2)*((theta[4]-theta[1])/((1+(x/theta[2])^(theta[3]))^3))-theta[3]*(theta[3]-1)*((x/theta[2])^(theta[3]-2))*((theta[4]-theta[1])/((1+(x/theta[2])^theta[3])^2))
  if(scale) {
    f <- scales::rescale(x = f, to = c(theta[4],theta[1]))
    f <- f - f[1]
  }
  return(f)
}

ggplot(df, aes(x = dat_as_num)) +
  geom_hline(yintercept = 0) +
  [![enter image description here][1]][1]geom_point(aes(y = cases), color = "grey", alpha = .6, size = 5) +
  stat_function(fun = d1_dr4pl, args = list(theta = dr4pl_obj$parameters, scale = T), color = "red") +
  stat_function(fun = d2_dr4pl, args = list(theta = dr4pl_obj$parameters, scale = T), color = "blue") +
  stat_function(fun = dr4pl::MeanResponse, args = list(theta = dr4pl_obj$parameters), color = "gold") +
  geom_vline(xintercept = dr4pl_obj$parameters[2], linetype = "dotted") +
  theme_classic()

As you can see, the inflection point, which is the IC50 value (theta 2) of the 4 parameter logistic model, lines up well when we approach it this way.

summary(dr4pl_obj)
#$call
#dr4pl.formula(formula = cases ~ dat_as_num, data = df, init.parm = c(30000, 18300, 2, 0))
#
#$coefficients
#               Estimate       StdErr       2.5 %      97.5 %
#Upper limit 25750.61451 4.301008e-05 25750.59681 25750.63221
#Log10(IC50) 18298.75347 4.301008e-09 18298.67889 18298.82806
#Slope        5154.35449 4.301008e-05  5154.33678  5154.37219
#Lower limit    58.48732 4.301008e-05    58.46962    58.50503
#
#attr(,"class")
#[1] "summary.dr4pl"

Furthermore, using dr4pl, it says the IC50 value is roughly 18298.8, which is late 2020-02-06. Not too far off from the inflection value. I'm sure there may be a better model to use than the 4pl, but it was just the one that I knew I could write first and second derivatives for the purposes of answering this question.

I'm sure other coding languages are more specialized when it comes to derivatives, and can even calculate them for you so long as you start with an initial function. I think one of these languages is mathematica.

A disclaimer, I ended up scaling the first and second derivatives so that they could be plotted together. Their actual values are much larger than shown here.


问:
Dynamically adding data from an API to a table with React
https://codesandbox.io/s/reverent-hermann-so8dg

I attempted mapping through a list array that I created and I can add an
 with what the user typed. But I have all of my info in a table that I would like to add rows after each API call.

答:
Based on your code I have tried to work out your aim.
So using what you had I updated your table list file and the Nutrition file.

The way I made your table dynamic was instead of passing a food item into your TableList component, it takes a list of food objects that it then maps through to create a row for each one. The foodList is a modified version of your list, this is where an object containing your food information is added

The structure of the food object is:

```<code>  const foodObject = {
                calories: responseData.nf_calories,
                protein: responseData.nf_protein,
                food: responseData.item_name
              };
</code>```

And adding it to the list is done like so:

```<code>          setFoodList([...foodList, foodObject]);
</code>```

where the foodObject is added to the previous food list via destructuring.

The updated code sand box is here
https://codesandbox.io/s/infallible-morse-migmn?fontsize=14&hidenavigation=1&theme=dark

Hopefully you could look at the changes and find something helpful

Good luck :D

If you need any other help or explanation, feel free to ask, happy to help :)

Body:
Based on your code I have tried to work out your aim.
So using what you had I updated your table list file and the Nutrition file.

The way I made your table dynamic was instead of passing a food item into your TableList component, it takes a list of food objects that it then maps through to create a row for each one. The foodList is a modified version of your list, this is where an object containing your food information is added

The structure of the food object is:

  const foodObject = {
                calories: responseData.nf_calories,
                protein: responseData.nf_protein,
                food: responseData.item_name
              };

And adding it to the list is done like so:

          setFoodList([...foodList, foodObject]);

where the foodObject is added to the previous food list via destructuring.

The updated code sand box is here
https://codesandbox.io/s/infallible-morse-migmn?fontsize=14&hidenavigation=1&theme=dark

Hopefully you could look at the changes and find something helpful

Good luck :D

If you need any other help or explanation, feel free to ask, happy to help :)


问:
range along row or column of tensor in tensorflow
In tensorflow, how can I calculate the the range along rows or columns of a tensor?
Where range is max - min.

In Matlab this can be done with 'range'

```<code>a=[ 1 2 3; 4 5 6]
range(a) = [3 3 3] %this is the range along columns of a
range(a') = [2 2]  %range along rows of a
</code>```

答:
Use tf.get_shape() to get the dimensions of a tensor which you can further use in range function:

```<code>import tensorflow as tf

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
>>> TensorShape([Dimension(2), Dimension(3)])

print(c.get_shape()[0].value)
>>> 2
</code>```

Body:
In tensorflow, how can I calculate the the range along rows or columns of a tensor?
Where range is max - min.

In Matlab this can be done with 'range'

a=[ 1 2 3; 4 5 6]
range(a) = [3 3 3] %this is the range along columns of a
range(a') = [2 2]  %range along rows of a

Body:
Use tf.get_shape() to get the dimensions of a tensor which you can further use in range function:

import tensorflow as tf

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
>>> TensorShape([Dimension(2), Dimension(3)])

print(c.get_shape()[0].value)
>>> 2


问:
Without data parameter with Firebase Functions for Android
I tried this code at Android.

Initialize Dependency

private FirebaseFunctions mFunctions;
```

<p>In <strong>onCreate()</strong></p>

<pre class="lang-java prettyprint-override"><code>mFunctions = FirebaseFunctions.getInstance();
</code>```

Additional Function

Map<String, Object> data = new HashMap<>();
data.put("key1", "value1");
data.put("key2", "value2");

mFunctions.getHttpsCallable("HTTP_EVENT_NAME")
    .call(data)
    .continueWith(new Continuation<HttpsCallableResult, String>() {
        @Override
        public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
            String result = (String) task.getResult().getData();
            return result;
        }
    });
```

<p>It works fine!</p>

<p>But when I check the HTTP Request's <strong>Body</strong>, I can find this.</p>

```{ data: {key1: 'value1', key2: 'value2'} }
```

<hr>

<p>If I want to make it without <code>data</code> like this.</p>

```{ key1: 'value1', key2: 'value2'}
```

What should I do?

答:
Callable functions in the client-side SDK are made to work with Callable Cloud Functions on the server. The wire protocol is defined, and cannot be modified to fit other needs.

If you want full control over the format of the function parameters in the request body, you should implement a regular HTTP(S) Cloud Function. You'll also have to implement your own client-side client in that case.

Body:
I tried this code at Android.

Initialize Dependency

private FirebaseFunctions mFunctions;

In onCreate()

mFunctions = FirebaseFunctions.getInstance();

Additional Function

Map<String, Object> data = new HashMap<>();
data.put("key1", "value1");
data.put("key2", "value2");

mFunctions.getHttpsCallable("HTTP_EVENT_NAME")
    .call(data)
    .continueWith(new Continuation<HttpsCallableResult, String>() {
        @Override
        public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
            String result = (String) task.getResult().getData();
            return result;
        }
    });

It works fine!

But when I check the HTTP Request's Body, I can find this.

{ data: {key1: 'value1', key2: 'value2'} }

If I want to make it without data like this.

{ key1: 'value1', key2: 'value2'}

What should I do?


问:
Koa.js: ctx.setcookie() fails to set cookie
In my server.js code below I am setting up a middleware that should pass through Shopify OAuth and then redirect to the / route.

The '/' route, and its redirect url, are loaded in an iframe inside the shopify Admin area. I do see the page that / redirects to. But no cookies are present.

Related to the cookie settings, I am accessing this route in a web browser and on a secure https connection.

I am using Google Chrome Version 79.0.3945.88 (Official Build) (64-bit). I'm also using EditThisCookie browser extension to see the cookies that are present for the domain.

Can anyone tell why the cookies I am trying to set in server.js are failing to set?

```<code>import "isomorphic-fetch";
require("dotenv").config();

import Koa from "koa";
import Router from "koa-router";
import session from "koa-session";
import authorizeForShopify, {verifyRequest} from "@shopify/koa-shopify-auth";

const koa = new Koa();
const router = new Router();

const {SHOPIFY_BUYUSED_API_KEY, SHOPIFY_BUYUSED_API_SECRET, SHOPIFY_BUYUSED_SCOPES} = process.env;

koa.keys = [SHOPIFY_BUYUSED_API_SECRET];
koa.use(session({secure: true, sameSite: "none"}, koa));

////// Shopify OAuth //////
koa.use(authorizeForShopify({
  apiKey : SHOPIFY_BUYUSED_API_KEY
  , secret : SHOPIFY_BUYUSED_API_SECRET
  , scopes : SHOPIFY_BUYUSED_SCOPES.split(",")
  , afterAuth(ctx: Koa.Context): void {
    console.log(`=====inside afterAuth()=====`); // I don't see this log statement
    const {shop, accessToken} = ctx.session;

    console.log({ // also I do not see this one
      message : "from inside afterAuth()"
      , shop
      , accessToken
    });

    // cookie setting
    const cookieOptions = {
      httpOnly: true,
      secure: true,
      signed: true,
      overwrite: true
    };

    // neither cookie is present in EditThisCookie
    ctx.cookie.set("buyUsed_shopName", shop, cookieOptions);
    ctx.cookie.set("buyUsed_generalToken", accessToken, cookieOptions);

    ctx.redirect("/");
  }
}));

////// Routing //////

router.get('/', async ctx => {
  // ctx.body = "Koa server running, '/' route triggered"
  ctx.redirect("https://storage.cloud.google.com/buy_used/consoleLog.js");
});

koa.use(verifyRequest());

koa.use(router.routes())
  .use(router.allowedMethods());

const port: number = Number(process.env.PORT) || 8080;

koa.listen(port, undefined, undefined, () => console.log(`=====Koa listening on port ${port.toString()}=====`));

</code>```

答:
In the case of Koa, the methods to work with cookies are ctx.cookies.get and ctx.cookies.set.  Thus, the lines should be changed to:

```<code>// neither cookie is present in EditThisCookie
ctx.cookies.set("buyUsed_shopName", shop, cookieOptions);
ctx.cookies.set("buyUsed_generalToken", accessToken, cookieOptions);
</code>```

Body:
In my server.js code below I am setting up a middleware that should pass through Shopify OAuth and then redirect to the / route.

The '/' route, and its redirect url, are loaded in an iframe inside the shopify Admin area. I do see the page that / redirects to. But no cookies are present.

Related to the cookie settings, I am accessing this route in a web browser and on a secure https connection.

I am using Google Chrome Version 79.0.3945.88 (Official Build) (64-bit). I'm also using EditThisCookie browser extension to see the cookies that are present for the domain.

Can anyone tell why the cookies I am trying to set in server.js are failing to set?

import "isomorphic-fetch";
require("dotenv").config();

import Koa from "koa";
import Router from "koa-router";
import session from "koa-session";
import authorizeForShopify, {verifyRequest} from "@shopify/koa-shopify-auth";

const koa = new Koa();
const router = new Router();

const {SHOPIFY_BUYUSED_API_KEY, SHOPIFY_BUYUSED_API_SECRET, SHOPIFY_BUYUSED_SCOPES} = process.env;

koa.keys = [SHOPIFY_BUYUSED_API_SECRET];
koa.use(session({secure: true, sameSite: "none"}, koa));

////// Shopify OAuth //////
koa.use(authorizeForShopify({
  apiKey : SHOPIFY_BUYUSED_API_KEY
  , secret : SHOPIFY_BUYUSED_API_SECRET
  , scopes : SHOPIFY_BUYUSED_SCOPES.split(",")
  , afterAuth(ctx: Koa.Context): void {
    console.log(`=====inside afterAuth()=====`); // I don't see this log statement
    const {shop, accessToken} = ctx.session;

    console.log({ // also I do not see this one
      message : "from inside afterAuth()"
      , shop
      , accessToken
    });

    // cookie setting
    const cookieOptions = {
      httpOnly: true,
      secure: true,
      signed: true,
      overwrite: true
    };

    // neither cookie is present in EditThisCookie
    ctx.cookie.set("buyUsed_shopName", shop, cookieOptions);
    ctx.cookie.set("buyUsed_generalToken", accessToken, cookieOptions);

    ctx.redirect("/");
  }
}));

////// Routing //////

router.get('/', async ctx => {
  // ctx.body = "Koa server running, '/' route triggered"
  ctx.redirect("https://storage.cloud.google.com/buy_used/consoleLog.js");
});

koa.use(verifyRequest());

koa.use(router.routes())
  .use(router.allowedMethods());

const port: number = Number(process.env.PORT) || 8080;

koa.listen(port, undefined, undefined, () => console.log(`=====Koa listening on port ${port.toString()}=====`));

Body:
In the case of Koa, the methods to work with cookies are ctx.cookies.get and ctx.cookies.set.  Thus, the lines should be changed to:

// neither cookie is present in EditThisCookie
ctx.cookies.set("buyUsed_shopName", shop, cookieOptions);
ctx.cookies.set("buyUsed_generalToken", accessToken, cookieOptions);