问:
Property must be a valid Date in grails
I have used incomeDate as Date and trying to submit as string '2015-08-02'. And I have trying to submit it different way but getting error.

Domain

```<code>class IncomeTransaction {
    Date incomeDate
    ------
}
</code>```

.gsp

```<code><input type="text" name="incomeDate" placeholder="yyyy-mm-dd" />
</code>```

Controller:

```<code>String dateString = params.incomeDate
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = formatter.parse(dateString);
incomeTransactionInstance.incomeDate = myDate

// get error like ---- Property incomeDate be a valid Date in grails

/*Another way*/
//params.incomeDate = new Date().parse( 'yyyy-MM-dd', params.incomeDate )
// get error like ---- unparsable
</code>```

答:
A global setting can be configured in grails-app/conf/application.groovy (for Grails 3, and at grails-app/conf/Config.groovy for Grails 2) to define date formats which will be used in the application wide when binding to Date, like so:

```<code>grails.databinding.dateFormats = ['yyyy-MM-dd']
</code>```

Hope this helps.

Title: Property must be a valid Date in grails

Body:
I have used incomeDate as Date and trying to submit as string '2015-08-02'. And I have trying to submit it different way but getting error.

Domain

class IncomeTransaction {
    Date incomeDate
    ------
}

.gsp

<input type="text" name="incomeDate" placeholder="yyyy-mm-dd" />

Controller:

String dateString = params.incomeDate
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = formatter.parse(dateString);
incomeTransactionInstance.incomeDate = myDate

// get error like ---- Property incomeDate be a valid Date in grails

/*Another way*/
//params.incomeDate = new Date().parse( 'yyyy-MM-dd', params.incomeDate )
// get error like ---- unparsable

Body:
A global setting can be configured in grails-app/conf/application.groovy (for Grails 3, and at grails-app/conf/Config.groovy for Grails 2) to define date formats which will be used in the application wide when binding to Date, like so:

grails.databinding.dateFormats = ['yyyy-MM-dd']

Hope this helps.


来源: stackexchange

问:
Solve differential equation in Python when I don't know the derivative analytically
I'm trying to solve a first-order ODE in Python:

where Gamma and u are square matrices.
I don't explicitly know u(t) at all times, but I do know it at discrete timesteps from doing an earlier calculation.

Every example I found of Python's solvers online (e.g. this one for scipy.integrate.odeint and scipy.integrate.ode) know the expression for the derivative analytically as a function of time.

Is there a way to call these (or other differential equation solvers) without knowing an analytic expression for the derivative?

For now, I've written my own Runge-Kutta solver and jitted it with numba.

答:
You can use any of the SciPy interpolation methods, such as interp1d, to create a callable function based on your discrete data, and pass it to odeint. Cubic spline interpolation,

```<code>f = interp1d(x, y, kind='cubic')
</code>```

should be good enough.

ContentLicense: CC BY-SA 3.0

Body:
You can use any of the SciPy interpolation methods, such as interp1d, to create a callable function based on your discrete data, and pass it to odeint. Cubic spline interpolation,

f = interp1d(x, y, kind='cubic')

should be good enough.


问:
JSON API's in ruby on rails
I need to send post request from the client(now i am checking that through postman).I don't know how to accept the  data which is coming as JSON format and store that into table?.when i send the request, It shows</p>

```<code>ActionController::InvalidAuthenticityToken in TopicsController#create
</code>```

答:
Looks to me like your controller is expecting an auth token.

You can skip this for certain actions using:

skip_before_action :verify_authenticity_token, only: [:action_name_goes_here]

This is intended to prevent cross site request forgery, so be careful with it. The official docs are here: http://guides.rubyonrails.org/security.html#csrf-countermeasures.

Here's the important part:

By default, Rails includes an unobtrusive scripting adapter, which
  adds a header called X-CSRF-Token with the security token on every
  non-GET Ajax call. Without this header, non-GET Ajax requests won't be
  accepted by Rails. When using another library to make Ajax calls, it
  is necessary to add the security token as a default header for Ajax
  calls in your library. To get the token, have a look at  tag printed by <%=
  csrf_meta_tags %> in your application view.

Title: JSON API's in ruby on rails

Body:
I need to send post request from the client(now i am checking that through postman).I don't know how to accept the  data which is coming as JSON format and store that into table?.when i send the request, It shows

ActionController::InvalidAuthenticityToken in TopicsController#create


问:
AngularJS - how to get all elements by querySelector and disable links
I'm trying to make a simple step-by-step wizard.

HTML code for that (in index.html) looks like

```<code><div class="stepwizard col-md-offset-3">
    <div class="stepwizard-row setup-panel">
      <div class="stepwizard-step">
        <a href="/" type="button" class="btn btn-default btn-circle" id="step-1">1</a>
        <p>Start</p>
      </div>
      <div class="stepwizard-step">
        <a href="/registration" type="button" class="btn btn-default btn-circle" disabled="disabled" id="step-2">2</a>
        <p>Registration</p>
      </div>
      <div class="stepwizard-step">
        <a href="/tutorial" type="button" class="btn btn-default btn-circle" disabled="disabled" id="step-3">3</a>
        <p>Tutorial</p>
      </div>
      <div class="stepwizard-step">
        <a href="/thank-you" type="button" class="btn btn-default btn-circle" disabled="disabled" id="step-4">4</a>
        <p>Finish</p>
      </div>
    </div>
  </div>
</code>```

Code above work fine when was triggered by jQuery which looks like
      function stepnext(n){

```<code>function step(n){
    if(n != 0){
        $(".stepwizard-row a").removeClass('btn-primary');
        $(".stepwizard-row a").addClass('btn-default');
        $('.stepwizard-row #step-'+n+'').removeClass('btn-default');
        $('.stepwizard-row #step-'+n+'').addClass('btn-primary');
    }
}
</code>```

but I have moved it to each step controller and triggers it as

```<code>var stepReset = angular.element( document.querySelector( '.stepwizard-row a' ) );
stepReset.removeClass('btn-primary');
stepReset.addClass('btn-default');

var stepActive = angular.element( document.querySelector( '#step-1' ) );
stepActive.removeClass('btn-default');
stepActive.addClass('btn-primary');
</code>```

and so on for each #step-X

It works fine for selecting on each step for btn-primary but then when I follow to next step like from 2 to 3 is not reseting class from step 2 to btn-default just taking effect on first element from .stepwizard-row a which is step#1.

My question is how I can select all DOM elements for .stepwizard-row a?

Another question is related to have links "disabled" until landed or passed particular step. I have set them to disabled="disabled" but AngularJS let me click on them and skip steps.

答:
Manually querying elements from the DOM is rarely needed in AngularJS, and in the rare cases where you need this functionality a directive is more suited.

A better way to do this is to use ngClass and add/remove the btn-default and btn-primary classes based on an expression, like so:

```<code><a href="/" type="button" class="btn btn-circle" ng-class="{'btn-default': notCurrentStep(), 'btn-primary': currentStep()}" id="step-1">1</a>
</code>```

You can then implement the notCurrentStep and currentStep functions in your controller based on your needs.

As for the disabled attribute and as @Knitesh mentioned, it's better to use ngDisabled so that you can dynamically add/remove the disabled attribute based on an expression.

Body:
I'm trying to make a simple step-by-step wizard.

HTML code for that (in index.html) looks like

        1

Start

        2

Registration

        3

Tutorial

        4

Finish

Code above work fine when was triggered by jQuery which looks like
      function stepnext(n){

function step(n){
    if(n != 0){
        $(".stepwizard-row a").removeClass('btn-primary');
        $(".stepwizard-row a").addClass('btn-default');
        $('.stepwizard-row #step-'+n+'').removeClass('btn-default');
        $('.stepwizard-row #step-'+n+'').addClass('btn-primary');
    }
}

but I have moved it to each step controller and triggers it as

var stepReset = angular.element( document.querySelector( '.stepwizard-row a' ) );
stepReset.removeClass('btn-primary');
stepReset.addClass('btn-default');

var stepActive = angular.element( document.querySelector( '#step-1' ) );
stepActive.removeClass('btn-default');
stepActive.addClass('btn-primary');

and so on for each #step-X

It works fine for selecting on each step for btn-primary but then when I follow to next step like from 2 to 3 is not reseting class from step 2 to btn-default just taking effect on first element from .stepwizard-row a which is step#1.

My question is how I can select all DOM elements for .stepwizard-row a?

Another question is related to have links "disabled" until landed or passed particular step. I have set them to disabled="disabled" but AngularJS let me click on them and skip steps.

Body:
Manually querying elements from the DOM is rarely needed in AngularJS, and in the rare cases where you need this functionality a directive is more suited.

A better way to do this is to use ngClass and add/remove the btn-default and btn-primary classes based on an expression, like so:

<a href="/" type="button" class="btn btn-circle" ng-class="{'btn-default': notCurrentStep(), 'btn-primary': currentStep()}" id="step-1">1</a>

You can then implement the notCurrentStep and currentStep functions in your controller based on your needs.

As for the disabled attribute and as @Knitesh mentioned, it's better to use ngDisabled so that you can dynamically add/remove the disabled attribute based on an expression.


问:
Passing merchant key and salt in website
I have integrated payu in my website for transaction. I have a doubt, in their dev guide they pass merchant key, salt, hash etc. to form parameters. Now, if anybody does an inspect element in my website then he/she can see those parameters.I want to know the best way people use payu apis and how do they make sure that mechant id, salt remains on server only. My backend is in django and front end in angular js</p>

答:
I've not used Payu, but sensitive information like this should be stored in the Django settings files (which can only be read if you have access to the server) and only accessed by Django (rather than put in JS files which can be read by anyone).

The normal way to implement something like this would be to have the form POST to a Django View which retrieves the sensitive information from the settings files and then calls the API.


问:
Dark color scheme for Eclipse
Is Eclipse at all theme-able? I would like to install a dark color scheme for it, since I much prefer white text on dark background than the other way around.</p>

答:
Easiest way:  change the Windows Display Properties main window background color.  I went to Appearance tab, changed to Silver scheme, clicked Advanced, clicked on "Active Window" and changed Color 1 to a light gray.  All Eclipse views softened.

Since Luna (4.4) there seems to be a full Dark them in

Window -> Preferences -> General -> Appearance -> Theme -> Dark

OwnerDisplayName: Bartosz Radaczyński

Title: Dark color scheme for Eclipse

LastEditorDisplayName: Bartosz Radaczyński


问:
Comparator as lambda
I've the following method in Java library:

public void setColumnComparator(final int columnIndex, final Comparator<T> columnComparator)
```

<p>Idea says it has the following prorotype:</p>

```setColumnComparator(columnIndex: Int, columnComparator: ((Any!, Any!) -> Int)!)
```

<p>How can I use it? I know it will be <code>String</code>, so I want something like this, but it doesn't compile.</p>

```setColumnComparator(0, Comparator<String> { a, b -> a.compareTo(b) }
```

答:
If you look more carefully, you need to pass comparator which compares complete values, not values in the column. So let's say the type of data in your table is Car (so that you have a SortableTableView<Car>) and the first column contains model names. Then you'd write

```<code>setColumnComparator(0, { a, b -> a.modelName.compareTo(b.modelName) }
</code>```

Or better:

```<code>setColumnComparator(0, compareBy({ it.modelName })
</code>```

(see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/compare-by.html)

From the signature IDEA shows, you might have a SortableTableView<Any> or a SortableTableView<*> instead. This really should be changed to a more specific type. But even without it, if you could have a Car or a Book:

```<code>compareBy({ (it as? Car)?.modelName }, { (it as? Book)?.title })
</code>```

Title: Comparator as lambda

Body:
I've the following method in Java library:

public void setColumnComparator(final int columnIndex, final Comparator<T> columnComparator)

Idea says it has the following prorotype:

setColumnComparator(columnIndex: Int, columnComparator: ((Any!, Any!) -> Int)!)

How can I use it? I know it will be String, so I want something like this, but it doesn't compile.

setColumnComparator(0, Comparator<String> { a, b -> a.compareTo(b) }

Body:
If you look more carefully, you need to pass comparator which compares complete values, not values in the column. So let's say the type of data in your table is Car (so that you have a SortableTableView<Car>) and the first column contains model names. Then you'd write

setColumnComparator(0, { a, b -> a.modelName.compareTo(b.modelName) }

Or better:

setColumnComparator(0, compareBy({ it.modelName })

(see https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/compare-by.html)

From the signature IDEA shows, you might have a SortableTableView<Any> or a SortableTableView<*> instead. This really should be changed to a more specific type. But even without it, if you could have a Car or a Book:

compareBy({ (it as? Car)?.modelName }, { (it as? Book)?.title })


问:
How to prevent Zero from appearing in Calculator?
I am writing a FreeCodeCamp Calculator. The problem that I am working on right now is repeating operators. For example, if I press "5" and then "+", but changed my mind and pressed "-", the history area should display "5-" instead of "5+". However, with my code, it display "5+0-". Therefore, I realize that I will need to fix the "Zero" problem as well.

The list I wanted to do for the "Zero" problem are:

If one press "0", allow it to appear in the history area. For example, if someone press "0" and then the operator, it should appear in the history area as "0-".

Otherwise, if someone press operator first without putting in any number, stop this method

Here is my code from this Codepen:

$(document).ready(function() {

  var mainMath = "0";
  var subMath = "0";
  var finalset = "";
  var subMatharray = [];
  var oppArray = [];
  var equalPressed = false;
  var prevKey = "";
  update();

  $("button").click(function(){
    calculate($(this).attr("value"));
  });

  function calculate(keyitem) {
    console.log("buttonpress: " + keyitem);
    switch(keyitem) {
      case "clear":
        clearScreen();
        break;
      case "%":
        percentageScreen();
        break;
      case "/":
      case "*":
      case "+":
      case "-":
        addOperator(keyitem);
        break;
      case "plusminus":
        plusminusScreen();
        break;
      case "0":
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        addNumber(keyitem);
        break;
      case ".":
        addDecimal(keyitem);
        break;
      case "=":
        solveEqual(keyitem);
        break;
    }
    update();
    };

  function clearScreen() {
     mainMath = "0";
     subMath = "0";
     prevKey = "";
     subMatharray = [];
     oppArray = [];
    if(mainMath.length > 0){
      $(".entry").css("font-size", "4em");
    }
    console.log("clearMain: " + mainMath);
    console.log("clearSub: " + subMath);
  };

  function plusminusScreen() {
     mainMath = -1 * mainMath;
    finalset = mainMath;
    console.log("plusminusMain: " + mainMath);
    console.log("plusminusFinal: " + finalset);
  };

  function addNumber(keyitem) {
    if (mainMath == "0"){
      mainMath = keyitem/*mainMath.replace("0", keyitem);*/
      finalset = mainMath;
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }
    if (equalPressed == true){
      mainMath = keyitem;
      subMath = "0";
      subMatharray = [];
      equalPressed = false;
      console.log("addNumberEqualmain: " + mainMath);
    }
    mainMath+=keyitem;
    finalset = mainMath;

    console.log("addedMain: " + mainMath);
    console.log("addedFinalset: " + finalset);
    console.log("addedarray: " + subMatharray);

    if(mainMath.length > 8){
      $(".entry").css("font-size", "1.5em");
    }

  };

  function addOperator(keyitem){

    if (equalPressed == true){
      subMatharray = [];
      equalPressed = false;
      console.log("addOpEqualarray: " + subMatharray);
    }
    /*if (mainMath == "0" && finalset !== "0"){
      mainMath = "0";
      subMatharray.push(keyitem);
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }*/

    oppArray.push(keyitem);
    console.log("addOpArray: " + oppArray);
    var opkeyitem = "";

    subMatharray.push(mainMath);
    prevKey = "numbertest";

    if(prevKey == "numbertest") {
      subMatharray.push(keyitem);
      prevKey = "operatortest";
      console.log("addOpArraySubArrayElse: " + subMatharray);
      console.log("addOpArrayPrevKeyElse: " + prevKey);
    } /*else if (oppArray.length > 1 && prevKey == "operatortest") {
      subMatharray.pop();
      subMatharray.push("droubletest");
      oppArray = [];
      console.log("addOpArraySubArray: " + subMatharray);
      console.log("addOpArrayPrevKey: " + prevKey);
    } /*else if(prevKey == "numbertest") {
      subMatharray.push(keyitem);
      prevKey = "operatortest";
      console.log("addOpArraySubArrayElse: " + subMatharray);
      console.log("addOpArrayPrevKeyElse: " + prevKey);
    }*/

    subMath = subMatharray.join("");
    mainMath = "0";
    prevKey = keyitem;
    console.log("addOpSub: " + subMath);
    console.log("addOpMain: " + mainMath);
    console.log("addOpMainarray: " + subMatharray);
    console.log("equaltrueTest: " + equalPressed);
  };

  function addDecimal(keyitem){
    if (mainMath.indexOf(keyitem) === -1){
      if(mainMath == "0") {
        mainMath = "0" + keyitem;
        return;
      }
    } else {
        return;
      }
    addNumber(keyitem);
  };

  function solveEqual(keyitem) {
    subMatharray.push(finalset);
    subMath = subMatharray.join("");
    mainMath = eval(subMath);
    console.log("solveEqualresult: " + mainMath);
    console.log("solveEqualhistory: " + subMath);
    console.log("solveEqualarray: " + subMatharray);
    var finalresult = mainMath.toString();
    if(finalresult.length > 8){
      $(".entry").css("font-size", "1.5em");
    }
    equalPressed = true;
  };

  function update(){
  $("#answer").html(mainMath);
  $("#history").html(subMath);
};

});

/*Problems
2. I need to work on percentage button soon...
3. fix the problem if someone click an operator more than one.
*/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
h1, h2, h3, p {
  font-family: 'Roboto', sans-serif;
}
html, body{
  height:100%;
  margin: 0;
  background-color: #ffffff;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
  background-repeat: no-repeat;
    background-size: cover;
  background-position: center center;
  padding: 160px 0;
}
.calculatorbox {
  width: 300px;
  margin: 0 auto;
  border: 1px solid #000000;
}
.calheader {
  text-align: center;
}
.calwindow {
  background: #000000;
  position: relative;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
   -webkit-flex-direction: column; /* Safari */
  flex-direction:         column;
  -webkit-justify-content: flex-end;
  justify-content: flex-end;
  -webkit-align-items: flex-end;
  align-items: flex-end;
  padding: 10px 0;
  box-sizing: border-box;
}
.entry {
  font-size: 4em;
  display: block;
  line-height: 1em;
}
.entryhistory {
  font-size: 1em;
  letter-spacing: 2px;
  padding-right: 5px;
}
.entry p, .entryhistory p {
  margin: 0;
  color: #ffffff;
}
sup {
  top: -0.5em;
}

sub {
  bottom: -0em;
}
.row {
  clear: both;
  width: 100%;
  display: flex;
}
button {
  display: inline-block;
  border: none;
  padding: 0;
  outline: none;
  cursor: pointer;
}
.key {
  width: 75px;
  height: 70px;
  font-size: 22px;
  border-top: 1px solid rgba(0, 0, 0, 0.3);
  border-right: 1px solid rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
}
.key.btnspan {
  width: 150px;
}
.key.topcolor {
  background: #d9d9d9;
}
.key.orange {
  background: #ff8c00;
  color: #ffffff;
}</code>```

Simple Calculator

        <button class="key topcolor" value="clear">C</button>
        <button class="key topcolor" value="plusminus">+/−</button>
        <button class="key topcolor" value="%">%</button>
        <button class="key orange" value="/">÷</button>

        <button class="key" value="7">7</button>
        <button class="key" value="8">8</button>
        <button class="key" value="9">9</button>
        <button class="key orange" value="*">×</button>

        <button class="key" value="4">4</button>
        <button class="key" value="5">5</button>
        <button class="key" value="6">6</button>
        <button class="key orange" value="-">−</button>

        <button class="key" value="1">1</button>
        <button class="key" value="2">2</button>
        <button class="key" value="3">3</button>
        <button class="key orange" value="+">+</button>

        <button class="key btnspan" value="0">0</button>
        <button class="key" value=".">.</button>
        <button class="key orange" value="=">=</button>

```
</div>
</div>
</p>

<p>All the action is happening in <code>function addOperator(keyitem)</code>. I have attempt to fix the "Zero" problem, but I commented it out so you can see fully what I am talking about. Here is the code that I commented out.</p>

```if (mainMath == "0" && finalset !== "0"){
      mainMath = "0";
      subMatharray.push(keyitem);
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }
```

I look forward to any suggestions or code solutions that can help me fix the "Zero" problem.

答:
In your "addOperator" function you'll just need a simple if statement, check whether or not the last character in your string is an operator. If it is then swap it, if it isn't than add the given operator

EDIT:

I looked through the code some more and looks like it's a little more complex than a single if statement and would require quite a bit of rewriting. All I can really offer is a different way of going about storing your values.

I would recommend storing an array of the actual button presses as soon as the button is pressed, and then modify that list within your individual button functions, then from that list generate you're display. For example, if the user were to press 1, +, 2, 3, -, +, = the array would look like this:

[] -> []

[1] -> [1]

[1,+] -> [1,+]

[1,+,2] -> [1,+,2]

[1,+,2,3] -> [1,+,23] // Checked by addNumber, concats numbers

[1,+,23,-] -> [1,+,23,-]

[1,+,23,-,+] -> [1,+,23,+]   // Checked by addOperator, swaps operator

[1,+,23,-,+,=] -> []   // Checked by solveEqual, solves then empties array

Having this as a global variable would allow your button functions to modify the array as opposed to pushing elements from the functions as it currently is, the benefit being you wouldn't be pushing elements that shouldn't be pushed like nulls or operators

Body:
I am writing a FreeCodeCamp Calculator. The problem that I am working on right now is repeating operators. For example, if I press "5" and then "+", but changed my mind and pressed "-", the history area should display "5-" instead of "5+". However, with my code, it display "5+0-". Therefore, I realize that I will need to fix the "Zero" problem as well.

The list I wanted to do for the "Zero" problem are:

If one press "0", allow it to appear in the history area. For example, if someone press "0" and then the operator, it should appear in the history area as "0-".

Otherwise, if someone press operator first without putting in any number, stop this method

Here is my code from this Codepen:

$(document).ready(function() {

  var mainMath = "0";
  var subMath = "0";
  var finalset = "";
  var subMatharray = [];
  var oppArray = [];
  var equalPressed = false;
  var prevKey = "";
  update();

  $("button").click(function(){
    calculate($(this).attr("value"));
  });

  function calculate(keyitem) {
    console.log("buttonpress: " + keyitem);
    switch(keyitem) {
      case "clear":
        clearScreen();
        break;
      case "%":
        percentageScreen();
        break;
      case "/":
      case "*":
      case "+":
      case "-":
        addOperator(keyitem);
        break;
      case "plusminus":
        plusminusScreen();
        break;
      case "0":
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        addNumber(keyitem);
        break;
      case ".":
        addDecimal(keyitem);
        break;
      case "=":
        solveEqual(keyitem);
        break;
    }
    update();
    };

  function clearScreen() {
     mainMath = "0";
     subMath = "0";
     prevKey = "";
     subMatharray = [];
     oppArray = [];
    if(mainMath.length > 0){
      $(".entry").css("font-size", "4em");
    }
    console.log("clearMain: " + mainMath);
    console.log("clearSub: " + subMath);
  };

  function plusminusScreen() {
     mainMath = -1 * mainMath;
    finalset = mainMath;
    console.log("plusminusMain: " + mainMath);
    console.log("plusminusFinal: " + finalset);
  };

  function addNumber(keyitem) {
    if (mainMath == "0"){
      mainMath = keyitem/*mainMath.replace("0", keyitem);*/
      finalset = mainMath;
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }
    if (equalPressed == true){
      mainMath = keyitem;
      subMath = "0";
      subMatharray = [];
      equalPressed = false;
      console.log("addNumberEqualmain: " + mainMath);
    }
    mainMath+=keyitem;
    finalset = mainMath;

    console.log("addedMain: " + mainMath);
    console.log("addedFinalset: " + finalset);
    console.log("addedarray: " + subMatharray);

    if(mainMath.length > 8){
      $(".entry").css("font-size", "1.5em");
    }

  };

  function addOperator(keyitem){

    if (equalPressed == true){
      subMatharray = [];
      equalPressed = false;
      console.log("addOpEqualarray: " + subMatharray);
    }
    /*if (mainMath == "0" && finalset !== "0"){
      mainMath = "0";
      subMatharray.push(keyitem);
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }*/

    oppArray.push(keyitem);
    console.log("addOpArray: " + oppArray);
    var opkeyitem = "";

    subMatharray.push(mainMath);
    prevKey = "numbertest";

    if(prevKey == "numbertest") {
      subMatharray.push(keyitem);
      prevKey = "operatortest";
      console.log("addOpArraySubArrayElse: " + subMatharray);
      console.log("addOpArrayPrevKeyElse: " + prevKey);
    } /*else if (oppArray.length > 1 && prevKey == "operatortest") {
      subMatharray.pop();
      subMatharray.push("droubletest");
      oppArray = [];
      console.log("addOpArraySubArray: " + subMatharray);
      console.log("addOpArrayPrevKey: " + prevKey);
    } /*else if(prevKey == "numbertest") {
      subMatharray.push(keyitem);
      prevKey = "operatortest";
      console.log("addOpArraySubArrayElse: " + subMatharray);
      console.log("addOpArrayPrevKeyElse: " + prevKey);
    }*/

    subMath = subMatharray.join("");
    mainMath = "0";
    prevKey = keyitem;
    console.log("addOpSub: " + subMath);
    console.log("addOpMain: " + mainMath);
    console.log("addOpMainarray: " + subMatharray);
    console.log("equaltrueTest: " + equalPressed);
  };

  function addDecimal(keyitem){
    if (mainMath.indexOf(keyitem) === -1){
      if(mainMath == "0") {
        mainMath = "0" + keyitem;
        return;
      }
    } else {
        return;
      }
    addNumber(keyitem);
  };

  function solveEqual(keyitem) {
    subMatharray.push(finalset);
    subMath = subMatharray.join("");
    mainMath = eval(subMath);
    console.log("solveEqualresult: " + mainMath);
    console.log("solveEqualhistory: " + subMath);
    console.log("solveEqualarray: " + subMatharray);
    var finalresult = mainMath.toString();
    if(finalresult.length > 8){
      $(".entry").css("font-size", "1.5em");
    }
    equalPressed = true;
  };

  function update(){
  $("#answer").html(mainMath);
  $("#history").html(subMath);
};

});

/*Problems
2. I need to work on percentage button soon...
3. fix the problem if someone click an operator more than one.
*/

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
h1, h2, h3, p {
  font-family: 'Roboto', sans-serif;
}
html, body{
  height:100%;
  margin: 0;
  background-color: #ffffff;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
  background-repeat: no-repeat;
    background-size: cover;
  background-position: center center;
  padding: 160px 0;
}
.calculatorbox {
  width: 300px;
  margin: 0 auto;
  border: 1px solid #000000;
}
.calheader {
  text-align: center;
}
.calwindow {
  background: #000000;
  position: relative;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
   -webkit-flex-direction: column; /* Safari */
  flex-direction:         column;
  -webkit-justify-content: flex-end;
  justify-content: flex-end;
  -webkit-align-items: flex-end;
  align-items: flex-end;
  padding: 10px 0;
  box-sizing: border-box;
}
.entry {
  font-size: 4em;
  display: block;
  line-height: 1em;
}
.entryhistory {
  font-size: 1em;
  letter-spacing: 2px;
  padding-right: 5px;
}
.entry p, .entryhistory p {
  margin: 0;
  color: #ffffff;
}
sup {
  top: -0.5em;
}

sub {
  bottom: -0em;
}
.row {
  clear: both;
  width: 100%;
  display: flex;
}
button {
  display: inline-block;
  border: none;
  padding: 0;
  outline: none;
  cursor: pointer;
}
.key {
  width: 75px;
  height: 70px;
  font-size: 22px;
  border-top: 1px solid rgba(0, 0, 0, 0.3);
  border-right: 1px solid rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
}
.key.btnspan {
  width: 150px;
}
.key.topcolor {
  background: #d9d9d9;
}
.key.orange {
  background: #ff8c00;
  color: #ffffff;
}

Simple Calculator

        <button class="key topcolor" value="clear">C</button>
        <button class="key topcolor" value="plusminus">+/−</button>
        <button class="key topcolor" value="%">%</button>
        <button class="key orange" value="/">÷</button>

        <button class="key" value="7">7</button>
        <button class="key" value="8">8</button>
        <button class="key" value="9">9</button>
        <button class="key orange" value="*">×</button>

        <button class="key" value="4">4</button>
        <button class="key" value="5">5</button>
        <button class="key" value="6">6</button>
        <button class="key orange" value="-">−</button>

        <button class="key" value="1">1</button>
        <button class="key" value="2">2</button>
        <button class="key" value="3">3</button>
        <button class="key orange" value="+">+</button>

        <button class="key btnspan" value="0">0</button>
        <button class="key" value=".">.</button>
        <button class="key orange" value="=">=</button>

All the action is happening in function addOperator(keyitem). I have attempt to fix the "Zero" problem, but I commented it out so you can see fully what I am talking about. Here is the code that I commented out.

if (mainMath == "0" && finalset !== "0"){
      mainMath = "0";
      subMatharray.push(keyitem);
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }

I look forward to any suggestions or code solutions that can help me fix the "Zero" problem.


问:
Printing a list after having removed adjacent duplicate elements
```<code>new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list
</code>```

Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.

Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

答:
```<code>new_list = []

def remove_adjacent(nums):
    i = 0
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
        i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

# appending the last item
new_list.append(l[len(l)-1])

print (new_list.append(nums[len(nums) - 1]))
</code>```

Output

```<code>[1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]
</code>```

Body:
new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list

Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.

Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

Body:
new_list = []

def remove_adjacent(nums):
    i = 0
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
        i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

# appending the last item
new_list.append(l[len(l)-1])

print (new_list.append(nums[len(nums) - 1]))

Output

[1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]


问:
No browser reads my Google Web font (except google chrome browser)
So i'm using the Roboto font using this

and obviously font-family: Roboto in my css.
The problem is that only chrome displays the Roboto font. What should I do?
here's my website so you can see: click</p>

答:
I try it On Firefox 56 and the font in loaded
 try to load font before another css file may be the problem solved
Like This </p>

```<code><link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="css/css.css" rel="stylesheet" />
<link href="css/sshow.css" rel="stylesheet" />
</code>```

Body:
I try it On Firefox 56 and the font in loaded
 try to load font before another css file may be the problem solved
Like This

<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="css/css.css" rel="stylesheet" />
<link href="css/sshow.css" rel="stylesheet" />


问:
How to animate a Bootstrap toggle in Angular 2?
As you may now, Bootstrap toggles just change display: none to display: block and vice-versa. I've been reading the Angular 2 Animation Guide but it all seems to depend on a changing property on the component, when I just want to change based on the element's style.display property.

Am I thinking about this the wrong way, or how would I do this?

答: I switched from using jquery to toggle() in the component, and just went the more Angular-idomatic way of using boolean properties with *ngIf. It cleaner and more declarative, and lets me use the :enter and :leave transitions.


问:
Disable vertical scroll bar for md-autocomplete autosuggestion drop down
i want to disable scroll bar for md-autocomplete autosuggestion drop down.Is there any css or attribute way to do it?</p>

答:
Give this a try.
overflow-y: hidden;</p>

Body:
Give this a try.
overflow-y: hidden;


问:
Problem doing reverse polish notation (Java)
One of the problems that im finding is that i cant manage to compare the +,-,*,/  is there any other way?  THx for the help

CODE:

```<code>import java.util.Scanner;

public class Question2 {

    public static void main(String args[]){

    Scanner scan = new Scanner(System.in);

    double array[] = new double[20];

    System.out.print("Enter sum: ");
    String sum = scan.nextLine();

    getValue(sum, array, 0);

    System.out.print(array[0]);
    }

    public static void getValue(String input, double array[], int poi){
     int counter = 0;
     char nextValue = ' ';
     String value = "";
     double num = 0;
     boolean checkDub = true;

        do{
            value = value + input.charAt(counter);

            counter ++;
            nextValue = input.charAt(counter);
        }while(nextValue != ' ');

     try {num = Integer.parseInt(value);}
     catch (Exception e) {
      checkDub = false;

      double l2 = array[poi];
      poi--;

      double l1 = array[poi];

      if(value.equals("+")){ array[poi] =  l1 + l2;} // <--- comparing problem?
      else if(value.equals("-")){ array[poi] =  l1 - l2;}
      else if(value.equals("*")){ array[poi] =  l1 * l2;}
      else if(value.equals("/")){ array[poi] =  l1 / l2;}
      else{System.out.println("Error");}

    }
        if(checkDub = true){
        array[poi] = num;}

        String nextInput = input.substring(counter);
        getValue(nextInput, array, poi + 1);

    }

}
</code>```

答:
Pretty sure your problem is that you're not stripping off leading space characters. For example, if your input is "2 2 + ", then at the third invocation your input is " + ", and value gets " +". That fails your equality check with "+". Meanwhile, parseInt cheerfully strips leading whitespace.

Your code will also throw an IndexOutOfBoundsException if your input is not terminated by a space. Further, you won't handle more complex expressions like "1 2 + 3 +" because you don't do recursive call after evaluating the first one. (Hint: you should return when you've consumed all tokens from the input).

Style points (not bugs): you should use indexOf to find the space (or, even better, split). The recursive tail call should really be a loop (for very long inputs, you might cause a StackOverflowError). You don't need to have a boolean checkDub - rather, you can place the body of if (checkDub == true) inside the try (after the parseInt). But that you'd probably want to refactor anyway if you're using a loop.

ContentLicense: CC BY-SA 2.5

Body:
One of the problems that im finding is that i cant manage to compare the +,-,*,/  is there any other way?  THx for the help

CODE:

import java.util.Scanner;

public class Question2 {

    public static void main(String args[]){

    Scanner scan = new Scanner(System.in);

    double array[] = new double[20];

    System.out.print("Enter sum: ");
    String sum = scan.nextLine();

    getValue(sum, array, 0);

    System.out.print(array[0]);
    }

    public static void getValue(String input, double array[], int poi){
     int counter = 0;
     char nextValue = ' ';
     String value = "";
     double num = 0;
     boolean checkDub = true;

        do{
            value = value + input.charAt(counter);

            counter ++;
            nextValue = input.charAt(counter);
        }while(nextValue != ' ');

     try {num = Integer.parseInt(value);}
     catch (Exception e) {
      checkDub = false;

      double l2 = array[poi];
      poi--;

      double l1 = array[poi];

      if(value.equals("+")){ array[poi] =  l1 + l2;} // <--- comparing problem?
      else if(value.equals("-")){ array[poi] =  l1 - l2;}
      else if(value.equals("*")){ array[poi] =  l1 * l2;}
      else if(value.equals("/")){ array[poi] =  l1 / l2;}
      else{System.out.println("Error");}

    }
        if(checkDub = true){
        array[poi] = num;}

        String nextInput = input.substring(counter);
        getValue(nextInput, array, poi + 1);

    }

}


问:
Generic, higher order functions
I'm trying to add Flow type information to a small library of mine.

The library defines some functions that are generic over Object, Array, Set, Map and other types.

Here a small piece example to give an idea:

```<code>function set( obj, key, value ) {
  if( isMap(obj) )      { obj.set(key, value); }
  else if( isSet(obj) ) { obj.add(value);      }
  else                  { obj[key] = value;    }
}
function instantiateSameType( obj ) {
  if( isArray(obj) )    { return [];        }
  else if( isMap(obj) ) { return new Map(); }
  else if( isSet(obj) ) { return new Set(); }
  else                  { return {};        }
}
function forEach( obj, fn ) {
  if( obj.forEach ) obj.forEach(    ( value, key )=>fn(value, key, obj) );
  else Object.entries(obj).forEach( ([key, value])=>fn(value, key, obj) );
}
function map( obj, fn ) {
  const result = instantiateSameType( obj );
  forEach(obj, (value, key)=>{
    set( result, key, fn(value, key, this) );
  });
  return result;
}
</code>```

How can I define types for map?

I'd want to avoid giving a specialized version for each of the 4 types I listed in the example, as map is generic over them.
I feel the need to define higher-order interfaces, and implement them for existing types, but can't find much about any of this...

Any hints or ideas?

答:
Update 2017-11-28: fp-ts is the successor to flow-static-land. fp-ts is a newer library by the same author. It supports both Flow and Typescript.

There is a library, flow-static-land, that does something quite similar to what you are attempting. You could probably learn some interesting things by looking at that code and reading the accompanying blog posts by @gcanti. I'll expand on the strategy in flow-static-land; but keep in mind that you can implement your iteration functions without higher-kinded types if you are OK with a closed set of iterable types.

As @ftor mentions, if you want polymorphic functions that can work on an open set of collection types then you want higher-kinded types (HKTs). Higher-kinded types are types that take type parameters, but with one or more of those parameters left unspecified. For example arrays in Flow take a type parameter to specify the type of elements in the array (Array<V>), and the same goes for maps (Map<K, V>). Sometimes you want to be able to refer to a parameterized type without specifying all of its type parameters. For example map should be able to operate on all arrays or maps regardless of their type parameters:

```<code>function map<K, A, B, M: Array<_> | Map<K, _>>(M<A>, fn: A => B): M<B>
</code>```

In this case M is a variable representing a higher-kinded type. We can pass M around as a first-class type, and fill in its type parameter with different types at different times. Flow does not natively support HKTs, so the syntax above does not work. But it is possible to fake HKTs with some type alias indirection, which is what flow-static-land does. There are details in the blog post, Higher kinded types with Flow.

To get a fully-polymorphic version of map, flow-static-land emulates Haskell type classes (which rely on HKTs). map is the defining feature of a type class called Functor; flow-static-land has this definition for Functor (from Functor.js):

```<code>export interface Functor<F> {
  map<A, B>(f: (a: A) => B, fa: HKT<F, A>): HKT<F, B>
}
</code>```

The HKT type is flow-static-land's workaround for implementing higher-kinded types. The actual higher-kinded type is F, which you can think of as standing in for Array or Map or any type that could implement map. Expressions like HKT<F, A> can be thought of as F where the higher-kinded type F has been applied to the type parameter A. (I'm doing some hand waving here - F is actually a type-level tag. But the simplified view works to some extent.)

You can create an implementation of Functor for any type. But there is a catch: you need to define your type in terms of HKT so that it can be used as a higher-kinded type. In flow-static-land in the module Arr.js we see this higher-kinded version of the array type:

```<code>class IsArr {}  // type-level tag, not used at runtime
export type ArrV<A> = Array<A>;  // used internally
export type Arr<A> = HKT<IsArr, A>;  // the HKT-compatible array type
</code>```

If you do not want to use Arr in place of Array everywhere in your code then you need to convert using inj: (a: Array) => Arr and prj: (fa: Arr) => Array. inj and prj are type-level transformers - at runtime both of those functions just return their input, so they are likely to be inlined by the JIT. There is no runtime difference between Arr and Array.

A Functor implementation for Arr looks like this:

```<code>const arrFunctor: Functor<IsArr> = {
  function map<A, B>(f: (a: A) => B, fa: Arr<A>): Arr<B> {
    const plainArray = prj(f)
    const mapped = plainArray.map(f)
    return inj(mapped)
  }
}
</code>```

In fact the entire Arr.js module is an Arr implementation for Functor, Foldable, Traversable, and other useful type classes. Using that implementation with polymorphic code looks like this:

```<code>import * as Arr from 'flow-static-land/lib/Arr'
import { type Foldable } from 'flow-static-land/lib/Foldable'
import { type Functor } from 'flow-static-land/lib/Functor'
import { type HKT } from 'flow-static-land/lib/HKT'

type Order = { items: string[], total: number }

// this code is polymorphic in that it is agnostic of the collection kind
// that is given
function computeTotal<F> (
  f: Foldable<F> & Functor<F>,
  orders: HKT<F, Order>
): number {
  const totals = f.map(order => order.total, orders)
  return f.reduce((sum, total) => sum + total, 0, totals)
}

// calling the code with an `Arr<Order>` collection
const orders = Arr.inj([{ items: ['foo', 'bar'], total: 23.6 }])

const t = computeTotal(Arr, orders)
</code>```

computeTotal needs to apply map and reduce to its input. Instead of constraining the input to a given collection type, computeTotal uses its first argument to constrain its input to types that implement both Foldable and Functor: f: Foldable<F> & Functor<F>. At the type-level the argument f acts as a "witness" to prove that the given collection type implements both map and reduce. At runtime f provides references to the specific implementations of map and reduce to be used. At the entry point to the polymorphic code (where computeTotal is called with a statically-known collection type) the Foldable & Functor implementation is given as the argument Arr. Because Javascript is not designed for type classes the choice of Arr must be given explicitly; but Flow will at least throw an error if you try to use an implementation that is incompatible with the collection type that is used.

To round this out here is an example of a polymorphic function, allItems, that accepts a collection, and returns a collection of the same kind. allItems is agnostic of the specific type of collection that it operates on:

```<code>import { type Monad } from 'flow-static-land/lib/Monad'
import { type Monoid, concatAll } from 'flow-static-land/lib/Monoid'
import { type Pointed } from 'flow-static-land/lib/Pointed'

// accepts any collection type that implements `Monad` & `Monoid`, returns
// a collection of the same kind but containing `string` values instead of
// `Order` values
function allItems<F> (f: Monad<F> & Monoid<*>, orders: HKT<F, Order>): HKT<F, string> {
  return f.chain(order => fromArray(f, order.items), orders)
}

function fromArray<F, A> (f: Pointed<F> & Monoid<*>, xs: A[]): HKT<F, A> {
  return concatAll(f, xs.map(f.of))
}

// called with an `Arr<Order>` collection
const is = allItems(Arr, orders)
</code>```

chain is flow-static-land's version of flatMap. For every element in a collection, chain runs a callback that must produce a collection of the same kind (but it could hold a different value type). That produces effectively a collection of collections. chain then flattens that to a single level for you. So chain is basically a combination of map and flatten.

I included fromArray because the callback given to chain must return the same kind of collection that allItems accepts and returns - returning an Array from the chain callback will not work. I used a Pointed constraint in fromArray to get the of function, which puts a single value into a collection of the appropriate kind. Pointed does not appear in the constraints of allItems because allItems has a Monad constraint, and every Monad implementation is also an implementation of Pointed, Chain, Functor, and some others.

I am personally a fan of flow-static-land. The functional style and use of HKTs result in code with better type safety than one could get with object-oriented style duck typing. But there are drawbacks. Error messages from Flow can become very verbose when using type unions like Foldable<F> & Functor<F>. And the code style requires extra training - it will seem super weird to programmers who are not well acquainted with Haskell.

Title: Generic, higher order functions

Body:
I'm trying to add Flow type information to a small library of mine.

The library defines some functions that are generic over Object, Array, Set, Map and other types.

Here a small piece example to give an idea:

function set( obj, key, value ) {
  if( isMap(obj) )      { obj.set(key, value); }
  else if( isSet(obj) ) { obj.add(value);      }
  else                  { obj[key] = value;    }
}
function instantiateSameType( obj ) {
  if( isArray(obj) )    { return [];        }
  else if( isMap(obj) ) { return new Map(); }
  else if( isSet(obj) ) { return new Set(); }
  else                  { return {};        }
}
function forEach( obj, fn ) {
  if( obj.forEach ) obj.forEach(    ( value, key )=>fn(value, key, obj) );
  else Object.entries(obj).forEach( ([key, value])=>fn(value, key, obj) );
}
function map( obj, fn ) {
  const result = instantiateSameType( obj );
  forEach(obj, (value, key)=>{
    set( result, key, fn(value, key, this) );
  });
  return result;
}

How can I define types for map?

I'd want to avoid giving a specialized version for each of the 4 types I listed in the example, as map is generic over them.
I feel the need to define higher-order interfaces, and implement them for existing types, but can't find much about any of this...

Any hints or ideas?

Body:
Update 2017-11-28: fp-ts is the successor to flow-static-land. fp-ts is a newer library by the same author. It supports both Flow and Typescript.

There is a library, flow-static-land, that does something quite similar to what you are attempting. You could probably learn some interesting things by looking at that code and reading the accompanying blog posts by @gcanti. I'll expand on the strategy in flow-static-land; but keep in mind that you can implement your iteration functions without higher-kinded types if you are OK with a closed set of iterable types.

As @ftor mentions, if you want polymorphic functions that can work on an open set of collection types then you want higher-kinded types (HKTs). Higher-kinded types are types that take type parameters, but with one or more of those parameters left unspecified. For example arrays in Flow take a type parameter to specify the type of elements in the array (Array<V>), and the same goes for maps (Map<K, V>). Sometimes you want to be able to refer to a parameterized type without specifying all of its type parameters. For example map should be able to operate on all arrays or maps regardless of their type parameters:

function map<K, A, B, M: Array<_> | Map<K, _>>(M<A>, fn: A => B): M<B>

In this case M is a variable representing a higher-kinded type. We can pass M around as a first-class type, and fill in its type parameter with different types at different times. Flow does not natively support HKTs, so the syntax above does not work. But it is possible to fake HKTs with some type alias indirection, which is what flow-static-land does. There are details in the blog post, Higher kinded types with Flow.

To get a fully-polymorphic version of map, flow-static-land emulates Haskell type classes (which rely on HKTs). map is the defining feature of a type class called Functor; flow-static-land has this definition for Functor (from Functor.js):

export interface Functor<F> {
  map<A, B>(f: (a: A) => B, fa: HKT<F, A>): HKT<F, B>
}

The HKT type is flow-static-land's workaround for implementing higher-kinded types. The actual higher-kinded type is F, which you can think of as standing in for Array or Map or any type that could implement map. Expressions like HKT<F, A> can be thought of as F<A> where the higher-kinded type F has been applied to the type parameter A. (I'm doing some hand waving here - F is actually a type-level tag. But the simplified view works to some extent.)

You can create an implementation of Functor for any type. But there is a catch: you need to define your type in terms of HKT so that it can be used as a higher-kinded type. In flow-static-land in the module Arr.js we see this higher-kinded version of the array type:

class IsArr {}  // type-level tag, not used at runtime
export type ArrV<A> = Array<A>;  // used internally
export type Arr<A> = HKT<IsArr, A>;  // the HKT-compatible array type

If you do not want to use Arr<A> in place of Array<A> everywhere in your code then you need to convert using inj: (a: Array<A>) => Arr<A> and prj: (fa: Arr<A>) => Array<A>. inj and prj are type-level transformers - at runtime both of those functions just return their input, so they are likely to be inlined by the JIT. There is no runtime difference between Arr<A> and Array<A>.

A Functor implementation for Arr looks like this:

const arrFunctor: Functor<IsArr> = {
  function map<A, B>(f: (a: A) => B, fa: Arr<A>): Arr<B> {
    const plainArray = prj(f)
    const mapped = plainArray.map(f)
    return inj(mapped)
  }
}

In fact the entire Arr.js module is an Arr implementation for Functor, Foldable, Traversable, and other useful type classes. Using that implementation with polymorphic code looks like this:

import * as Arr from 'flow-static-land/lib/Arr'
import { type Foldable } from 'flow-static-land/lib/Foldable'
import { type Functor } from 'flow-static-land/lib/Functor'
import { type HKT } from 'flow-static-land/lib/HKT'

type Order = { items: string[], total: number }

// this code is polymorphic in that it is agnostic of the collection kind
// that is given
function computeTotal<F> (
  f: Foldable<F> & Functor<F>,
  orders: HKT<F, Order>
): number {
  const totals = f.map(order => order.total, orders)
  return f.reduce((sum, total) => sum + total, 0, totals)
}

// calling the code with an `Arr<Order>` collection
const orders = Arr.inj([{ items: ['foo', 'bar'], total: 23.6 }])

const t = computeTotal(Arr, orders)

computeTotal needs to apply map and reduce to its input. Instead of constraining the input to a given collection type, computeTotal uses its first argument to constrain its input to types that implement both Foldable and Functor: f: Foldable<F> & Functor<F>. At the type-level the argument f acts as a "witness" to prove that the given collection type implements both map and reduce. At runtime f provides references to the specific implementations of map and reduce to be used. At the entry point to the polymorphic code (where computeTotal is called with a statically-known collection type) the Foldable & Functor implementation is given as the argument Arr. Because Javascript is not designed for type classes the choice of Arr must be given explicitly; but Flow will at least throw an error if you try to use an implementation that is incompatible with the collection type that is used.

To round this out here is an example of a polymorphic function, allItems, that accepts a collection, and returns a collection of the same kind. allItems is agnostic of the specific type of collection that it operates on:

import { type Monad } from 'flow-static-land/lib/Monad'
import { type Monoid, concatAll } from 'flow-static-land/lib/Monoid'
import { type Pointed } from 'flow-static-land/lib/Pointed'

// accepts any collection type that implements `Monad` & `Monoid`, returns
// a collection of the same kind but containing `string` values instead of
// `Order` values
function allItems<F> (f: Monad<F> & Monoid<*>, orders: HKT<F, Order>): HKT<F, string> {
  return f.chain(order => fromArray(f, order.items), orders)
}

function fromArray<F, A> (f: Pointed<F> & Monoid<*>, xs: A[]): HKT<F, A> {
  return concatAll(f, xs.map(f.of))
}

// called with an `Arr<Order>` collection
const is = allItems(Arr, orders)

chain is flow-static-land's version of flatMap. For every element in a collection, chain runs a callback that must produce a collection of the same kind (but it could hold a different value type). That produces effectively a collection of collections. chain then flattens that to a single level for you. So chain is basically a combination of map and flatten.

I included fromArray because the callback given to chain must return the same kind of collection that allItems accepts and returns - returning an Array from the chain callback will not work. I used a Pointed constraint in fromArray to get the of function, which puts a single value into a collection of the appropriate kind. Pointed does not appear in the constraints of allItems because allItems has a Monad constraint, and every Monad implementation is also an implementation of Pointed, Chain, Functor, and some others.

I am personally a fan of flow-static-land. The functional style and use of HKTs result in code with better type safety than one could get with object-oriented style duck typing. But there are drawbacks. Error messages from Flow can become very verbose when using type unions like Foldable<F> & Functor<F>. And the code style requires extra training - it will seem super weird to programmers who are not well acquainted with Haskell.


问:
Adding an ImageView to a Constraint Layout causes a crash
I am trying to create a splash screen for my app and it works just fine when I only display some text on the splashScreen's layout file(using a Constraint Layout). When I add an imageView however, the app crashes and I don't get why. The image's file size is only 299kb so it's not a memory issue or something right? Any ideas on why this is happening and how to fix it? Here's my xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical"
    tools:context="com.spdesigns.funfacts.SplashScreen">

<ImageView
    android:id="@+id/logoImageView"
    android:layout_width="377dp"
    android:layout_height="293dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/logo" />

</android.support.constraint.ConstraintLayout>
</code>```

SplashScreen.java

```<code>package com.spdesigns.funfacts;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SplashScreen extends AppCompatActivity {

private static final int Splash_Timer = 4000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash_screen);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent mainActivity = new Intent(SplashScreen.this,FunFactsActivity.class);
            startActivity(mainActivity);
            finish();
        }
    },Splash_Timer);
}
}
</code>```

Logcat Error:

```<code>11-15 18:29:19.218 3486-3486/com.spdesigns.funfacts E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.spdesigns.funfacts, PID: 3486
                                                                  java.lang.OutOfMemoryError: Failed to allocate a 655089132 byte allocation with 3077156 free bytes and 379MB until OOM
                                                                      at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                      at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                                      at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:620)
                                                                      at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:455)
                                                                      at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1155)
                                                                      at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:720)
                                                                      at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:571)
                                                                      at android.content.res.Resources.loadDrawable(Resources.java:854)
                                                                      at android.content.res.TypedArray.getDrawable(TypedArray.java:928)
                                                                      at android.widget.ImageView.<init>(ImageView.java:157)
                                                                      at android.widget.ImageView.<init>(ImageView.java:145)
                                                                      at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                                                      at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                                                      at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                                      at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
                                                                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                      at com.spdesigns.funfacts.SplashScreen.onCreate(SplashScreen.java:15)
                                                                      at android.app.Activity.performCreate(Activity.java:6662)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
</code>```

答:
The issue is that ImageView uses a GL Texture, which on most devices is limited to 2048x2048. The max texture size varies from device to device, I've seen is as small as ~1500x1500 and as big as 4096x4096.

For that, you have to create an image for each dimension to make sure will work in all devices. Check this thread for more info.

GL Maximum Textures Size Policy

Body:
I am trying to create a splash screen for my app and it works just fine when I only display some text on the splashScreen's layout file(using a Constraint Layout). When I add an imageView however, the app crashes and I don't get why. The image's file size is only 299kb so it's not a memory issue or something right? Any ideas on why this is happening and how to fix it? Here's my xml file:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical"
    tools:context="com.spdesigns.funfacts.SplashScreen">

<ImageView
    android:id="@+id/logoImageView"
    android:layout_width="377dp"
    android:layout_height="293dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/logo" />

</android.support.constraint.ConstraintLayout>

SplashScreen.java

package com.spdesigns.funfacts;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SplashScreen extends AppCompatActivity {

private static final int Splash_Timer = 4000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash_screen);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Intent mainActivity = new Intent(SplashScreen.this,FunFactsActivity.class);
            startActivity(mainActivity);
            finish();
        }
    },Splash_Timer);
}
}

Logcat Error:

11-15 18:29:19.218 3486-3486/com.spdesigns.funfacts E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.spdesigns.funfacts, PID: 3486
                                                                  java.lang.OutOfMemoryError: Failed to allocate a 655089132 byte allocation with 3077156 free bytes and 379MB until OOM
                                                                      at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
                                                                      at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
                                                                      at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:620)
                                                                      at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:455)
                                                                      at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:1155)
                                                                      at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:720)
                                                                      at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:571)
                                                                      at android.content.res.Resources.loadDrawable(Resources.java:854)
                                                                      at android.content.res.TypedArray.getDrawable(TypedArray.java:928)
                                                                      at android.widget.ImageView.<init>(ImageView.java:157)
                                                                      at android.widget.ImageView.<init>(ImageView.java:145)
                                                                      at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                                                      at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                                                      at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                                      at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:769)
                                                                      at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                                      at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                                      at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                      at com.spdesigns.funfacts.SplashScreen.onCreate(SplashScreen.java:15)
                                                                      at android.app.Activity.performCreate(Activity.java:6662)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:154)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)


问:
input javascript checked - unchecked
I have input in body of my html page:

```<code><input id="showElement" type="checkbox" checked="checked" oninput="onShowElementChange()" checked="checked"/>
</code>```

And in script there is:

```<code>  function onShowElementChange(value) {
  scene3dManager.showElement = $('#showElement').is(':checked')
}

function onShowElementChange(value) {
  scene3dManager.showElement = $('#showElement').is(':checked')
}

<input id="showElement" type="checkbox" checked="checked" oninput="onShowElementChange()" checked="checked" />
</code>```

But, for some reason, it doesn't work ... My input should be clicked by default, and user can unclick it if he chooses to.

Perhaps, there is some mistake in my code, so, im asking for help. Thanks

答:
I think that checked="checked" is deprecated, try just checked instead</p>

```<code><input id="showElement" type="checkbox" oninput="onShowElementChange()" checked/>
</code>```

Title: input javascript checked - unchecked

Body:
I have input in body of my html page:

<input id="showElement" type="checkbox" checked="checked" oninput="onShowElementChange()" checked="checked"/>

And in script there is:

  function onShowElementChange(value) {
  scene3dManager.showElement = $('#showElement').is(':checked')
}

function onShowElementChange(value) {
  scene3dManager.showElement = $('#showElement').is(':checked')
}

<input id="showElement" type="checkbox" checked="checked" oninput="onShowElementChange()" checked="checked" />

But, for some reason, it doesn't work ... My input should be clicked by default, and user can unclick it if he chooses to.

Perhaps, there is some mistake in my code, so, im asking for help. Thanks

Body:
I think that checked="checked" is deprecated, try just checked instead

<input id="showElement" type="checkbox" oninput="onShowElementChange()" checked/>


问:
Is using output buffering considered a bad practice?
Are ob_start / ob_get_clean() considered bad practice by php programmers in general?

Are there any disadvantages of output buffering?

答: For program efficiency, output buffer capturing is not bad.  It is a useful feature of PHP.  However, it can be used for things that are better done with other methods.  Code smell can be an issue with it, so make sure that there's not a better, clearer solution to your problem.</p>


问:
Insert into SQL DB doesn't work
```<code> SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();
        string checkRadioButton()
        {
            string rbdText;
            if(RadioButton1.Checked)
            {
                rbdText = RadioButton1.Text;
            }
            else
            {
                rbdText = RadioButton2.Text;
            }
            return rbdText;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand(" insert into Registration values(@Name, @Gender, @MobileNumber, @EmailID, @UserID, @Password, @Address, @Country)", con);
            cmd.Parameters.AddWithValue("@Name", TextBox1.Text);
            cmd.Parameters.AddWithValue("@Gender", checkRadioButton());
            cmd.Parameters.AddWithValue("@MobileNumber", TextBox2.Text);
            cmd.Parameters.AddWithValue("@EmailID", TextBox3.Text);
            cmd.Parameters.AddWithValue("@UserID", TextBox5.Text);
            cmd.Parameters.AddWithValue("@Password", TextBox6.Text);
            cmd.Parameters.AddWithValue("@Address", TextBox8.Text);
            cmd.Parameters.AddWithValue("@Country", DropDownList1.SelectedItem.Value);
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Redirect("Homepage2.aspx");

        }
</code>```

This is my  aspx.cs file for registration page. There is no compilation error, but after the Button1_Click event executed, the registration data is not saved into the database.

答:
You would need to add a connection string into the SQLConnection constructor. The connection string itself is usual to keep in the web.config. So the code could be similar to:

```<code>var connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Do your insert here;
}
</code>```

Title: Insert into SQL DB doesn't work

Body:
 SqlCommand cmd = new SqlCommand();
        SqlConnection con = new SqlConnection();
        string checkRadioButton()
        {
            string rbdText;
            if(RadioButton1.Checked)
            {
                rbdText = RadioButton1.Text;
            }
            else
            {
                rbdText = RadioButton2.Text;
            }
            return rbdText;
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand(" insert into Registration values(@Name, @Gender, @MobileNumber, @EmailID, @UserID, @Password, @Address, @Country)", con);
            cmd.Parameters.AddWithValue("@Name", TextBox1.Text);
            cmd.Parameters.AddWithValue("@Gender", checkRadioButton());
            cmd.Parameters.AddWithValue("@MobileNumber", TextBox2.Text);
            cmd.Parameters.AddWithValue("@EmailID", TextBox3.Text);
            cmd.Parameters.AddWithValue("@UserID", TextBox5.Text);
            cmd.Parameters.AddWithValue("@Password", TextBox6.Text);
            cmd.Parameters.AddWithValue("@Address", TextBox8.Text);
            cmd.Parameters.AddWithValue("@Country", DropDownList1.SelectedItem.Value);
            cmd.ExecuteNonQuery();
            con.Close();
            Response.Redirect("Homepage2.aspx");

        }

This is my  aspx.cs file for registration page. There is no compilation error, but after the Button1_Click event executed, the registration data is not saved into the database.

Body:
You would need to add a connection string into the SQLConnection constructor. The connection string itself is usual to keep in the web.config. So the code could be similar to:

var connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Do your insert here;
}


问:
Why are notSupported error responses handled differently in different QUERY intent scenarios?
This question was prompted by our previous question regarding review requirements for QUERY intents, found here.

Although we are currently unable to implement querying a detailed status of many of our devices, we would like to respond properly to attempts at QUERY intents. Specifically: with a notSupported error response seems appropriate. For a general user query, such as "Is the Desk light on?", this works as we would expect:

"That mode isn't available for the Desk light".

However, when attempting relative operations, such as "Dim the Desk light.", the same response format results in the following response by Google Home:

"Encountered an unknown error for the Desk light."

The same json response is returned in both scenarios:

```<code>{

"requestId": "****************",

"payload": {

    "devices": {
        "********": {
            "errorCode": "notSupported"
            }
        }
    }
}
</code>```

We have verified, by faking a query response with an actual brightness status, that the intent continues properly after the QUERY returns; receiving an EXECUTE intent next to effect the change in brightness.

We are unsure why a notSupported error is handled differently in this case; are we perhaps misunderstanding how an error response to this kind of QUERY should be formatted? If so, how can we distinguish a QUERY intent that will be followed by an EXECUTE intent from a solitary QUERY intent? Perhaps there is something else entirely that we have missed?

Thank you for reading.

答:
When giving a relative command, like "dim the desk light", the Google Assistant first needs to know the current brightness. To do this, the Assistant either needs to first query your server or use REPORT_STATE to store the data directly in the HomeGraph.

The responses are intentional. If I ask if the light is on, the device cannot respond to that type of query.

If I want to change the brightness, that is a mode that your light can support. Saying otherwise would be incorrect. However, the execution flow fails since it cannot retrieve your current brightness. Without knowing what it is now, it cannot relatively change the brightness and returns an error.

Saying something like "set my light to 10 percent" is an absolute change.

Body:
This question was prompted by our previous question regarding review requirements for QUERY intents, found here.

Although we are currently unable to implement querying a detailed status of many of our devices, we would like to respond properly to attempts at QUERY intents. Specifically: with a notSupported error response seems appropriate. For a general user query, such as "Is the Desk light on?", this works as we would expect:

"That mode isn't available for the Desk light".

However, when attempting relative operations, such as "Dim the Desk light.", the same response format results in the following response by Google Home:

"Encountered an unknown error for the Desk light."

The same json response is returned in both scenarios:

{

"requestId": "****************",

"payload": {

    "devices": {
        "********": {
            "errorCode": "notSupported"
            }
        }
    }
}

We have verified, by faking a query response with an actual brightness status, that the intent continues properly after the QUERY returns; receiving an EXECUTE intent next to effect the change in brightness.

We are unsure why a notSupported error is handled differently in this case; are we perhaps misunderstanding how an error response to this kind of QUERY should be formatted? If so, how can we distinguish a QUERY intent that will be followed by an EXECUTE intent from a solitary QUERY intent? Perhaps there is something else entirely that we have missed?

Thank you for reading.


问:
String concatenation for include path
Is there a way to concatenate 2 strings literals to form an include path?

Code stub:

```<code>#define INCLUDE_DIR "/include"
#include INCLUDE_DIR "/dummy.h"
</code>```

Looking at this question, the answers point in a different direction (compiler command line). It is mentioned here that it is seemingly not possible, but I wonder if the topic has been dug enough.

(I do have an use case in which this is relevant, please focus your answers/comments on this question only.)

答:
Simply avoid the space and the concatenation (##) and use the < > it makes all simplier:</p>

```<code>#include <QtCore/QtGlobal>

#define QT_VERSION_PREFIX QT_VERSION_MAJOR.QT_VERSION_MINOR.QT_VERSION_PATCH

#define _CONCATE(a, c) <a/QT_VERSION_PREFIX/a/private/c>
#include _CONCATE(QtWidgets, qwidgettextcontrol_p.h)
</code>```

Title: String concatenation for include path

Body:
Is there a way to concatenate 2 strings literals to form an include path?

Code stub:

#define INCLUDE_DIR "/include"
#include INCLUDE_DIR "/dummy.h"

Looking at this question, the answers point in a different direction (compiler command line). It is mentioned here that it is seemingly not possible, but I wonder if the topic has been dug enough.

(I do have an use case in which this is relevant, please focus your answers/comments on this question only.)

Body:
Simply avoid the space and the concatenation (##) and use the < > it makes all simplier:

#include <QtCore/QtGlobal>

#define QT_VERSION_PREFIX QT_VERSION_MAJOR.QT_VERSION_MINOR.QT_VERSION_PATCH

#define _CONCATE(a, c) <a/QT_VERSION_PREFIX/a/private/c>
#include _CONCATE(QtWidgets, qwidgettextcontrol_p.h)


答:
checked without the value checked should work fine.

```<code><input type="checkbox" checked/>
</code>```

Below should work if you remove oninput="onShowSeabedChange()"

```<code>$("#showSeabed").on("click", function(){
   scene3dManager.showSeabed = $('#showSeabed').is(':checked');
});
</code>```

Title: input javascript checked - unchecked

Body:
checked without the value checked should work fine.

<input type="checkbox" checked/>

Below should work if you remove oninput="onShowSeabedChange()"

$("#showSeabed").on("click", function(){
   scene3dManager.showSeabed = $('#showSeabed').is(':checked');
});


问:
UI client for command line ssh remote server manager
I learning to use the command line for remote server operation, since the usual ftp/sftp client are terribly slower the unix commands via ssh. But of course is not very practical if you're not an expert.

My question is: does it exist a app (or a webapp) that gives a UI to unix ssh remote commands? something that when for example I copy a file between two folder will use the cp command (wishfully giving you the options).

thanks

PS: I use Mac

答:
Not exactly a GUI for the shell, but nice for filesystem operations: MacFuse. Here is a short introduction into sshfs and MacFuse:

http://zanshin.net/2009/11/06/using-sshfs-macfuse-and-macfusion-to-access-remote-filesystems/


问:
Expected tensorflow model size from learned variables
When training convolutional neural networks for image classification tasks we generally want our algorithm to learn the filters (and biases) that transform a given image to its correct label. I have a few models I'm trying to compare in terms of model size, number of operations, accuracy, etc. However, the size of the model outputed from tensorflow, concretely the model.ckpt.data file that stores the values of all the variables in the graph, is not the one I expected. In fact, it seems to be three times bigger.

To go straight to the problem I'm gonna base my question on this Jupyter notebook. Below is the section where the variables (weights and biases) are defined:

```<code># Store layers weight & bias
weights = {
# 5x5 conv, 1 input, 32 outputs
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32]),dtype=tf.float32),
# 5x5 conv, 32 inputs, 64 outputs
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64]),dtype=tf.float32),
# fully connected, 7*7*64 inputs, 1024 outputs
'wd1': tf.Variable(tf.random_normal([7*7*64, 1024]),dtype=tf.float32),
# 1024 inputs, 10 outputs (class prediction)
'out': tf.Variable(tf.random_normal([1024, num_classes]),dtype=tf.float32)
}

biases = {
'bc1': tf.Variable(tf.random_normal([32]),dtype=tf.float32),
'bc2': tf.Variable(tf.random_normal([64]),dtype=tf.float32),
'bd1': tf.Variable(tf.random_normal([1024]),dtype=tf.float32),
'out': tf.Variable(tf.random_normal([num_classes]),dtype=tf.float32)
}
</code>```

I've added a couple of lines in order to save the model at the end of the training process:

```<code># Save the model
save_path = saver.save(sess, logdir+"model.ckpt")
print("Model saved in file: %s" % save_path)
</code>```

Adding up all those variables we would expect to get a model.ckpt.data file of size 12.45Mb (I've obtained this by just computing the number of float elements that our model learns and then convert that value to MegaBytes). But! the .data file saved is 39.3Mb. Why is this?

I've followed the same approach with a more complex network (a variation of ResNet) and my expected model.data size is also ~3x smaller than what the actual .data file is.

The data type of all these variables is float32.

答:
Adding up all those variables we would expect to get a model.ckpt.data file of size 12.45Mb

Traditionally, most of model parameters are in the first fully connected layer, in this case wd1. Computing only its size yields:

```<code>7*7*128 * 1024 * 4 = 25690112
</code>```

... or 25.6Mb. Note 4 coefficient, because the variable dtype=tf.float32, i.e. 4 bytes per parameter. Other layers also contribute to the model size, but not so drastically.

As you can see, your estimate 12.45Mb is a bit off (did you use 16bit per param?). The checkpoint also stores some general information, hence the overhead around 25%, which is still big, but not 300%.

[Update]

The model in question actually has FC1 layer of shape [7*7*64, 1024], as was clarified. So the calculated above size should be 12.5Mb, indeed. That made me look into the saved checkpoint more carefully.

After inspecting it, I noticed other big variables that I missed originally:

```<code>...
Variable_2 (DT_FLOAT) [3136,1024]
Variable_2/Adam (DT_FLOAT) [3136,1024]
Variable_2/Adam_1 (DT_FLOAT) [3136,1024]
...
</code>```

The Variable_2 is exactly wd1, but there are 2 more copies for the Adam optimizer. These variables are created by the Adam optimizer, they're called slots and hold the m and v accumulators for all trainable variables. Now the total size makes sense.

You can run the following code to compute the total size of the graph variables - 37.47Mb:

```<code>var_sizes = [np.product(list(map(int, v.shape))) * v.dtype.size
             for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)]
print(sum(var_sizes) / (1024 ** 2), 'MB')
</code>```

So the overhead is actually pretty small. Extra size is due to the optimizer.

Body:
When training convolutional neural networks for image classification tasks we generally want our algorithm to learn the filters (and biases) that transform a given image to its correct label. I have a few models I'm trying to compare in terms of model size, number of operations, accuracy, etc. However, the size of the model outputed from tensorflow, concretely the model.ckpt.data file that stores the values of all the variables in the graph, is not the one I expected. In fact, it seems to be three times bigger.

To go straight to the problem I'm gonna base my question on this Jupyter notebook. Below is the section where the variables (weights and biases) are defined:

# Store layers weight & bias
weights = {
# 5x5 conv, 1 input, 32 outputs
'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32]),dtype=tf.float32),
# 5x5 conv, 32 inputs, 64 outputs
'wc2': tf.Variable(tf.random_normal([5, 5, 32, 64]),dtype=tf.float32),
# fully connected, 7*7*64 inputs, 1024 outputs
'wd1': tf.Variable(tf.random_normal([7*7*64, 1024]),dtype=tf.float32),
# 1024 inputs, 10 outputs (class prediction)
'out': tf.Variable(tf.random_normal([1024, num_classes]),dtype=tf.float32)
}

biases = {
'bc1': tf.Variable(tf.random_normal([32]),dtype=tf.float32),
'bc2': tf.Variable(tf.random_normal([64]),dtype=tf.float32),
'bd1': tf.Variable(tf.random_normal([1024]),dtype=tf.float32),
'out': tf.Variable(tf.random_normal([num_classes]),dtype=tf.float32)
}

I've added a couple of lines in order to save the model at the end of the training process:

# Save the model
save_path = saver.save(sess, logdir+"model.ckpt")
print("Model saved in file: %s" % save_path)

Adding up all those variables we would expect to get a model.ckpt.data file of size 12.45Mb (I've obtained this by just computing the number of float elements that our model learns and then convert that value to MegaBytes). But! the .data file saved is 39.3Mb. Why is this?

I've followed the same approach with a more complex network (a variation of ResNet) and my expected model.data size is also ~3x smaller than what the actual .data file is.

The data type of all these variables is float32.

Body:
Adding up all those variables we would expect to get a model.ckpt.data file of size 12.45Mb

Traditionally, most of model parameters are in the first fully connected layer, in this case wd1. Computing only its size yields:

7*7*128 * 1024 * 4 = 25690112

... or 25.6Mb. Note 4 coefficient, because the variable dtype=tf.float32, i.e. 4 bytes per parameter. Other layers also contribute to the model size, but not so drastically.

As you can see, your estimate 12.45Mb is a bit off (did you use 16bit per param?). The checkpoint also stores some general information, hence the overhead around 25%, which is still big, but not 300%.

[Update]

The model in question actually has FC1 layer of shape [7*7*64, 1024], as was clarified. So the calculated above size should be 12.5Mb, indeed. That made me look into the saved checkpoint more carefully.

After inspecting it, I noticed other big variables that I missed originally:

...
Variable_2 (DT_FLOAT) [3136,1024]
Variable_2/Adam (DT_FLOAT) [3136,1024]
Variable_2/Adam_1 (DT_FLOAT) [3136,1024]
...

The Variable_2 is exactly wd1, but there are 2 more copies for the Adam optimizer. These variables are created by the Adam optimizer, they're called slots and hold the m and v accumulators for all trainable variables. Now the total size makes sense.

You can run the following code to compute the total size of the graph variables - 37.47Mb:

var_sizes = [np.product(list(map(int, v.shape))) * v.dtype.size
             for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)]
print(sum(var_sizes) / (1024 ** 2), 'MB')

So the overhead is actually pretty small. Extra size is due to the optimizer.


答:
From here: How do I loop through JSON object

You can foreach through an Object in PHP.

```<code><?php
    $objectJSON = JSON OBJECT;
    $string = '';
    foreach ($objectJSON[0] as $key => $value)
        {
            $values[] = $value;
        }
    $string = implode(",", $values);
?>
</code>```

$string ends up being what you need.

Title: Create a List of Values from a JSON Object in PHP

Body:
How can I convert the following JSON object array into an ordered list of values using PHP?

JSON Object

array:1 [▼
  0 => {#226 ▼
    +"sum(hour0)": "2098571"
    +"sum(hour1)": "1316168"
    +"sum(hour2)": "643316"
    +"sum(hour3)": "210643"
    +"sum(hour4)": "97135"
    +"sum(hour5)": "25334"
    +"sum(hour6)": "20451"
    +"sum(hour7)": "20639"
    +"sum(hour8)": "20382"
    +"sum(hour9)": "16966"
    +"sum(hour10)": "25301"
    +"sum(hour11)": "17352"
    +"sum(hour12)": "23883"
    +"sum(hour13)": "425294"
    +"sum(hour14)": "3776592"
    +"sum(hour15)": "5292751"
    +"sum(hour16)": "5945308"
    +"sum(hour17)": "952250"
    +"sum(hour18)": "0"
    +"sum(hour19)": "0"
    +"sum(hour20)": "0"
    +"sum(hour21)": "0"
    +"sum(hour22)": "0"
    +"sum(hour23)": "0"
  }
]

Desired Output

2098571,1315168,643316,210643,...

Body:
From here: How do I loop through JSON object

You can foreach through an Object in PHP.

<?php
    $objectJSON = JSON OBJECT;
    $string = '';
    foreach ($objectJSON[0] as $key => $value)
        {
            $values[] = $value;
        }
    $string = implode(",", $values);
?>

$string ends up being what you need.