问:
Paypal Express Checkout not Showing the Order summery
I am using the Paypal Express checkout in zend framework payments are working fine but there is an issues with the order summery on paypal checkout page.

It is not showing any order information there.

Here is my controller:

```<code>$storage = $this->getServiceLocator()->get('payum')->getStorage('Reisesparer\Model\PaymentDetails');

$details = $storage->create();
$details['PAYMENTREQUEST_0_CURRENCYCODE'] = 'EUR';
$details['PAYMENTREQUEST_0_AMT'] = $request->getPost('grandtotal_price');
$details['ORDER_CUSTOM_ID'] = $orderNumber;
$storage->update($details);
$captureToken =    this->getServiceLocator()->get('payum.security.token_factory')->createCaptureToken(               this->redirect()->toUrl($captureToken->getTargetUrl().'?amout='.$details['PAYMENTREQUEST_0_AMT']);
</code>```

How i can show the current transaction summery on the checkout page.

答:
You can provide item details in the same way as you provided currency etc. But you have to be careful while setting up details about items, specially about the total price, item numbers etc. Because they should be in sequential orders and calculated exactly.

```<code>$details['L_PAYMENTREQUEST_0_NAME0'] = 'Book One';
$details['L_PAYMENTREQUEST_0_NAME1'] = 'Book Two';
$details['L_PAYMENTREQUEST_0_AMT0'] = 25.00;
$details['L_PAYMENTREQUEST_0_AMT1'] = '22.00';
$details['PAYMENTREQUEST_0_ITEMAMT'] = 47.00;
</code>```

You must read the Doc for paypal express checkout to make it implement. For item details, search for Payment Details Item Type Fields on that doc page.

You can check this issue on order summary too.

Hope it helps you!

Body:
I am using the Paypal Express checkout in zend framework payments are working fine but there is an issues with the order summery on paypal checkout page.

It is not showing any order information there.

Here is my controller:

$storage = $this->getServiceLocator()->get('payum')->getStorage('Reisesparer\Model\PaymentDetails');

$details = $storage->create();
$details['PAYMENTREQUEST_0_CURRENCYCODE'] = 'EUR';
$details['PAYMENTREQUEST_0_AMT'] = $request->getPost('grandtotal_price');
$details['ORDER_CUSTOM_ID'] = $orderNumber;
$storage->update($details);
$captureToken =    this->getServiceLocator()->get('payum.security.token_factory')->createCaptureToken(               this->redirect()->toUrl($captureToken->getTargetUrl().'?amout='.$details['PAYMENTREQUEST_0_AMT']);

How i can show the current transaction summery on the checkout page.

Body:
You can provide item details in the same way as you provided currency etc. But you have to be careful while setting up details about items, specially about the total price, item numbers etc. Because they should be in sequential orders and calculated exactly.

$details['L_PAYMENTREQUEST_0_NAME0'] = 'Book One';
$details['L_PAYMENTREQUEST_0_NAME1'] = 'Book Two';
$details['L_PAYMENTREQUEST_0_AMT0'] = 25.00;
$details['L_PAYMENTREQUEST_0_AMT1'] = '22.00';
$details['PAYMENTREQUEST_0_ITEMAMT'] = 47.00;

You must read the Doc for paypal express checkout to make it implement. For item details, search for Payment Details Item Type Fields on that doc page.

You can check this issue on order summary too.

Hope it helps you!


来源: stackexchange

问:
Big ugly SQL query problem
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

```<code>SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id
</code>```

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

```<code>Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------
</code>```

答:
If you can create these functions then you can do:

```<code>SELECT Status.status_id,
       MaxOfList(l1.levelD,l2.levelD,l3.levelD,l4.levelD) AS ds_column,
       MaxOfList(l1.levelS,l2.levelS,l3.levelS,l4.levelS) AS ss_column
FROM Status s, Status_level l1, Status_level l2, Status_level l3, Status_level l4
WHERE l1.desc=s.desc1 AND l2.desc=s.desc2
      AND l3.desc=s.desc3 AND l4.desc=s.desc4;
</code>```

Note that I am assuming that null is not allowed in desc1-4

ContentLicense: CC BY-SA 2.5

Title: Big ugly SQL query problem

Body:
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------

Body:
If you can create these functions then you can do:

SELECT Status.status_id,
       MaxOfList(l1.levelD,l2.levelD,l3.levelD,l4.levelD) AS ds_column,
       MaxOfList(l1.levelS,l2.levelS,l3.levelS,l4.levelS) AS ss_column
FROM Status s, Status_level l1, Status_level l2, Status_level l3, Status_level l4
WHERE l1.desc=s.desc1 AND l2.desc=s.desc2
      AND l3.desc=s.desc3 AND l4.desc=s.desc4;

Note that I am assuming that null is not allowed in desc1-4


问:
Gradle 3.4 : Build profile using ConfigSlurper
I have the below tasks in build.gradle and my trying to get the wsdlURL value from config.groovy as per the environment

```<code>loadConfiguration()

task printProps << {
    println "WSDLURL:  $config.wsdlURL"
}

def loadConfiguration() {
    def environment = hasProperty('env') ? env : 'dev'
    System.setProperty('environment', environment)
    println "Environment is set to $environment"

    def configFile = file('config.groovy')
    def config = new ConfigSlurper(environment).parse(configFile.toURI().toURL())
    System.setProperty('config', config) \\line 52
}
</code>```

below is my config.groovy

```<code>environments {
    dev {
        wsdlURL = 'https://dev.com/ts/svs.asmx?wsdl'
    }

    qa {
        wsdlURL = 'https://qa.com/ts/svs.asmx?wsdl'
    }

    stg {
        wsdlURL = 'https://stg.com/ts/svs.asmx?wsdl'
    }

    prod {
        wsdlURL = 'https://prod.com/ts/svs.asmx?wsdl'
    }
}
</code>```

And when I run the gradle -q -Penv=prod printProps command its failing with below error

```<code>Environment is set to prod

FAILURE: Build failed with an exception.

* Where:
Build file 'build.gradle' line: 52

* What went wrong:
A problem occurred evaluating root project 'SignService'.
> No signature of method: static java.lang.System.setProperty() is applicable fo
r argument types: (java.lang.String, groovy.util.ConfigObject) values: [config,
[wsdlURL:https://prod.com/ts/svs.asmx?wsdl]]
Possible solutions: setProperty(java.lang.String, java.lang.String), getProperty
(java.lang.String), getProperty(java.lang.String, java.lang.String), hasProperty
(java.lang.String), getProperties(), getProperties()
</code>```

below is my environment details

```<code>------------------------------------------------------------
Gradle 3.4
------------------------------------------------------------

Build time:   2017-02-20 14:49:26 UTC
Revision:     73f32d68824582945f5ac1810600e8d87794c3d4

Groovy:       2.4.7
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_40 (Oracle Corporation 25.40-b25)
OS:           Windows 7 6.1 amd64
</code>```

Looks like gradle couldnt set groovy object into system property, can some one please help me to fix it?

答:
The error message is pretty clear

System.setProperty(key, value) expects two String arguments but you are passing a String and a ConfigObject.

Perhaps you want to

```<code>System.properties['config'] = config
</code>```

Or

```<code>System.properties.put('config', config)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the below tasks in build.gradle and my trying to get the wsdlURL value from config.groovy as per the environment

loadConfiguration()

task printProps << {
    println "WSDLURL:  $config.wsdlURL"
}

def loadConfiguration() {
    def environment = hasProperty('env') ? env : 'dev'
    System.setProperty('environment', environment)
    println "Environment is set to $environment"

    def configFile = file('config.groovy')
    def config = new ConfigSlurper(environment).parse(configFile.toURI().toURL())
    System.setProperty('config', config) \\line 52
}

below is my config.groovy

environments {
    dev {
        wsdlURL = 'https://dev.com/ts/svs.asmx?wsdl'
    }

    qa {
        wsdlURL = 'https://qa.com/ts/svs.asmx?wsdl'
    }

    stg {
        wsdlURL = 'https://stg.com/ts/svs.asmx?wsdl'
    }

    prod {
        wsdlURL = 'https://prod.com/ts/svs.asmx?wsdl'
    }
}

And when I run the gradle -q -Penv=prod printProps command its failing with below error

Environment is set to prod

FAILURE: Build failed with an exception.

* Where:
Build file 'build.gradle' line: 52

* What went wrong:
A problem occurred evaluating root project 'SignService'.
> No signature of method: static java.lang.System.setProperty() is applicable fo
r argument types: (java.lang.String, groovy.util.ConfigObject) values: [config,
[wsdlURL:https://prod.com/ts/svs.asmx?wsdl]]
Possible solutions: setProperty(java.lang.String, java.lang.String), getProperty
(java.lang.String), getProperty(java.lang.String, java.lang.String), hasProperty
(java.lang.String), getProperties(), getProperties()

below is my environment details

------------------------------------------------------------
Gradle 3.4
------------------------------------------------------------

Build time:   2017-02-20 14:49:26 UTC
Revision:     73f32d68824582945f5ac1810600e8d87794c3d4

Groovy:       2.4.7
Ant:          Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM:          1.8.0_40 (Oracle Corporation 25.40-b25)
OS:           Windows 7 6.1 amd64

Looks like gradle couldnt set groovy object into system property, can some one please help me to fix it?

Body:
The error message is pretty clear

System.setProperty(key, value) expects two String arguments but you are passing a String and a ConfigObject.

Perhaps you want to

System.properties['config'] = config

Or

System.properties.put('config', config)


问:
PHP Posting data to another php file hosted in a remote server using file_get_contents
I have access to 3 different remote servers. They all host the same php file, it's named processing.php.

And in a different server I have 3 pages :

index.html : that contains a form with POST method that send data to forward.php

forward.php : that forward the form values to processing.php on the other servers

processing.php : Display the posted data

The Problem : the code in processing.php is not executed and the returned result is a plain text of the source code of processing.php!!

forward.php :

```<code>$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
rtrim($_POST['listserver'],"-");
$listServer = explode("-",$_POST['listserver']);

foreach ($listServer as $server){
    if(!empty($server)){
        $url = 'http://'.$server.'/processing.php';
        $data = array('field1' => $field1, 'field2' => $field2);
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded",
                'method'  => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        if ($result === FALSE) {
            echo "You can't ";
        }else{
            echo ('result : '.$result);
        }
    }
}
</code>```

Processing.php

```<code>$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$result = $field1+$field2;
$myFile = "files/result.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $result);
fclose($fh);
</code>```

But in all the servers, result.txt is empty!!

答:
Thanx to @MarkusZeller suggestion, I managed to get it work using cURL.

This thread was very helpful, thank you Stack Over Flow community !

Body:
I have access to 3 different remote servers. They all host the same php file, it's named processing.php.

And in a different server I have 3 pages :

index.html : that contains a form with POST method that send data to forward.php

forward.php : that forward the form values to processing.php on the other servers

processing.php : Display the posted data

The Problem : the code in processing.php is not executed and the returned result is a plain text of the source code of processing.php!!

forward.php :

$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
rtrim($_POST['listserver'],"-");
$listServer = explode("-",$_POST['listserver']);

foreach ($listServer as $server){
    if(!empty($server)){
        $url = 'http://'.$server.'/processing.php';
        $data = array('field1' => $field1, 'field2' => $field2);
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded",
                'method'  => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        if ($result === FALSE) {
            echo "You can't ";
        }else{
            echo ('result : '.$result);
        }
    }
}

Processing.php

$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$result = $field1+$field2;
$myFile = "files/result.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $result);
fclose($fh);

But in all the servers, result.txt is empty!!


问:
How can I get value from react modal bootstrap?
How can I get value from bootstrap modal? I'm using reacstrap  https://github.com/reactstrap

Here is my page that call the modal

```<code>import { ButtonGroup, Button, Input, Row, Col } from 'reactstrap';
import RegisterLookup from '../lookup/RegisterLookup';

<RegisterLookup
  isOpen={this.state.register}
  toggle={this.toggleRegister}
  className={''}
/>
</code>```

and here is my modal component:

```<code>  register() {
    console.log("da")
  }

render() {
    return (
      <div>
        <Modal isOpen={this.props.isOpen} toggle={this.props.toggle} className={this.props.className} size="lg">
          <ModalHeader toggle={this.props.toggle}>Register</ModalHeader>
          <ModalBody>
            <div className="row mb-2">
              <div className="col-sm-12">
                <Row>
                  <Col md="6" xs="12">
                    <FormGroup row>
                      <Label sm="4">Enter your name <span className="text-danger">*</span></Label>
                      <Col>
                        <Input />
                      </Col>
                    </FormGroup>
                  </Col>
                </Row>
              </div>
            </div>

          </ModalBody>
          <ModalFooter>
            <Button className="pull-right" type="button" color="primary" onClick={() => { this.register(); }}>
              <span className="hidden-xs-down">Register </span>
            </Button>
          </ModalFooter>
        </Modal>
      </div>
    );
  }
}

RegisterLookup.defaultProps = {
  isOpen: PropTypes.bool,
  toggle: PropTypes.func,
  className: PropTypes.string,
};

RegisterLookup.propTypes = {
  isOpen: PropTypes.bool,
  toggle: PropTypes.func,
  className: PropTypes.string,
};
</code>```

It show the modal :

but how can I get the value I enter in modal to my page that call the modal? Thanks in advance.

答:
You can send the value back with a function you send as a prop from the parent to the modal.

Here's an example that I have simplified to highlight the changes you need to make. The Modal controls the state of the Input but when you hit the button the local reg() function is called, which in turn calls the register() function from the parent because it's being passed down as a prop called onRegister. We pass name as the argument to that function call.

Note that I've also added the nameChange() function which you didn't have. This function is called whenever the value of the Input is changed (e.g by a keypress) and updates the local state.

Parent:

```<code>register(name) {
  console.log(name);
}

render() {
  return(
    <RegisterLookup onRegister={this.register} />
  );
}
</code>```

Modal:

```<code>nameChange = (e) => {
  this.setState({name: e.target.value});
}

reg = () => {
  this.props.onRegister(this.state.name);
}

render() {
  return(
    <Modal>
      Enter your name: <Input onChange={this.nameChange} />
      <Button onClick={this.reg}>Register</Button>
    </Modal>
  );
}
</code>```

Body:
How can I get value from bootstrap modal? I'm using reacstrap  https://github.com/reactstrap

Here is my page that call the modal

import { ButtonGroup, Button, Input, Row, Col } from 'reactstrap';
import RegisterLookup from '../lookup/RegisterLookup';

<RegisterLookup
  isOpen={this.state.register}
  toggle={this.toggleRegister}
  className={''}
/>

and here is my modal component:

  register() {
    console.log("da")
  }

render() {
    return (

        <Modal isOpen={this.props.isOpen} toggle={this.props.toggle} className={this.props.className} size="lg">
          <ModalHeader toggle={this.props.toggle}>Register</ModalHeader>
          <ModalBody>

                <Row>
                  <Col md="6" xs="12">
                    <FormGroup row>
                      Enter your name *
                      <Col>
                        <Input />
                      </Col>
                    </FormGroup>
                  </Col>
                </Row>

          </ModalBody>
          <ModalFooter>
            <Button className="pull-right" type="button" color="primary" onClick={() => { this.register(); }}>
              Register
            </Button>
          </ModalFooter>
        </Modal>

    );
  }
}

RegisterLookup.defaultProps = {
  isOpen: PropTypes.bool,
  toggle: PropTypes.func,
  className: PropTypes.string,
};

RegisterLookup.propTypes = {
  isOpen: PropTypes.bool,
  toggle: PropTypes.func,
  className: PropTypes.string,
};

It show the modal :

but how can I get the value I enter in modal to my page that call the modal? Thanks in advance.

Body:
You can send the value back with a function you send as a prop from the parent to the modal.

Here's an example that I have simplified to highlight the changes you need to make. The Modal controls the state of the Input but when you hit the button the local reg() function is called, which in turn calls the register() function from the parent because it's being passed down as a prop called onRegister. We pass name as the argument to that function call.

Note that I've also added the nameChange() function which you didn't have. This function is called whenever the value of the Input is changed (e.g by a keypress) and updates the local state.

Parent:

register(name) {
  console.log(name);
}

render() {
  return(
    <RegisterLookup onRegister={this.register} />
  );
}

Modal:

nameChange = (e) => {
  this.setState({name: e.target.value});
}

reg = () => {
  this.props.onRegister(this.state.name);
}

render() {
  return(
    <Modal>
      Enter your name: <Input onChange={this.nameChange} />
      <Button onClick={this.reg}>Register</Button>
    </Modal>
  );
}

ContentLicense: CC BY-SA 4.0


问:
draggable is not a function - how to add draggable as an extension to jQuery UI?
I am wondering how can I add the draggable (found here) functionality as an extension method in my project. I have jquery and jQuery UI already in the project and I am not allowed to extend the original files, therefore I need to add it as an extension and initialize it.

I've done something similar already (see here), so now I have one extension function in my extension file. But I can't figure our how to do add the draggable in my extension file.

Finally, I am initializing the extension methods like this :

```<code> string init = "var init = function() { " +
            "initJUI();" +
            "if (typeof addJqueryEasing == 'function' ) { addJqueryEasing(jQuery, window); } ;"
</code>```

Any tips?

答:
I think you need to initialise like this - </p>

```<code>var init = function() {
    initJUI();
    if (typeof addJqueryEasing == 'function') {
        addJqueryEasing(jQuery, window);
    }
};
init();
</code>```

<p>OR </p>

```<code>(function() {
    initJUI();
    if (typeof addJqueryEasing == 'function') {
        addJqueryEasing(jQuery, window);
    }
}());
</code>```

Body:
I am wondering how can I add the draggable (found here) functionality as an extension method in my project. I have jquery and jQuery UI already in the project and I am not allowed to extend the original files, therefore I need to add it as an extension and initialize it.

I've done something similar already (see here), so now I have one extension function in my extension file. But I can't figure our how to do add the draggable in my extension file.

Finally, I am initializing the extension methods like this :

 string init = "var init = function() { " +
            "initJUI();" +
            "if (typeof addJqueryEasing == 'function' ) { addJqueryEasing(jQuery, window); } ;"

Any tips?

Body:
I think you need to initialise like this -

var init = function() {
    initJUI();
    if (typeof addJqueryEasing == 'function') {
        addJqueryEasing(jQuery, window);
    }
};
init();

OR

(function() {
    initJUI();
    if (typeof addJqueryEasing == 'function') {
        addJqueryEasing(jQuery, window);
    }
}());


问:
Why wont my email validation work? PHP
I have used

```<code>if (!preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)) {
    [PRINT ERROR]
}
</code>```

&

```<code>if (!eregi( "^[0-9]+$", $email)) {
    [PRINT ERROR]
}
</code>```

&

```<code>if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    [PRINT ERROR]
}
</code>```

I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..

I am using PHP

答: Check your php version. eregi is deprecated after 5.3.0. Also, the regex is not correct.</p>

Title: Why wont my email validation work? PHP

Body:
I have used

if (!preg_match('/[a-z||0-9]@[a-z||0-9].[a-z]/', $email)) {
    [PRINT ERROR]
}

&

if (!eregi( "^[0-9]+$", $email)) {
    [PRINT ERROR]
}

&

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    [PRINT ERROR]
}

I have also tried taking out the ! and make it work backwards but for some reason NONE of those work to find out if it is valid. Any ideas why?...
I have it in an else if statement, Im not sure if that could be the cause..

I am using PHP


问:
how to change ProgressBar color?
i want to change Horizontal ProgressBar color

i have tried this

How to change the color of an indefinite ProgressBar?

its not working still progress run in blue color

this is my code

```<code><ProgressBar
                 android:id="@+id/mini_progress"
                 android:layout_marginLeft="10dip"
                 android:layout_marginRight="10dip"
                 style="?android:attr/progressBarStyleHorizontal"
                 android:layout_width="match_parent"
                 android:layout_height="20dip"
                 android:layout_gravity="center_horizontal"
                 android:indeterminate="false"
                 android:indeterminateBehavior="repeat"
                 android:indeterminateOnly="true"
                 android:visibility="gone"/>
</code>```

how i can change the color to Pink ?

答:
Since API 21 it's a one liner:</p>

```<code><ProgressBar
            ...
            android:progressTint="@color/colorAccent"/>
</code>```

Title: how to change ProgressBar color?

Body:
i want to change Horizontal ProgressBar color

i have tried this

How to change the color of an indefinite ProgressBar?

its not working still progress run in blue color

this is my code

<ProgressBar
                 android:id="@+id/mini_progress"
                 android:layout_marginLeft="10dip"
                 android:layout_marginRight="10dip"
                 style="?android:attr/progressBarStyleHorizontal"
                 android:layout_width="match_parent"
                 android:layout_height="20dip"
                 android:layout_gravity="center_horizontal"
                 android:indeterminate="false"
                 android:indeterminateBehavior="repeat"
                 android:indeterminateOnly="true"
                 android:visibility="gone"/>

how i can change the color to Pink ?

Body:
Since API 21 it's a one liner:

<ProgressBar
            ...
            android:progressTint="@color/colorAccent"/>


问:
How to heapify array of types in julia
In julia I have created given type:

```<code>type Event
  clientNumber
  time
end
</code>```

Then I created an array which elements are of type Event:

```<code>e1 = Event(1, 12)
e2 = Event(2, 13)
e3 = Event(3, 2)
events = [e1, e2, e3]
</code>```

My question is: how to heapify this array by field time of type Event? If it was just simple array of Int's it would look just like this:

```<code>arr = [4, 3, 21, 54, 1]
Collections.heapify!(arr)
</code>```

but I don't know how to compare these events in heap.

Code:

```<code>Collections.heapify!(events)
</code>```

returns error:

```<code>MethodError: no method matching isless(::Event, ::Event)
</code>```

答:
One way to solve the problem is to define the method Julia is complaining about, like so:

```<code>Base.isless(a::Event,b::Event) = isless(a.time,b.time)
</code>```

Now, Collections.heapify!(events) should work.

Title: How to heapify array of types in julia

Body:
In julia I have created given type:

type Event
  clientNumber
  time
end

Then I created an array which elements are of type Event:

e1 = Event(1, 12)
e2 = Event(2, 13)
e3 = Event(3, 2)
events = [e1, e2, e3]

My question is: how to heapify this array by field time of type Event? If it was just simple array of Int's it would look just like this:

arr = [4, 3, 21, 54, 1]
Collections.heapify!(arr)

but I don't know how to compare these events in heap.

Code:

Collections.heapify!(events)

returns error:

MethodError: no method matching isless(::Event, ::Event)

Body:
One way to solve the problem is to define the method Julia is complaining about, like so:

Base.isless(a::Event,b::Event) = isless(a.time,b.time)

Now, Collections.heapify!(events) should work.


问:
python - readable list of objects
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

```<code><__main__.evolutions instance at 0x01B8EA08>
</code>```

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

答:
Checkout the __str__() and __repr__() methods.

See http://docs.python.org/reference/datamodel.html#object.__repr__

Title: python - readable list of objects

Body:
This is probably a kinda commonly asked question but I could do with help on this. I have a list of class objects and I'm trying to figure out how to make it print an item from that class but rather than desplaying in the;

<__main__.evolutions instance at 0x01B8EA08>

but instead to show a selected attribute of a chosen object of the class. Can anyone help with that?

OwnerDisplayName: Peter Rowell

LastEditorDisplayName: Greg Hewgill


问:
how can I keep partition'number not change when I use window.partitionBy() function with spark/scala?
I have a RDD , the RDD' partition of result changes to 200 when I use window,can I not change partition when I use window?

This is my code:

```<code>val rdd= sc.parallelize(List(1,3,2,4,5,6,7,8),4)
val result = rdd.toDF("values").withColumn("csum", sum(col("values")).over(Window.partitionBy(col("values")))).rdd
println(result.getNumPartitions + "rdd2")
</code>```

My input partition is 4, why result partition is 200?

I want my result partition to be also 4.

Is there any cleaner solution?

答:
Note: As mentioned by @eliasah - it's not possible to avoid
  repartition when using window functions with spark

Why result partition is 200?

Spark doc
The default value of spark.sql.shuffle.partitions which
Configures the number of partitions to use when shuffling data for joins or aggregations - is 200

How can I repartition to 4?

You can use:

```<code>coalesce(4)
</code>```

or

```<code>repartition(4)
</code>```

spark doc

coalesce(numPartitions)     Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.

repartition(numPartitions) Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network.

Body:
I have a RDD , the RDD' partition of result changes to 200 when I use window,can I not change partition when I use window?

This is my code:

val rdd= sc.parallelize(List(1,3,2,4,5,6,7,8),4)
val result = rdd.toDF("values").withColumn("csum", sum(col("values")).over(Window.partitionBy(col("values")))).rdd
println(result.getNumPartitions + "rdd2")

My input partition is 4, why result partition is 200?

I want my result partition to be also 4.

Is there any cleaner solution?

Body:
Note: As mentioned by @eliasah - it's not possible to avoid
  repartition when using window functions with spark

Why result partition is 200?

Spark doc
The default value of spark.sql.shuffle.partitions which
Configures the number of partitions to use when shuffling data for joins or aggregations - is 200

How can I repartition to 4?

You can use:

coalesce(4)

or

repartition(4)

spark doc

coalesce(numPartitions)     Decrease the number of partitions in the RDD to numPartitions. Useful for running operations more efficiently after filtering down a large dataset.

repartition(numPartitions) Reshuffle the data in the RDD randomly to create either more or fewer partitions and balance it across them. This always shuffles all data over the network.


问:
why use distinct function was different in sql Query result and Linq result?
this is my raw data

LINQ code

```<code>   public PartialViewResult Menu()
        {
            IEnumerable<string> categories = repository.Products
                        .Select(x => x.Category)
                        .Distinct();
            return PartialView(categories.Distinct());
        }
</code>```

LINQ result

Why use distinct function , LINQ have the different result

答:
There are sometimes spaces at the end of the category. You should not store them. You could fix it in the SELECT query with Trim:

```<code>IEnumerable<string> categories = repository.Products
                    .Select(x => x.Category.Trim())
                    .Distinct();
</code>```

But instead of storing the category as string in your product table redundantly you should have a foreign-key here to another table Category >> Database normalization

Body:
this is my raw data

LINQ code

   public PartialViewResult Menu()
        {
            IEnumerable<string> categories = repository.Products
                        .Select(x => x.Category)
                        .Distinct();
            return PartialView(categories.Distinct());
        }

LINQ result

Why use distinct function , LINQ have the different result

Body:
There are sometimes spaces at the end of the category. You should not store them. You could fix it in the SELECT query with Trim:

IEnumerable<string> categories = repository.Products
                    .Select(x => x.Category.Trim())
                    .Distinct();

But instead of storing the category as string in your product table redundantly you should have a foreign-key here to another table Category >> Database normalization


问:
How do update a scheduled quartz Job?
Both of the below snippets give this error:

org.quartz.SchedulerException: Jobs added with no trigger must be
  durable.

```<code>  JobDetail job = scheduler.getJobDetail(jobKey(jobInfo));
  job.getJobDataMap().put(JOB_CONTENT, objectMapper.writeValueAsString(jobInfo));
  scheduler.addJob(job, true);

  JobDetail job = JobBuilder
        .newJob(MyJob.class)
        .usingJobData(JOB_CONTENT, objectMapper.writeValueAsString(jobInfo))
        .withIdentity(jobKey(jobInfo))
        .build();
  scheduler.addJob(job, true);
</code>```

答:
With non durable jobs, you must use scheduler.addJob(job, true, true) instead, with 3 parameters. The third parameter tells Quartz to store the job (in RAM) until it gets scheduled, that is until you add a trigger for it:

void addJob(JobDetail jobDetail,
              boolean replace,
              boolean storeNonDurableWhileAwaitingScheduling)
              throws SchedulerException

With the storeNonDurableWhileAwaitingScheduling parameter set to true, a non-durable job can be stored. Once it is scheduled, it will resume normal non-durable behavior (i.e. be deleted once there are no remaining associated triggers).

Title: How do update a scheduled quartz Job?

Body:
Both of the below snippets give this error:

org.quartz.SchedulerException: Jobs added with no trigger must be
  durable.

  JobDetail job = scheduler.getJobDetail(jobKey(jobInfo));
  job.getJobDataMap().put(JOB_CONTENT, objectMapper.writeValueAsString(jobInfo));
  scheduler.addJob(job, true);

  JobDetail job = JobBuilder
        .newJob(MyJob.class)
        .usingJobData(JOB_CONTENT, objectMapper.writeValueAsString(jobInfo))
        .withIdentity(jobKey(jobInfo))
        .build();
  scheduler.addJob(job, true);


问:
How to pass tag id to to onClick function in react?
I want to pass id of th tag  to on click function. Suppose i want to print the id of  in click() function console.log.
here is the code-

```<code><thead>
 <tr>
    <th id='name' onClick={this.click.bind(this)}>Name</th>
    <th id='phone' onClick={this.click.bind(this)}>Phone number</th>
    <th id='email' onClick={this.click.bind(this)}>Email</th>
 </tr>
</thead>
</code>```

the click() function-

```<code>click(){
console.log('the clicked id is:') //here i want the id
}
</code>```

答:
Bind takes arguments

```<code>this.click.bind(this, 'phone')

click(phone) {
  // ...
}
</code>```

or use es6 arrow functions

```<code>onClick={() => this.click('phone')}
</code>```

Body:
I want to pass id of th tag  to on click function. Suppose i want to print the id of  in click() function console.log.
here is the code-

    Name
    Phone number
    Email

the click() function-

click(){
console.log('the clicked id is:') //here i want the id
}

Body:
Bind takes arguments

this.click.bind(this, 'phone')

click(phone) {
  // ...
}

or use es6 arrow functions

onClick={() => this.click('phone')}


问:
create custom function for date difference excluding weekends and holidays in oracle sql
I need to calculate the number of days between two dates as decimal, excluding the weekends and holidays by using a custom function in Oracle SQL.
There are similar questions on the site; however as I could see, none of them asks for an output as decimal using a custom function. The reason why I need a decimal is to be able to use/extract time component afterwards. If there is already a question like this, please just share the link.

Tried to write a function as below with the help of the additional content I found on the internet thanks to the author.  The inner subqueries works fine seperately, but it doesn't work as a whole function.

In brief, the idea is:

(calculate the day difference between startdate and enddate) -> (exclude the number of weekend days between startdate and enddate) -> (exclude the number of weekends between startdate and enddate)

When I try to save the function, it gives the error PLS-00103: Encountered the symbol "end-of-file". Since I am already new in functions maybe missing something basic.

Lastly, also please let me know if you have suggestions on how to make the code more efficient.

Thanks in advance!

```<code>CREATE OR REPLACE FUNCTION  NET_WORKING_DAYS (startdate IN DATE, enddate IN DATE)
RETURN NUMBER IS
  WORKINGDAYS_BETWEEN NUMBER;
BEGIN

SELECT

    -- number of days between startdate and enddate
      (
        SELECT (TO_DATE('20160831150000','YYYYMMDDHH24MISS')  - TO_DATE('20160801000000','YYYYMMDDHH24MISS') ) DAYS_BETWEEN
        FROM DUAL
      )
    -
    -- number of weekend days (after a given date)
      (
        SELECT COUNT(1)  WEEKEND_DAYS_BETWEEN
        FROM
        (
          SELECT
            TO_DATE('20160701000000','YYYYMMDDHH24MISS') + SEQ as day_date,     --2016/07/01 is a constant/given date for this formula
            TO_CHAR(TO_DATE('20160701000000','YYYYMMDDHH24MISS') + SEQ , 'D') day_of_week
          FROM
            (
                SELECT ROWNUM-1 SEQ
                FROM   ( SELECT 1 FROM  DUAL CONNECT BY LEVEL<= 365 * 5) --5 years
            )
          ORDER BY 1
        )
        WHERE day_of_week IN (6,7)
          AND day_date > TO_DATE('20160801000000','YYYYMMDDHH24MISS')     --this should be replaced with startdate parameter
          AND day_date < TO_DATE('20160831000000','YYYYMMDDHH24MISS')      --this should be replaced with enddate parameter
      )
    -
    -- number of holidays (after a given date)
      (
        SELECT COUNT(1)
        FROM HOLIDAYS
        WHERE HOLIDAY_DATE > TO_DATE('20160801000000','YYYYMMDDHH24MISS')     --this should be replaced with startdate parameter
          AND HOLIDAY_DATE < TO_DATE('20160831000000','YYYYMMDDHH24MISS')      --this should be replaced with enddate parameter
      )
INTO WORKINGDAYS_BETWEEN
FROM DUAL;

RETURN WORKINGDAYS_BETWEEN;
END NET_WORKING_DAYS;
</code>```

**EDIT-1: Holidays are already defined in HOLIDAYS table in the database and for this date range from 20160801000000 to 20160831000000 , 30.06.2016 is the holiday date.

答:
You do not need to use a row generator to enumerate every day to get the number of week days - it can be done using a simple calculation:

From my answer here:

```<code>CREATE FUNCTION getWorkingDays (
  in_start_date IN  DATE,
  in_end_date   IN  DATE
) RETURN NUMBER DETERMINISTIC
IS
  p_start_date   DATE;
  p_end_date     DATE;
  p_working_days NUMBER;
  p_holiday_days NUMBER;
BEGIN
  IF in_start_date IS NULL OR in_end_date IS NULL THEN
    RETURN NUll;
  END IF;

  p_start_date := LEAST( in_start_date, in_end_date );
  p_end_date   := GREATEST( in_start_date, in_end_date );

  -- 5/7 * ( Number of days between monday of the week containing the start date
  --         and monday of the week containing the end date )
  -- + LEAST( day of week for end date, 5 )
  -- - LEAST( day of week for start date, 5 )
  p_working_days := ( TRUNC( p_end_date, 'IW' ) - TRUNC( p_start_date, 'IW' ) ) * 5 / 7
                    + LEAST( p_end_date - TRUNC( p_end_date, 'IW' ), 5 )
                    - LEAST( p_start_date - TRUNC( p_start_date, 'IW' ), 5 );

  SELECT COALESCE(
           SUM(
             LEAST( p_end_date, holiday_date + INTERVAL '1' DAY )
             - GREATEST( p_start_date, holiday_date )
           ),
           0
         )
  INTO   p_holiday_days
  FROM   Holidays
  WHERE  HOLIDAY_DATE BETWEEN TRUNC( p_start_date )
                      AND     TRUNC( p_end_date )
  AND    HOLIDAY_DATE - TRUNC( HOLIDAY_DATE, 'IW' ) < 5;

  RETURN GREATEST( p_working_days - p_holiday_days, 0 );
END;
/
</code>```

Body:
I need to calculate the number of days between two dates as decimal, excluding the weekends and holidays by using a custom function in Oracle SQL.
There are similar questions on the site; however as I could see, none of them asks for an output as decimal using a custom function. The reason why I need a decimal is to be able to use/extract time component afterwards. If there is already a question like this, please just share the link.

Tried to write a function as below with the help of the additional content I found on the internet thanks to the author.  The inner subqueries works fine seperately, but it doesn't work as a whole function.

In brief, the idea is:

(calculate the day difference between startdate and enddate) -> (exclude the number of weekend days between startdate and enddate) -> (exclude the number of weekends between startdate and enddate)

When I try to save the function, it gives the error PLS-00103: Encountered the symbol "end-of-file". Since I am already new in functions maybe missing something basic.

Lastly, also please let me know if you have suggestions on how to make the code more efficient.

Thanks in advance!

CREATE OR REPLACE FUNCTION  NET_WORKING_DAYS (startdate IN DATE, enddate IN DATE)
RETURN NUMBER IS
  WORKINGDAYS_BETWEEN NUMBER;
BEGIN

SELECT

    -- number of days between startdate and enddate
      (
        SELECT (TO_DATE('20160831150000','YYYYMMDDHH24MISS')  - TO_DATE('20160801000000','YYYYMMDDHH24MISS') ) DAYS_BETWEEN
        FROM DUAL
      )
    -
    -- number of weekend days (after a given date)
      (
        SELECT COUNT(1)  WEEKEND_DAYS_BETWEEN
        FROM
        (
          SELECT
            TO_DATE('20160701000000','YYYYMMDDHH24MISS') + SEQ as day_date,     --2016/07/01 is a constant/given date for this formula
            TO_CHAR(TO_DATE('20160701000000','YYYYMMDDHH24MISS') + SEQ , 'D') day_of_week
          FROM
            (
                SELECT ROWNUM-1 SEQ
                FROM   ( SELECT 1 FROM  DUAL CONNECT BY LEVEL<= 365 * 5) --5 years
            )
          ORDER BY 1
        )
        WHERE day_of_week IN (6,7)
          AND day_date > TO_DATE('20160801000000','YYYYMMDDHH24MISS')     --this should be replaced with startdate parameter
          AND day_date < TO_DATE('20160831000000','YYYYMMDDHH24MISS')      --this should be replaced with enddate parameter
      )
    -
    -- number of holidays (after a given date)
      (
        SELECT COUNT(1)
        FROM HOLIDAYS
        WHERE HOLIDAY_DATE > TO_DATE('20160801000000','YYYYMMDDHH24MISS')     --this should be replaced with startdate parameter
          AND HOLIDAY_DATE < TO_DATE('20160831000000','YYYYMMDDHH24MISS')      --this should be replaced with enddate parameter
      )
INTO WORKINGDAYS_BETWEEN
FROM DUAL;

RETURN WORKINGDAYS_BETWEEN;
END NET_WORKING_DAYS;

**EDIT-1: Holidays are already defined in HOLIDAYS table in the database and for this date range from 20160801000000 to 20160831000000 , 30.06.2016 is the holiday date.

Body:
You do not need to use a row generator to enumerate every day to get the number of week days - it can be done using a simple calculation:

From my answer here:

CREATE FUNCTION getWorkingDays (
  in_start_date IN  DATE,
  in_end_date   IN  DATE
) RETURN NUMBER DETERMINISTIC
IS
  p_start_date   DATE;
  p_end_date     DATE;
  p_working_days NUMBER;
  p_holiday_days NUMBER;
BEGIN
  IF in_start_date IS NULL OR in_end_date IS NULL THEN
    RETURN NUll;
  END IF;

  p_start_date := LEAST( in_start_date, in_end_date );
  p_end_date   := GREATEST( in_start_date, in_end_date );

  -- 5/7 * ( Number of days between monday of the week containing the start date
  --         and monday of the week containing the end date )
  -- + LEAST( day of week for end date, 5 )
  -- - LEAST( day of week for start date, 5 )
  p_working_days := ( TRUNC( p_end_date, 'IW' ) - TRUNC( p_start_date, 'IW' ) ) * 5 / 7
                    + LEAST( p_end_date - TRUNC( p_end_date, 'IW' ), 5 )
                    - LEAST( p_start_date - TRUNC( p_start_date, 'IW' ), 5 );

  SELECT COALESCE(
           SUM(
             LEAST( p_end_date, holiday_date + INTERVAL '1' DAY )
             - GREATEST( p_start_date, holiday_date )
           ),
           0
         )
  INTO   p_holiday_days
  FROM   Holidays
  WHERE  HOLIDAY_DATE BETWEEN TRUNC( p_start_date )
                      AND     TRUNC( p_end_date )
  AND    HOLIDAY_DATE - TRUNC( HOLIDAY_DATE, 'IW' ) < 5;

  RETURN GREATEST( p_working_days - p_holiday_days, 0 );
END;
/


问:
How to write to SRAM on STm32 nucleo board (mbed)
I want to store a simple integer in the SRAM on the chip. (Cortex M4)
The program I use is mbed online.
I know that the address for the SRAM starts at 0x2000 0000 and the chip has 4KB of said memory.

I have read the datasheet and the bitbanding part, but it just doesn't make sense to me.

Can someone please explain to me how I can store for example the number 5 in the SRAM and read it again?

Current code is like this(c is an integer that the user changes with a button):

    if(c==100){
    temp=c;
    MBX_B0 = 1;      // Word write
    temp = MBX_B7;   // Word read

    TIMER_B0 = temp; // Byte write
    return TIMER_B7; // Byte read
}
    pc.printf("%d",temp);

It just stops running once c==100
THE VALUE SHOULD BE SAVED EVEN AFTER POWER DOWN.

答:
EDIT, your question COMPLETELY changes the answer as you are not interested in SRAM writing at all but flash/eeprom...

So adding a major section to this answer, your comment is critical here:

But Is the value stored even after power down? Isn't that what SRAM
  would do instead of normal RAM? RAM=lose value when no power,
  SRAM=Keep value when no power?

SRAM means Static RAM, RAM means Random Access Memory.  Now RAM by that definition can be safe to use for things like a ROM (Read Only Memory) as the Random part has to do with addressing, can I address any random address I want or can I only read this thing using linear one address after the other per some rules.

The convention is that ROM is non-volatile and RAM is volatile which are the relevant terms here.  ROM implementations are not technically read only  PROM is programmable rom which means writeable, so that kinda breaks down the term EPROM electrically programmable, EEPROM is electrically eraseable and programmable.  And flash is a newer technology electrically eraseable and programmable rom or non-volatile storage.

Volatile in this sense means it can or cannot survive a power cycle.  volaitle means it cannot non-volatile means it can.

The S in SRAM is for Static sure which the term implies it might survive esp when you learn for DRAM the D means dynamic, and perfectly fine to assume one survives a power cycle and the other does not but unfortunately that is not what they refer to.  Instead in both cases they have to do with memory that remains powered, they are both volatile memories.  go look these up on wikipedia.  Static uses four transistors lets say, two gates with feedback in a classic flip flop implementation, you write the bit high or low and so long as the power doesnt turn off it stays that value it doesnt forget (so long as the power stays on).  DRAM though uses one transistor and to some extent relies heavily on the capacitance in that transistor, kind of like a lame rechargable battery, you want it to remember a 1 you have to charge it up and it discharges quickly (as in milliseconds) so you have to constantly remind it it is a one or a zero (refresh).

so static ram is static in the sense that we only have to tell it once and it remembers, dynamic ram is dynamic in the sense that we tell the dram system what that bit is and as a system we have to keep reminding it, this is done by reading the bit then reprogramming/charging that bit at a certain frequency.

DRAM is cheap, can pack four times the number of bits into the same number of transistors, SRAM is fast dont have the complicated overhead nor refresh cycles getting in the way, it is just gates so can run as fast as other gates as fast as the gates doing other things (processing instructions).

A microcontroller will have some form of non-volatile storage in it ROM, PROM, EEPROM or flash (of which there are now various flavors).  sometimes you have both flash and eeprom the eeprom for the kind of thing you may be asking for here, and sometimes for reverse compatibility reasons they have an eeprom legacy interface but it is really using the main flash for storage.  In any case you have to look at the documentation for your chip and or chip family.  These days it is common (although there are many exceptions) to have the ability in application to write to an on chip non-volatile memory (eeprom/flash).  And the documentation tells you how to do this.

And that is all great but some free advice is you can wear out your flash if you do this wrong, in hours or days...literally...The part can be trashed.  Ideally you want support on your board to detect the power going down, at the same time have enough bulk capacitance or a battery or both to keep the board/device alive long enough for the worst case amount of time it needs to save the non-volatile information (ideally confirming first that the values have changed otherwise dont burn an erase cycle).  Quite simple to implement, but still better than wearing out flash.

Lots of solutions and opinions on how to not wear out your flash, and sadly some of the flash hardware has logic that does write leveling, which if both software and hardware are trying to spread things out to reduce the wear on the flash they can work against each other and do more harm than good.

The number of supported write cycles for your part should be documented in the datasheet, you exceed that for the lifetime of the product you built with this device, it can forget what you wrote.  That is the minimum supported it might say 10000 writes but in testing you might get to 100,000 and have a device that still works. Doesnt mean all the reset of them will exceed the rating in the datasheet so you can work backward from that, if I get a new value every so many units of time and the lifetime of the product is I hope to be so many units of time, then I cannot save more than some simple math units of time (per storage location/erase boundary, etc).

so start by learning how, in application, to erase a block you are not using, and then write something to it then see if it is there when you power back up, try eeprom if you have it if not flash.  generally well documented and pretty easy to do on these STM32 devices.  then once you know how to do it then start to worry about how often you feel you need to do it.

Ever notice in some cars that when you turn them "off" and back on the clock still works and the radio remembers your favorite stations or the air condition remembers the last temperature and fan speed you used.  but if you disconnect the battery some or all of that is lost.  they are not using non-volatile storage they are using ram (SRAM) and the power simply went off, they are relying on a battery backup.  Motherboards did and maybe still do this for your "CMOS" or "BIOS" settings.  battery backed ram basically in that the ram doesnt lose power, the main power may go off but a battery is keeping the ram powered.  That is another design solution you can use, a battery or super cap(acitor), might assume you never need to store to flash, if like the car stereo, the battery dies the oh well.

Granted all of this requires my prior answer, in order to get at the registers that control the eeprom/flash you need to know how to access them from your program:

First and foremost bit banding is not required here (to store/load some value to/from ram), are you asking how to write to and read from specific addresses in ram or are you asking how to use bit banding?  Normally you wouldnt use bit banding with ram, the feature is there for example to change a subset of the bits in a register where the designers have for some reason packed separate items into the same register (things like gpio pin configurations make sense, and you might want to change the configuration for a single pin without a read-modify-write in software (hardware may still have to do the read-modify-write))

Sure you could use the bitbanding feature on ram, if the cortex-m allows it I would need to re-read that, doesnt necessarily make sense unless you are that tightly starved for ram that you need to be packing separate things into a single word (like bitfields but dont even start with that)...

```<code>#define BITBAND_SRAM_REF   0x20000000
#define BITBAND_SRAM_BASE  0x22000000
#define BITBAND_SRAM(a,b)  ((BITBAND_SRAM_BASE + (a-BITBAND_SRAM_REF)*32 + (b*4)))
#define BITBAND_PERI_REF   0x40000000
#define BITBAND_PERI_BASE  0x42000000
#define BITBAND_PERI(a,b)  ((BITBAND_PERI_BASE + (a-BITBAND_PERI_REF)*32  + (b*4)))
#define MAILBOX            0x20004000
#define TIMER              0x40004000
#define MBX_B0             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,0)))
#define MBX_B7             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,7)))
#define TIMER_B0           *((volatile unsigned char*)(BITBAND_PERI(TIMER,0)))
#define TIMER_B7           *((volatile unsigned char*)(BITBAND_PERI(TIMER,7)))

MBX_B0 = 1;
</code>```

So none of this is special, or related to the cortex-m or arm, just basic C code.  MBX_B0 is a macro you work the macro backward

```<code>#define MBX_B0             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,0)))
</code>```

then

```<code>#define MAILBOX            0x20004000
#define BITBAND_SRAM(a,b)  ((BITBAND_SRAM_BASE + (a-BITBAND_SRAM_REF)*32 + (b*4)))
#define BITBAND_SRAM_BASE  0x22000000
#define BITBAND_SRAM_REF   0x20000000
</code>```

so

```<code>0x22000000+(0x20004000-0x20000000)*32 + (0*4)

= 0x22080000
</code>```

The volatile unsigned int thing is just a C syntax way to take some constant like 0x22080009 and say this is the address to something I want to point to so

```<code>MBX_B0 = 1;
</code>```

means write a 0x00000001 to address 0x22080000 but since this is using bit banding, that means set bit 1 of bit 0 of address 0x20004000 (bit banding being very specific to these arm cortex-m cores)

If you just wanted to write the value 5 to some location in memory you could have just

```<code>#define SOME_ADD *((volatile unsigned int*)(0x20001234)
unsigned int x;
SOME_ADD = 5;
x = SOME_ADD;
</code>```

and to see this all done for you you can just try it:

```<code>#define BITBAND_SRAM_REF   0x20000000
#define BITBAND_SRAM_BASE  0x22000000
#define BITBAND_SRAM(a,b)  ((BITBAND_SRAM_BASE + (a-BITBAND_SRAM_REF)*32 + (b*4)))
#define MAILBOX            0x20004000
#define MBX_B0             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,0)))

#define SOME_ADD *((volatile unsigned int*)(0x20001234))

unsigned int fun ( void )
{
    unsigned int x;

    MBX_B0 = 1;

    SOME_ADD = 5;
    x = SOME_ADD;

}
</code>```

arm-none-eabi-gcc -c -O2 so.c -o so.o
arm-none-eabi-objdump -D so.o

```<code>00000000 <fun>:
   0:   e3a0c001    mov r12, #1
   4:   e3a02005    mov r2, #5
   8:   e59f1010    ldr r1, [pc, #16]   ; 20 <fun+0x20>
   c:   e59f3010    ldr r3, [pc, #16]   ; 24 <fun+0x24>
  10:   e581c000    str r12, [r1]
  14:   e5832234    str r2, [r3, #564]  ; 0x234
  18:   e5933234    ldr r3, [r3, #564]  ; 0x234
  1c:   e12fff1e    bx  lr
  20:   22080000    andcs   r0, r8, #0
  24:   20001000    andcs   r1, r0, r0
</code>```

the processor loads the address 0x20001000 and in this case the assembler has chosen to add the immediate 0x234 to that rather than put the whole 0x20001234 in the address loaded, six of one... no different cost either way, as written the compiler didnt need to align the loaded value.

Now if you are not needing to hit a specific address (0x20001234 or some peripheral register, etc) then simply

```<code>unsigned int some_value;
void fun ( void )
{
    some_value = 5;
}
</code>```

need to compile and link it to see the whole story:

```<code>00000004 <fun>:
   4:   e3a02005    mov r2, #5
   8:   e59f3004    ldr r3, [pc, #4]    ; 14 <fun+0x10>
   c:   e5832000    str r2, [r3]
  10:   e12fff1e    bx  lr
  14:   20000000    andcs   r0, r0, r0

Disassembly of section .bss:

20000000 <some_value>:
20000000:   00000000    andeq   r0, r0, r0
</code>```

and the code has now stored the number 5 to some location in ram (chosen by the linker).

on the bitbanding side of things if you read your arm documentation you will find that it is not always supported, in some cores it is an optional feature which means when they compile the chip they can choose to not include it.  And if for examaple this is a particular st chip or family you may find that they forgot to document one or both of the bitband addresses (0x22000000, 0x42000000) but have it in the library.

Personaly I am not a fan of the volatile pointer trick, I have seen compilers fail to produce the right instruction so I write a tiny two line assembly function that I can abstract all such accesses through which has a great side effect of forcing an abstraction like you would have in a linux or other driver anyway.  Allows the code to be much more useful, can abstract the access to a software simulation, can abstract the access to a logic simulation, can abstract through mmap, can use in a kernel driver, can add a printf layer for debugging that way, single place to set a breakpoint if you prefer that type of debugging, can implement with the couple of lines of asm for bare metal, or can use a generic macro/define to do the volatile pointer thing if you prefer that. YMMV.

Note local variables

```<code>void fun ( void )
{
    unsigned int some_value;
    some_value = 5;
}
</code>```

do not necessarily end up in ram, they ideally go on the stack, but can get optimized out if you optimize (recommended for a resource starved device like a microcontroller unless MISRA or some other requirement prevents you from using the optimizer).  The above code of course is completely dead code, results in a simple return:

```<code>00000000 <fun>:
   0:   e12fff1e    bx  lr
</code>```

Body:
EDIT, your question COMPLETELY changes the answer as you are not interested in SRAM writing at all but flash/eeprom...

So adding a major section to this answer, your comment is critical here:

But Is the value stored even after power down? Isn't that what SRAM
  would do instead of normal RAM? RAM=lose value when no power,
  SRAM=Keep value when no power?

SRAM means Static RAM, RAM means Random Access Memory.  Now RAM by that definition can be safe to use for things like a ROM (Read Only Memory) as the Random part has to do with addressing, can I address any random address I want or can I only read this thing using linear one address after the other per some rules.

The convention is that ROM is non-volatile and RAM is volatile which are the relevant terms here.  ROM implementations are not technically read only  PROM is programmable rom which means writeable, so that kinda breaks down the term EPROM electrically programmable, EEPROM is electrically eraseable and programmable.  And flash is a newer technology electrically eraseable and programmable rom or non-volatile storage.

Volatile in this sense means it can or cannot survive a power cycle.  volaitle means it cannot non-volatile means it can.

The S in SRAM is for Static sure which the term implies it might survive esp when you learn for DRAM the D means dynamic, and perfectly fine to assume one survives a power cycle and the other does not but unfortunately that is not what they refer to.  Instead in both cases they have to do with memory that remains powered, they are both volatile memories.  go look these up on wikipedia.  Static uses four transistors lets say, two gates with feedback in a classic flip flop implementation, you write the bit high or low and so long as the power doesnt turn off it stays that value it doesnt forget (so long as the power stays on).  DRAM though uses one transistor and to some extent relies heavily on the capacitance in that transistor, kind of like a lame rechargable battery, you want it to remember a 1 you have to charge it up and it discharges quickly (as in milliseconds) so you have to constantly remind it it is a one or a zero (refresh).

so static ram is static in the sense that we only have to tell it once and it remembers, dynamic ram is dynamic in the sense that we tell the dram system what that bit is and as a system we have to keep reminding it, this is done by reading the bit then reprogramming/charging that bit at a certain frequency.

DRAM is cheap, can pack four times the number of bits into the same number of transistors, SRAM is fast dont have the complicated overhead nor refresh cycles getting in the way, it is just gates so can run as fast as other gates as fast as the gates doing other things (processing instructions).

A microcontroller will have some form of non-volatile storage in it ROM, PROM, EEPROM or flash (of which there are now various flavors).  sometimes you have both flash and eeprom the eeprom for the kind of thing you may be asking for here, and sometimes for reverse compatibility reasons they have an eeprom legacy interface but it is really using the main flash for storage.  In any case you have to look at the documentation for your chip and or chip family.  These days it is common (although there are many exceptions) to have the ability in application to write to an on chip non-volatile memory (eeprom/flash).  And the documentation tells you how to do this.

And that is all great but some free advice is you can wear out your flash if you do this wrong, in hours or days...literally...The part can be trashed.  Ideally you want support on your board to detect the power going down, at the same time have enough bulk capacitance or a battery or both to keep the board/device alive long enough for the worst case amount of time it needs to save the non-volatile information (ideally confirming first that the values have changed otherwise dont burn an erase cycle).  Quite simple to implement, but still better than wearing out flash.

Lots of solutions and opinions on how to not wear out your flash, and sadly some of the flash hardware has logic that does write leveling, which if both software and hardware are trying to spread things out to reduce the wear on the flash they can work against each other and do more harm than good.

The number of supported write cycles for your part should be documented in the datasheet, you exceed that for the lifetime of the product you built with this device, it can forget what you wrote.  That is the minimum supported it might say 10000 writes but in testing you might get to 100,000 and have a device that still works. Doesnt mean all the reset of them will exceed the rating in the datasheet so you can work backward from that, if I get a new value every so many units of time and the lifetime of the product is I hope to be so many units of time, then I cannot save more than some simple math units of time (per storage location/erase boundary, etc).

so start by learning how, in application, to erase a block you are not using, and then write something to it then see if it is there when you power back up, try eeprom if you have it if not flash.  generally well documented and pretty easy to do on these STM32 devices.  then once you know how to do it then start to worry about how often you feel you need to do it.

Ever notice in some cars that when you turn them "off" and back on the clock still works and the radio remembers your favorite stations or the air condition remembers the last temperature and fan speed you used.  but if you disconnect the battery some or all of that is lost.  they are not using non-volatile storage they are using ram (SRAM) and the power simply went off, they are relying on a battery backup.  Motherboards did and maybe still do this for your "CMOS" or "BIOS" settings.  battery backed ram basically in that the ram doesnt lose power, the main power may go off but a battery is keeping the ram powered.  That is another design solution you can use, a battery or super cap(acitor), might assume you never need to store to flash, if like the car stereo, the battery dies the oh well.

Granted all of this requires my prior answer, in order to get at the registers that control the eeprom/flash you need to know how to access them from your program:

First and foremost bit banding is not required here (to store/load some value to/from ram), are you asking how to write to and read from specific addresses in ram or are you asking how to use bit banding?  Normally you wouldnt use bit banding with ram, the feature is there for example to change a subset of the bits in a register where the designers have for some reason packed separate items into the same register (things like gpio pin configurations make sense, and you might want to change the configuration for a single pin without a read-modify-write in software (hardware may still have to do the read-modify-write))

Sure you could use the bitbanding feature on ram, if the cortex-m allows it I would need to re-read that, doesnt necessarily make sense unless you are that tightly starved for ram that you need to be packing separate things into a single word (like bitfields but dont even start with that)...

#define BITBAND_SRAM_REF   0x20000000
#define BITBAND_SRAM_BASE  0x22000000
#define BITBAND_SRAM(a,b)  ((BITBAND_SRAM_BASE + (a-BITBAND_SRAM_REF)*32 + (b*4)))
#define BITBAND_PERI_REF   0x40000000
#define BITBAND_PERI_BASE  0x42000000
#define BITBAND_PERI(a,b)  ((BITBAND_PERI_BASE + (a-BITBAND_PERI_REF)*32  + (b*4)))
#define MAILBOX            0x20004000
#define TIMER              0x40004000
#define MBX_B0             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,0)))
#define MBX_B7             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,7)))
#define TIMER_B0           *((volatile unsigned char*)(BITBAND_PERI(TIMER,0)))
#define TIMER_B7           *((volatile unsigned char*)(BITBAND_PERI(TIMER,7)))

MBX_B0 = 1;

So none of this is special, or related to the cortex-m or arm, just basic C code.  MBX_B0 is a macro you work the macro backward

#define MBX_B0             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,0)))

then

#define MAILBOX            0x20004000
#define BITBAND_SRAM(a,b)  ((BITBAND_SRAM_BASE + (a-BITBAND_SRAM_REF)*32 + (b*4)))
#define BITBAND_SRAM_BASE  0x22000000
#define BITBAND_SRAM_REF   0x20000000

so

0x22000000+(0x20004000-0x20000000)*32 + (0*4)

= 0x22080000

The volatile unsigned int thing is just a C syntax way to take some constant like 0x22080009 and say this is the address to something I want to point to so

MBX_B0 = 1;

means write a 0x00000001 to address 0x22080000 but since this is using bit banding, that means set bit 1 of bit 0 of address 0x20004000 (bit banding being very specific to these arm cortex-m cores)

If you just wanted to write the value 5 to some location in memory you could have just

#define SOME_ADD *((volatile unsigned int*)(0x20001234)
unsigned int x;
SOME_ADD = 5;
x = SOME_ADD;

and to see this all done for you you can just try it:

#define BITBAND_SRAM_REF   0x20000000
#define BITBAND_SRAM_BASE  0x22000000
#define BITBAND_SRAM(a,b)  ((BITBAND_SRAM_BASE + (a-BITBAND_SRAM_REF)*32 + (b*4)))
#define MAILBOX            0x20004000
#define MBX_B0             *((volatile unsigned int*)(BITBAND_SRAM(MAILBOX,0)))

#define SOME_ADD *((volatile unsigned int*)(0x20001234))

unsigned int fun ( void )
{
    unsigned int x;

    MBX_B0 = 1;

    SOME_ADD = 5;
    x = SOME_ADD;

}

arm-none-eabi-gcc -c -O2 so.c -o so.o
arm-none-eabi-objdump -D so.o

00000000 <fun>:
   0:   e3a0c001    mov r12, #1
   4:   e3a02005    mov r2, #5
   8:   e59f1010    ldr r1, [pc, #16]   ; 20 <fun+0x20>
   c:   e59f3010    ldr r3, [pc, #16]   ; 24 <fun+0x24>
  10:   e581c000    str r12, [r1]
  14:   e5832234    str r2, [r3, #564]  ; 0x234
  18:   e5933234    ldr r3, [r3, #564]  ; 0x234
  1c:   e12fff1e    bx  lr
  20:   22080000    andcs   r0, r8, #0
  24:   20001000    andcs   r1, r0, r0

the processor loads the address 0x20001000 and in this case the assembler has chosen to add the immediate 0x234 to that rather than put the whole 0x20001234 in the address loaded, six of one... no different cost either way, as written the compiler didnt need to align the loaded value.

Now if you are not needing to hit a specific address (0x20001234 or some peripheral register, etc) then simply

unsigned int some_value;
void fun ( void )
{
    some_value = 5;
}

need to compile and link it to see the whole story:

00000004 <fun>:
   4:   e3a02005    mov r2, #5
   8:   e59f3004    ldr r3, [pc, #4]    ; 14 <fun+0x10>
   c:   e5832000    str r2, [r3]
  10:   e12fff1e    bx  lr
  14:   20000000    andcs   r0, r0, r0

Disassembly of section .bss:

20000000 <some_value>:
20000000:   00000000    andeq   r0, r0, r0

and the code has now stored the number 5 to some location in ram (chosen by the linker).

on the bitbanding side of things if you read your arm documentation you will find that it is not always supported, in some cores it is an optional feature which means when they compile the chip they can choose to not include it.  And if for examaple this is a particular st chip or family you may find that they forgot to document one or both of the bitband addresses (0x22000000, 0x42000000) but have it in the library.

Personaly I am not a fan of the volatile pointer trick, I have seen compilers fail to produce the right instruction so I write a tiny two line assembly function that I can abstract all such accesses through which has a great side effect of forcing an abstraction like you would have in a linux or other driver anyway.  Allows the code to be much more useful, can abstract the access to a software simulation, can abstract the access to a logic simulation, can abstract through mmap, can use in a kernel driver, can add a printf layer for debugging that way, single place to set a breakpoint if you prefer that type of debugging, can implement with the couple of lines of asm for bare metal, or can use a generic macro/define to do the volatile pointer thing if you prefer that. YMMV.

Note local variables

void fun ( void )
{
    unsigned int some_value;
    some_value = 5;
}

do not necessarily end up in ram, they ideally go on the stack, but can get optimized out if you optimize (recommended for a resource starved device like a microcontroller unless MISRA or some other requirement prevents you from using the optimizer).  The above code of course is completely dead code, results in a simple return:

00000000 <fun>:
   0:   e12fff1e    bx  lr


问:
in angular js how to call a function if ng-if is true?
i am totally new with angular js and trying to call a function when ng-if is true
my code =>

```<code>ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false && hellow()"
</code>```

and my js =>

```<code><script type="text/javascript">
       $scope.hellow = function ()
       {
           alert('hi');
       };
</script>
</code>```

also try=>

```<code><span ng-if="$index === 3" ng-init="hellow()"></span>
</code>```

problem is it is not alerting anything ?can anybody tell me what i have done wrong?

答:
It should be like this,</p>

```<code>ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false; hellow()";
</code>```

Body:
i am totally new with angular js and trying to call a function when ng-if is true
my code =>

ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false && hellow()"

and my js =>

also try=>

problem is it is not alerting anything ?can anybody tell me what i have done wrong?

Body:
It should be like this,

ng-repeat="image in post.postImages" ng-if="$index <= 3" ng-init="image.showDeleteIcon= false; hellow()";


问:
a large scale java project solution
I would like to start up a project from scratch. I am a java developer for years. I did even write my own mvc framework some time ago for fun. Now I am working in a company using in-house framework - which i think is a total loss of time and money. I respect the idea of  teaming up with different skilled people for a large scale project. The separation of the project is very important; Graphics guys, front end developers, software architectures, software developers, database experts, etc. I cannot risk to use a scripting language like php.

Lately, I am researching java technologies for a large scale project in every aspects. What I mean by that, for the front layer I come across with very famous technologies.

Spring

MyFaces

Tapestry

Google Web Toolkit

Cocoon

Velocity

Every one of them states that it is the simplest, the fastest, the latest technology and whatsoever. Of course only one them can hold the truth. I need a front end technology for fast implementation for ajax, customer/administrator security, themes, templates, internationalization, caching static pages, clustering and a support of ejb. It should also have IDE support, community support, rich documentation and online tutorials. Still I have no experience of those frameworks which to choose from. Maybe there is even better one? And most importantly, I cannot risk to start up on a technology which has development limitations. Is there any suggestions for this layer?

For the business layer, I am sure of EJB and JPA. I do even considering a web service for facade of this layer for interoperability purposes for future extensions. However, I have no idea about securing that layer (it could be applied on its web service level) which is still a problem for me. For the application server I am considering GlassFish.

And for the last question is what IDE should be picked for development. Regarding all the technologies, which are going to be used, an IDE should help me in every step, either doing the configuration for me or helping me configuring with its ready wizards. I suppose the IDE will have proper plugins for to be used technologies.

I know that I want too much, however I have a hope for a combination of technologies which will help me saving time and money in my future plans.

I ll be really glad to hear your responses, experiences for a bigger picture.

edited: There is no ultimate answer, I know that. I am just taking advice. Any answer is appreciated.

答:
There is almost no way that someone can actually answer this question for you. In terms of frontend technology, one of the frameworks will work for you and others won't. It all depends on which one makes sense to you. My suggestion would be to try them all out and pick the ones that you feel the most comfortable with.

With that being said, I do have a few suggestions. First, don't limit yourself to using Java. If it were me, I would use Ruby on Rails running on jRuby as the frontend as it is the fastest framework for developing web applications that I have used. By running it on jRuby, it allows you to hook into Java and let java and its libraries do all the heavy lifting on the back end. I would stay away from web services and implement things using ReST.

In terms of an IDE, definitely go with IntelliJ IDEA. It may take a little bit to get used to, but it is definitely the fastest IDE on the market. However, both Eclipse and Netbeans are also very good for Java and a tad cheaper.

Once again, the answer is, "it depends".

Title: a large scale java project solution


问:
CSRF token is invalid after changing Host
we had a Symfony2 project and for some reason we've changed the Host, after changing to a host with Plesk Panel,  we are facing with The CSRF token is invalid. Please try to resubmit the form., I tried to figure out why? then provide a simple  Twig form with following codes :

```<code><!doctype html>
<html>
<head>
    {# ... #}

    <link rel="stylesheet"
          href="{{ asset('assets/vendor/bootstrap/dist/css/bootstrap.min.css') }}">
</head>
<body>

<div class="container">
    <h2>ADD Item to Crawling List</h2>
    {{ form_start(form) }}
    {{ form_widget(form) }}
    {{ form_end(form) }}
</div>
</body>
</html>
</code>```

and it rendered correctly

```<code><!doctype html>
<html>
<head>

    <link rel="stylesheet"
          href="/assets/vendor/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <h2>ADD Item to Crawling List</h2>
    <form name="form" method="post">
    <div id="form"><div><label for="form_post_id" class="required">Instagram Post Id</label><input type="text" id="form_post_id" name="form[post_id]" required="required" /></div><div><button type="submit" id="form_save" name="form[save]">Fetch Comments</button></div><input type="hidden" id="form__token" name="form[_token]" value="j9YWKseFdkU4Z_Yc5nuwm72SKD4dT06gJpARLqPID6I" /><button type="submit" id="form_save" name="form[save]">Fetch Comments</button></div>
    </form>
</div>
</body>
</html>
</code>```

Also tried to add {{ form_rest(form) }} but Not any achievement and the result is the same.

Another note is we didn't override session config handler in config.yml` and it's

```<code>framework:
    #esi:             ~
    #translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    #serializer:      { enable_annotations: true }
    templating:
        engines: ['twig']
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # handler_id set to null will use default session handler from php.ini
        handler_id:  ~
</code>```

any solution or idea help us to resolve this issue will be appreciated.

答:
You should add:

```<code>{{ form_rest(form) }}
</code>```

Just before the form_end, this adds the CSRF token in a hidden input in your form.

Body:
we had a Symfony2 project and for some reason we've changed the Host, after changing to a host with Plesk Panel,  we are facing with The CSRF token is invalid. Please try to resubmit the form., I tried to figure out why? then provide a simple  Twig form with following codes :

<!doctype html>

    {# ... #}

    <link rel="stylesheet"
          href="{{ asset('assets/vendor/bootstrap/dist/css/bootstrap.min.css') }}">

ADD Item to Crawling List

    {{ form_start(form) }}
    {{ form_widget(form) }}
    {{ form_end(form) }}

and it rendered correctly

<!doctype html>

    <link rel="stylesheet"
          href="/assets/vendor/bootstrap/dist/css/bootstrap.min.css">

ADD Item to Crawling List

    <form name="form" method="post">

Instagram Post Id<input type="text" id="form_post_id" name="form[post_id]" required="required" />

<button type="submit" id="form_save" name="form[save]">Fetch Comments</button>
<input type="hidden" id="form__token" name="form[_token]" value="j9YWKseFdkU4Z_Yc5nuwm72SKD4dT06gJpARLqPID6I" /><button type="submit" id="form_save" name="form[save]">Fetch Comments</button>

    </form>

Also tried to add {{ form_rest(form) }} but Not any achievement and the result is the same.

Another note is we didn't override session config handler in config.yml` and it's

framework:
    #esi:             ~
    #translator:      { fallbacks: ["%locale%"] }
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    #serializer:      { enable_annotations: true }
    templating:
        engines: ['twig']
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # handler_id set to null will use default session handler from php.ini
        handler_id:  ~

any solution or idea help us to resolve this issue will be appreciated.

Body:
You should add:

{{ form_rest(form) }}

Just before the form_end, this adds the CSRF token in a hidden input in your form.


问:
using data-attribute inside javascript
I have table rows and each of them has an ID. How can I use data-attribute to button EDIT if my code look like this?

```<code>//some javascript code

var content = '<button type="button" class="btn btn-success edit_shipment" data-id="b.booking_id">Edit</button>';
return content;

//some javascript code again

//when Edit onclick, it shows modal
$('#booking_table tbody').on('click', 'button.edit_shipment', function(){
 $('#edit_shipment_modal').modal('show');
</code>```

data-id="b.booking_id" is not working

Thanks in advance

答:
```<code>var tr = $(this).closest("tr");
var id = $(this).attr("data-id");
</code>```

Title: using data-attribute inside javascript

Body:
I have table rows and each of them has an ID. How can I use data-attribute to button EDIT if my code look like this?

//some javascript code

var content = '<button type="button" class="btn btn-success edit_shipment" data-id="b.booking_id">Edit</button>';
return content;

//some javascript code again

//when Edit onclick, it shows modal
$('#booking_table tbody').on('click', 'button.edit_shipment', function(){
 $('#edit_shipment_modal').modal('show');

data-id="b.booking_id" is not working

Thanks in advance


问:
Loop for monthly or yearly averages by day number (in Julian day format)
I have daily '.mat' files whose nomenclature is like 'Data_grid_day_ppt_ice003.mat', the last '003' is the date of the year in Julian day format, It can start from '001' and end in '365' and '366' depending on whether it is a leap year or not.

I need monthly averages of the data. Any idea how can I make loops for the date files?

Some dates can be missing also, so just counting the number of files would not work.

I am writing in Matlab, I was trying something like

```<code>year = linspace(2007,2016,10); % Years of data
months = linspace(01,12,12);% Months of the year
for n = 1:length(year)
    foldery = int2str(year(n));
    if ~exist(folderyear)
        continue
    else
        if mod(year,4) == 0 % if the year is divisible by four
            dpm = [31 60 91 121 152 182 213 244 274 305 335 366];
        else
           dpm = [31 59 90 120 151 181 212 243 273 304 334 365];
        end
        for j = 1:length(months) %loop over months
            if ~exist(months)
                continue
            else
                for ii = 1:dpm(j)   %loop over days
                    % ... Not sure what to do here ...
                end
            end
        end
    end
end
</code>```

However, I am not able to work out the next step...

答:
Firstly, don't use year as a variable name, because it is a built in Matlab function! Then be careful with your variable names, like confusing foldery and folderyear.

The easiest way to do this would be to just add the day of the year to the 1st Jan in that year, then get the month using Matlab's built in month function. This will take care of all of the leap year issues as long as you know the year (which you seem to). Also see this documentation, Date and Time Arithmetic, which confirms that adding a number to a datetime value will add full 24 hour days.

The key is this method for getting month from Julian day of year:

```<code>thisyear = 2017;               % Define which year you're in
J1 = datetime(2016,1,1);       % Set January first datetime
dayofyear = 360;               % Christmas day as an example!
m = month(J1 + dayofyear - 1)  % Add day of year to Jan 1st, get month
% J1 + dayofyear - 1 = 25-Dec-2016 00:00:00
% m = 12
% month(J1 + dayofyear - 1, 'name') = 'December'
</code>```

See this commented extension of your code for more detail...

```<code>y = 2007:2016; % Years of data [2007, 2008, ... 2016]
outputdata = cell(1,12);
for n = 1:length(y)
    folderyear = int2str(y(n));
    if ~exist(folderyear, 'dir')
        continue
    else
        % Get all .mat files within this year folder
        f = dir(fullfile(folderyear, '*.mat'));
        filenames = {f.name};
        % Set Jan 1st date
        J1 = datetime(y, 1, 1);
        % Loop over months
        for m = 1:12
            % Loop over files
            for myfile = 1:numel(filenames)
                % Get number from end of file name
                dayofyear = filenames{myfile};
                dayofyear = str2num(dayofyear(end-6:end-4));
                % Get month of day by adding to Jan 1st of that year
                % -1 used assuming Jan 1st is day 1. Not needed if Jan 1st is day 0.
                if month(J1 + dayofyear - 1) == m
                    % hurrah, this file is in the month m, add it to an average
                    % or anything else you want, then you could assign to
                    % an output cell or matrix
                    % outputdata{m} = ...
                end
            end
        end
    end
end
</code>```

Body:
I have daily '.mat' files whose nomenclature is like 'Data_grid_day_ppt_ice003.mat', the last '003' is the date of the year in Julian day format, It can start from '001' and end in '365' and '366' depending on whether it is a leap year or not.

I need monthly averages of the data. Any idea how can I make loops for the date files?

Some dates can be missing also, so just counting the number of files would not work.

I am writing in Matlab, I was trying something like

year = linspace(2007,2016,10); % Years of data
months = linspace(01,12,12);% Months of the year
for n = 1:length(year)
    foldery = int2str(year(n));
    if ~exist(folderyear)
        continue
    else
        if mod(year,4) == 0 % if the year is divisible by four
            dpm = [31 60 91 121 152 182 213 244 274 305 335 366];
        else
           dpm = [31 59 90 120 151 181 212 243 273 304 334 365];
        end
        for j = 1:length(months) %loop over months
            if ~exist(months)
                continue
            else
                for ii = 1:dpm(j)   %loop over days
                    % ... Not sure what to do here ...
                end
            end
        end
    end
end

However, I am not able to work out the next step...

Body:
Firstly, don't use year as a variable name, because it is a built in Matlab function! Then be careful with your variable names, like confusing foldery and folderyear.

The easiest way to do this would be to just add the day of the year to the 1st Jan in that year, then get the month using Matlab's built in month function. This will take care of all of the leap year issues as long as you know the year (which you seem to). Also see this documentation, Date and Time Arithmetic, which confirms that adding a number to a datetime value will add full 24 hour days.

The key is this method for getting month from Julian day of year:

thisyear = 2017;               % Define which year you're in
J1 = datetime(2016,1,1);       % Set January first datetime
dayofyear = 360;               % Christmas day as an example!
m = month(J1 + dayofyear - 1)  % Add day of year to Jan 1st, get month
% J1 + dayofyear - 1 = 25-Dec-2016 00:00:00
% m = 12
% month(J1 + dayofyear - 1, 'name') = 'December'

See this commented extension of your code for more detail...

y = 2007:2016; % Years of data [2007, 2008, ... 2016]
outputdata = cell(1,12);
for n = 1:length(y)
    folderyear = int2str(y(n));
    if ~exist(folderyear, 'dir')
        continue
    else
        % Get all .mat files within this year folder
        f = dir(fullfile(folderyear, '*.mat'));
        filenames = {f.name};
        % Set Jan 1st date
        J1 = datetime(y, 1, 1);
        % Loop over months
        for m = 1:12
            % Loop over files
            for myfile = 1:numel(filenames)
                % Get number from end of file name
                dayofyear = filenames{myfile};
                dayofyear = str2num(dayofyear(end-6:end-4));
                % Get month of day by adding to Jan 1st of that year
                % -1 used assuming Jan 1st is day 1. Not needed if Jan 1st is day 0.
                if month(J1 + dayofyear - 1) == m
                    % hurrah, this file is in the month m, add it to an average
                    % or anything else you want, then you could assign to
                    % an output cell or matrix
                    % outputdata{m} = ...
                end
            end
        end
    end
end


问:
Better way to structure/new keyword
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

```<code>boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();
</code>```

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

```<code>boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();
</code>```

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

答:
How about relocating the setup to the operator bool on the Condition class?  This makes it far more readable and hides the mechanics.</p>

```<code>class Condition
{
    bool _isSet;
public:
    Condition() : _isSet(false) {
    }
    void setup() {
        _isSet = true;
    }
    operator bool () {
        if (!_isSet) {
            setup();
        }
        return rand() & 1;
    }
};

void doSomething()
{
}

int _tmain(int argc, _TCHAR* argv[])
{
    Condition cond1, cond2, cond3;
    if (cond1 && cond2 && cond3) {
        doSomething();
    }
    return 0;
}
</code>```

Title: Better way to structure/new keyword

Body:
Some time ago I came across the following construct which I have rarely seen since, though I use it relatively frequently.  I use it typically when checking on a whole list of conditions are true and it prevents large levels of indentation.  Essentially it uses a for loop to provide a kind of structured goto.  My question is firstly whether there is better way to structure this, secondly whether people like it and thirdly whether a new keyword in java/c++ etc. such as unit { } which would only cause breaks to exit to the end of the unit would be useful and clearer.

ps I realise that it is on slip away from an infinite loop, but I think my paranoia about that has meant its never happened.

Edit: I have added some setup code for the further conditions to try to illuminate problems with chained if then elses

boolean valid = false;

// this loop never loops
for (;;)
{
    if (!condition1)
        break;

    condition2.setup();

    if (!condition2)
        break;

    condition3.setup();

    if (!condition3)
        break;

    valid = true;
    break;
}

if (valid) dosomething();

EDIT:

I have just discovered that in fact there is a way to structure this in java without misusing loops etc. and wondered whether this would similarily be frowned on, though I guess I have missed the boat on this one.

The restructured code looks like this.

boolean valid = false;

breakout:
{
    if (!condition1)
        break breakout;

    condition2.setup();

    if (!condition2)
        break breakout;

    condition3.setup();

    if (!condition3)
        break breakout;

    valid = true;
}

if (valid) dosomething();

Now that removes the misuse of the for loop which caused a lot of the complaints, and is actually a solution I think is quite neat and is what I was looking to find originally.
I am guessing that this structure is probably not well known since no one mentioned it, people object to this as strongly?

Body:
How about relocating the setup to the operator bool on the Condition class?  This makes it far more readable and hides the mechanics.

class Condition
{
    bool _isSet;
public:
    Condition() : _isSet(false) {
    }
    void setup() {
        _isSet = true;
    }
    operator bool () {
        if (!_isSet) {
            setup();
        }
        return rand() & 1;
    }
};

void doSomething()
{
}

int _tmain(int argc, _TCHAR* argv[])
{
    Condition cond1, cond2, cond3;
    if (cond1 && cond2 && cond3) {
        doSomething();
    }
    return 0;
}