问:
Pass multiple parameters to event handlers in React
So im trying to make react work with ES6 syntax. In ES5 I had setInitialState without a constructor which worked with the function binding syntax. I have a list of prices which is arbitrary and I want the state to change when the input element is changed. But the right price has to be changed.

I'm not even quite sure this is the right way to do it. Can someone please tell me the most recent way this should be done?

Here is my code:

```<code>import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.css';

export default class PriceTable extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      pid: this.props.pid || "12345",
      name: this.props.name || "name",
      prices: this.props.prices || [
        {count: 1, desc: 'one', price: 8.25},
        {count: 6, desc: 'six', price: 7.60},
        {count: 12, desc: 'twelve', price: 6.953}
      ]
    };

    this.setPid = this.setPid.bind(this);
    this.setName = this.setName.bind(this);
    this.setCount = this.setCount.bind(this, i);
    this.setDesc = this.setDesc.bind(this, i);
    this.setPrice = this.setPrice.bind(this, i);
    this.logDebug = this.logDebug.bind(this);
  }

  setPid(e) {
    this.setState({pid: e.target.value})
  }

  setName(e) {
    this.setState({name: e.target.value})
  }

  setCount(i, e) {
    var newPrices = this.state.prices
    newPrices[i].count = e.target.value
    this.setState({prices: newPrices})
  }

  setDesc(i, e) {
    var newPrices = this.state.prices
    newPrices[i].sec = e.target.value
    this.setState({prices: newPrices})
  }

  setPrice(i, e) {
    var newPrices = this.state.prices
    newPrices[i].price = e.target.value
    this.setState({prices: newPrices})
  }

  _renderPriceRow(price, i) {
    return (
      <tr key={i}>
        <td >
          <input type="text" className="form-control" defaultValue={price.count} onChange={this.setCount(this, i).bind(this, i)}/>
        </td>
        <td >
          <input type="text" className="form-control" defaultValue={price.desc} onChange={this.setDesc(this, i).bind(this, i)}/>
        </td>
        <td >
          <input type="text" className="form-control" defaultValue={price.price} onChange={this.setPrice(this, i).bind(this, i)}/>
        </td>
      </tr>
    );
  }

  render() {
    return (
      <div className="row">
       ...
      </div>
    );
  }
}
</code>```

And this is the error...

```<code>PriceTable.jsx:21 Uncaught ReferenceError: i is not defined
    at new PriceTable (PriceTable.jsx:21)
</code>```

答:
You are binding the functions incorrectly

In your constructor you need not specify the argument, you only need to bind it like this.setDesc = this.setDesc.bind(this);

Also In your onChange, when you want to pass paramters to the function you specify it with bind and not pass as arguments and bind them again .

```<code>onChange={this.setDesc.bind(this, i)}
</code>```

You entire code will look like

```<code>import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.css';

export default class PriceTable extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      pid: this.props.pid || "12345",
      name: this.props.name || "name",
      prices: this.props.prices || [
        {count: 1, desc: 'one', price: 8.25},
        {count: 6, desc: 'six', price: 7.60},
        {count: 12, desc: 'twelve', price: 6.953}
      ]
    };

    this.setPid = this.setPid.bind(this);
    this.setName = this.setName.bind(this);
    this.setCount = this.setCount.bind(this);
    this.setDesc = this.setDesc.bind(this);
    this.setPrice = this.setPrice.bind(this);
    this.logDebug = this.logDebug.bind(this);
    this._renderPriceRow = this._renderPriceRow.bind(this);
  }

  setPid(e) {
    this.setState({pid: e.target.value})
  }

  setName(e) {
    this.setState({name: e.target.value})
  }

  setCount(i, e) {
    var newPrices = this.state.prices
    newPrices[i].count = e.target.value
    this.setState({prices: newPrices})
  }

  setDesc(i, e) {
    var newPrices = this.state.prices
    newPrices[i].sec = e.target.value
    this.setState({prices: newPrices})
  }

  setPrice(i, e) {
    var newPrices = this.state.prices
    newPrices[i].price = e.target.value
    this.setState({prices: newPrices})
  }

  _renderPriceRow(price, i) {
    return (
      <tr key={i}>
        <td >
          <input type="text" className="form-control" defaultValue={price.count} onChange={this.setCount.bind(this, i)}/>
        </td>
        <td >
          <input type="text" className="form-control" defaultValue={price.desc} onChange={this.setDesc.bind(this, i)}/>
        </td>
        <td >
          <input type="text" className="form-control" defaultValue={price.price} onChange={this.setPrice.bind(this, i)}/>
        </td>
      </tr>
    );
  }

  render() {
    return (
      <div className="row">
       ...
      </div>
    );
  }
}
</code>```

You could also make use of Arrow functions to pass parameters like

```<code>onChange={(e) => this.setDesc(e,  i)}
</code>```

Body:
So im trying to make react work with ES6 syntax. In ES5 I had setInitialState without a constructor which worked with the function binding syntax. I have a list of prices which is arbitrary and I want the state to change when the input element is changed. But the right price has to be changed.

I'm not even quite sure this is the right way to do it. Can someone please tell me the most recent way this should be done?

Here is my code:

import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.css';

export default class PriceTable extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      pid: this.props.pid || "12345",
      name: this.props.name || "name",
      prices: this.props.prices || [
        {count: 1, desc: 'one', price: 8.25},
        {count: 6, desc: 'six', price: 7.60},
        {count: 12, desc: 'twelve', price: 6.953}
      ]
    };

    this.setPid = this.setPid.bind(this);
    this.setName = this.setName.bind(this);
    this.setCount = this.setCount.bind(this, i);
    this.setDesc = this.setDesc.bind(this, i);
    this.setPrice = this.setPrice.bind(this, i);
    this.logDebug = this.logDebug.bind(this);
  }

  setPid(e) {
    this.setState({pid: e.target.value})
  }

  setName(e) {
    this.setState({name: e.target.value})
  }

  setCount(i, e) {
    var newPrices = this.state.prices
    newPrices[i].count = e.target.value
    this.setState({prices: newPrices})
  }

  setDesc(i, e) {
    var newPrices = this.state.prices
    newPrices[i].sec = e.target.value
    this.setState({prices: newPrices})
  }

  setPrice(i, e) {
    var newPrices = this.state.prices
    newPrices[i].price = e.target.value
    this.setState({prices: newPrices})
  }

  _renderPriceRow(price, i) {
    return (

          <input type="text" className="form-control" defaultValue={price.count} onChange={this.setCount(this, i).bind(this, i)}/>

          <input type="text" className="form-control" defaultValue={price.desc} onChange={this.setDesc(this, i).bind(this, i)}/>

          <input type="text" className="form-control" defaultValue={price.price} onChange={this.setPrice(this, i).bind(this, i)}/>

    );
  }

  render() {
    return (

       ...

    );
  }
}

And this is the error...

PriceTable.jsx:21 Uncaught ReferenceError: i is not defined
    at new PriceTable (PriceTable.jsx:21)

Body:
You are binding the functions incorrectly

In your constructor you need not specify the argument, you only need to bind it like this.setDesc = this.setDesc.bind(this);

Also In your onChange, when you want to pass paramters to the function you specify it with bind and not pass as arguments and bind them again .

onChange={this.setDesc.bind(this, i)}

You entire code will look like

import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.css';

export default class PriceTable extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      pid: this.props.pid || "12345",
      name: this.props.name || "name",
      prices: this.props.prices || [
        {count: 1, desc: 'one', price: 8.25},
        {count: 6, desc: 'six', price: 7.60},
        {count: 12, desc: 'twelve', price: 6.953}
      ]
    };

    this.setPid = this.setPid.bind(this);
    this.setName = this.setName.bind(this);
    this.setCount = this.setCount.bind(this);
    this.setDesc = this.setDesc.bind(this);
    this.setPrice = this.setPrice.bind(this);
    this.logDebug = this.logDebug.bind(this);
    this._renderPriceRow = this._renderPriceRow.bind(this);
  }

  setPid(e) {
    this.setState({pid: e.target.value})
  }

  setName(e) {
    this.setState({name: e.target.value})
  }

  setCount(i, e) {
    var newPrices = this.state.prices
    newPrices[i].count = e.target.value
    this.setState({prices: newPrices})
  }

  setDesc(i, e) {
    var newPrices = this.state.prices
    newPrices[i].sec = e.target.value
    this.setState({prices: newPrices})
  }

  setPrice(i, e) {
    var newPrices = this.state.prices
    newPrices[i].price = e.target.value
    this.setState({prices: newPrices})
  }

  _renderPriceRow(price, i) {
    return (
      <tr key={i}>
        <td >
          <input type="text" className="form-control" defaultValue={price.count} onChange={this.setCount.bind(this, i)}/>
        </td>
        <td >
          <input type="text" className="form-control" defaultValue={price.desc} onChange={this.setDesc.bind(this, i)}/>
        </td>
        <td >
          <input type="text" className="form-control" defaultValue={price.price} onChange={this.setPrice.bind(this, i)}/>
        </td>
      </tr>
    );
  }

  render() {
    return (
      <div className="row">
       ...
      </div>
    );
  }
}

You could also make use of Arrow functions to pass parameters like

onChange={(e) => this.setDesc(e,  i)}


来源: stackexchange

问:
Django Docker settings with link and environment
I'm setting up django with docker and I can't really get what's the correct way to setup the setting.py

For example, the database I've right now in the setting.py is:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ['db_name'],
        'USER': os.environ['db_user'],
        'PASSWORD': os.environ['db_password'],
        'HOST': 'db',
        'PORT': '5432',
    }
}
</code>```

where db_name, db_user, db_password are set in an enviroment file. db is instead a --link (docker run --link mydb:db ..).

Now, it seems to work, but I'm not really sure I should do like this.

Is this the right way to setup the settings? Especially where the secrete things should be placed, what's the way to call variables in the environment (apparently docker is creating DB_ variables), and when/how to use the linked containers in the settings (with the name or with env variables?).

Is there a way to use 'db' or an enviroment variable as host? I would like to have so beacuse I may specify the db as link or inside the .env file.

答:
You can pass environment variable to containers with the -e flag:

```<code>docker run -e VAR_NAME=VAR_VALUE ...
</code>```

so, if your db value is accessible to the process running the container, you could do something along those lines:

```<code>export DB=db
docker run -e db_host=$DB --link mydb:$DB mycontainer
</code>```

and then in Django settings:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ['db_name'],
        'USER': os.environ['db_user'],
        'PASSWORD': os.environ['db_password'],
        'HOST': os.environ['db_host'], # 'db' in this example
        'PORT': '5432',
    }
}
</code>```

Depending on your set up, you could also load the whole .env file instead of exporting the single DB variable (look at the the answers to this question for an explanation of how do it). In this way - assuming that your app takes care of loading the env file for itself - you wouldn't have to pass an environment variable to the container, since the app will rely on the .env file for getting the value.

```<code># Assuming DB=db in the .env file
docker run -e --link mydb:$DB mycontainer
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm setting up django with docker and I can't really get what's the correct way to setup the setting.py

For example, the database I've right now in the setting.py is:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ['db_name'],
        'USER': os.environ['db_user'],
        'PASSWORD': os.environ['db_password'],
        'HOST': 'db',
        'PORT': '5432',
    }
}

where db_name, db_user, db_password are set in an enviroment file. db is instead a --link (docker run --link mydb:db ..).

Now, it seems to work, but I'm not really sure I should do like this.

Is this the right way to setup the settings? Especially where the secrete things should be placed, what's the way to call variables in the environment (apparently docker is creating DB_ variables), and when/how to use the linked containers in the settings (with the name or with env variables?).

Is there a way to use 'db' or an enviroment variable as host? I would like to have so beacuse I may specify the db as link or inside the .env file.

Body:
You can pass environment variable to containers with the -e flag:

docker run -e VAR_NAME=VAR_VALUE ...

so, if your db value is accessible to the process running the container, you could do something along those lines:

export DB=db
docker run -e db_host=$DB --link mydb:$DB mycontainer

and then in Django settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ['db_name'],
        'USER': os.environ['db_user'],
        'PASSWORD': os.environ['db_password'],
        'HOST': os.environ['db_host'], # 'db' in this example
        'PORT': '5432',
    }
}

Depending on your set up, you could also load the whole .env file instead of exporting the single DB variable (look at the the answers to this question for an explanation of how do it). In this way - assuming that your app takes care of loading the env file for itself - you wouldn't have to pass an environment variable to the container, since the app will rely on the .env file for getting the value.

# Assuming DB=db in the .env file
docker run -e --link mydb:$DB mycontainer

ContentLicense: CC BY-SA 3.0


问:
Elements from xml using php
so I can access an xml file and all its elements using

```<code>$xml = simplexml_load_file('file.xml');
</code>```

Inside there are items and some of them have images, some more than others. I, of course, receive this file from another server. These images live inside an element called 'images' and the xml file looks like this:

```<code><images>
    <image id="1" time_modif="1490197696">
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >
</code>```

I am in desperate need to loop through these images and get their Url. For that I've tried:

```<code>$element = $xml->element;
$i = 0;

foreach ($element->images as $img)
{
    echo $img->image[$i] . '<br>';
    $i++
}
</code>```

but the 'foreach' loop only returns the first url, and not the others.

Does anyone have any thoughts?

Thanks in advance !

答:
Are you looking for this?

PHP code demo

```<code><?php
$domObject= new DOMDocument();
$domObject->loadXML('<images>
    <image id="1" time_modif="1490197696">
        http://example.com/1.jpg
    </image >
    <image id="2" time_modif="1490197699">
        http://example.com/2.jpg
    </image>
    <image id="3" time_modif="1490197702">
        http://example.com/3.jpg
    </image >
</images >');

foreach($domObject->getElementsByTagName("image") as $nodeObj)
{
    $imageLink=trim($nodeObj->nodeValue);
    print_r($imageLink);
}
</code>```

Title: Elements from xml using php

Body:
so I can access an xml file and all its elements using

$xml = simplexml_load_file('file.xml');

Inside there are items and some of them have images, some more than others. I, of course, receive this file from another server. These images live inside an element called 'images' and the xml file looks like this:

<images>
    <image id="1" time_modif="1490197696">
        *** url here   ***
    </image >
    <image id="2" time_modif="1490197699">
        *** url here   ***
    </ image >
    <image id="3" time_modif="1490197702">
        *** url here   ***
    </image >
</images >

I am in desperate need to loop through these images and get their Url. For that I've tried:

$element = $xml->element;
$i = 0;

foreach ($element->images as $img)
{
    echo $img->image[$i] . '
';
    $i++
}

but the 'foreach' loop only returns the first url, and not the others.

Does anyone have any thoughts?

Thanks in advance !

Body:
Are you looking for this?

PHP code demo

<?php
$domObject= new DOMDocument();
$domObject->loadXML('<images>
    <image id="1" time_modif="1490197696">
        http://example.com/1.jpg
    </image >
    <image id="2" time_modif="1490197699">
        http://example.com/2.jpg
    </image>
    <image id="3" time_modif="1490197702">
        http://example.com/3.jpg
    </image >
</images >');

foreach($domObject->getElementsByTagName("image") as $nodeObj)
{
    $imageLink=trim($nodeObj->nodeValue);
    print_r($imageLink);
}


问:
SSIS - Data Conversion from DT_STR to int
How to apply the below transformation in SSIS data flow task

```<code>cast(gift_amount as int)/100
</code>```

In Derived Column Transformation Editor, I am unable to change the data type. It gives 0xC0049064 error upon giving typecast function.

答:
You should try

```<code>((DT_I4)gift_amount)/100
</code>```

Also, in the Derived Column Editor window, you can add other types of casts - take a look through some of those options in the upper right hand part of the editor.

Body:
How to apply the below transformation in SSIS data flow task

cast(gift_amount as int)/100

In Derived Column Transformation Editor, I am unable to change the data type. It gives 0xC0049064 error upon giving typecast function.

Body:
You should try

((DT_I4)gift_amount)/100

Also, in the Derived Column Editor window, you can add other types of casts - take a look through some of those options in the upper right hand part of the editor.


问:
How do I insert a space after a character in a textbox, depending on the total characters entered, JQuery?
Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks

My Solution, Although it's basic:

```<code>$(document).ready(function(){

    $('#postcode').blur(function(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{
            document.write('OOPS!');}
    });
});
</code>```

答:
Another option is to use a regex replace:</p>

```<code>$('#postcode').blur(function() {
     var str = $(this).val();

     // I assume that since the example had 6 characters that this was the min you were looking for
     if(str.length >= 6) {
         $(this).val(str.replace(/.{3}$/, " $&"));
     }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to add a space in a textbox depending on the total characters entered by the user.

For example if the user entered 'LU33RT' on blur I'd like it to display 'LU3 3RT'. The rule that I'm looking to incorporate is by counting 3 characters in from the right then add a space.

$('#postcode').blur(...

Any help would be greatly appreciated, Thanks

My Solution, Although it's basic:

$(document).ready(function(){

    $('#postcode').blur(function(){
        if(($(this).val().length == 6) && (/\S/)){
           var myString = $(this).val().slice(0, 3);
           var myString2 = $(this).val().slice(-3);
           $(this).val(myString + ' ' + myString2);
        }else{
            document.write('OOPS!');}
    });
});

Body:
Another option is to use a regex replace:

$('#postcode').blur(function() {
     var str = $(this).val();

     // I assume that since the example had 6 characters that this was the min you were looking for
     if(str.length >= 6) {
         $(this).val(str.replace(/.{3}$/, " $&"));
     }
});


问:
Servlet should have a mapping and cannot resolve Servlet
When I open my project, I get the error:

Servlet should have a mapping

and the other error:

Cannot resolve Servlet

But in the below code you can see every servlet have its mapping:

In my web.xml, I have 8 servlet, and every servlet has its corresponding mapping:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>loginservlet</servlet-name>
    <servlet-class>com.sam.servlet.loginservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>changeservlet</servlet-name>
    <servlet-class>com.sam.servlet.changeservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Searchservlet</servlet-name>
    <servlet-class>com.sam.servlet.Searchservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>borrowservlet</servlet-name>
    <servlet-class>com.sam.servlet.borrowservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>mealselectservlet</servlet-name>
    <servlet-class>com.sam.servlet.mealselectservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>mealaddservlet</servlet-name>
    <servlet-class>com.sam.servlet.mealaddservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>mealdeletedservlet</servlet-name>
    <servlet-class>com.sam.servlet.mealdeletedservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>mealupdateservlet</servlet-name>
    <servlet-class>com.sam.servlet.mealupdateservlet</servlet-class>
  </servlet>

<!-- mapping -->

  <servlet-mapping>
    <servlet-name>loginservlet</servlet-name>
    <url-pattern>/loginservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>changeservlet</servlet-name>
    <url-pattern>/changeservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Searchservlet</servlet-name>
    <url-pattern>/Searchservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>borrowservlet</servlet-name>
    <url-pattern>/borrowservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>mealselectservlet</servlet-name>
    <url-pattern>/mealselectservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>mealaddservlet</servlet-name>
    <url-pattern>/mealaddservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>mealdeletedservlet</servlet-name>
    <url-pattern>/mealdeletedservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>mealupdateservlet</servlet-name>
    <url-pattern>/mealupdateservlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
</code>```

答:
It's a known issue that is already fixed in the current IntelliJ IDEA version. For the older versions there is a workaround:

please open Project Structure | Modules | Web Facet and add your web.xml as Deployment Descriptor.

Body:
When I open my project, I get the error:

Servlet should have a mapping

and the other error:

Cannot resolve Servlet

But in the below code you can see every servlet have its mapping:

In my web.xml, I have 8 servlet, and every servlet has its corresponding mapping:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>loginservlet</servlet-name>
    <servlet-class>com.sam.servlet.loginservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>changeservlet</servlet-name>
    <servlet-class>com.sam.servlet.changeservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Searchservlet</servlet-name>
    <servlet-class>com.sam.servlet.Searchservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>borrowservlet</servlet-name>
    <servlet-class>com.sam.servlet.borrowservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>mealselectservlet</servlet-name>
    <servlet-class>com.sam.servlet.mealselectservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>mealaddservlet</servlet-name>
    <servlet-class>com.sam.servlet.mealaddservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>mealdeletedservlet</servlet-name>
    <servlet-class>com.sam.servlet.mealdeletedservlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>mealupdateservlet</servlet-name>
    <servlet-class>com.sam.servlet.mealupdateservlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>loginservlet</servlet-name>
    <url-pattern>/loginservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>changeservlet</servlet-name>
    <url-pattern>/changeservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Searchservlet</servlet-name>
    <url-pattern>/Searchservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>borrowservlet</servlet-name>
    <url-pattern>/borrowservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>mealselectservlet</servlet-name>
    <url-pattern>/mealselectservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>mealaddservlet</servlet-name>
    <url-pattern>/mealaddservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>mealdeletedservlet</servlet-name>
    <url-pattern>/mealdeletedservlet</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>mealupdateservlet</servlet-name>
    <url-pattern>/mealupdateservlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


问:
pack_forget() not working
After creating a Label object in tkinter I tried to remove label using pack_forget attribute. But script not working. I am using python version 2.7.9 in raspbian.
Code is like:</p>

```<code>visual = Tkinter.Tk()
sample = Label(visual, text="Hello python!")
sample.pack()
visual.update()
time.sleep(2)
sample.pack_forget()
visual.update()
</code>```

答: The effect of    pack_forget() is render the widget on which it is applied to be invisible (like it is falsely removed). The proof is that if you add, after visual.update() this line print(sample.winfo_exists()) it will print you 1, which thing means your label still exists in reality. So to effectively get rid of your label, you must use sample.destroy() instead. In this later case, the line print(sample.winfo_exists()) will print 0 meaning your label called sample does not exist any more.

Title: pack_forget() not working

Body:
After creating a Label object in tkinter I tried to remove label using pack_forget attribute. But script not working. I am using python version 2.7.9 in raspbian.
Code is like:

visual = Tkinter.Tk()
sample = Label(visual, text="Hello python!")
sample.pack()
visual.update()
time.sleep(2)
sample.pack_forget()
visual.update()


问:
How to call / access a label in button action programmatically?
```<code>//This is the label

let changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

self.view.addSubview(changeLbl)

//This is the button

let submitButton = UIButton(type: .system) // let preferred over var here

submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

self.view.addSubview(submitButton)

//and this is action of above button

func buttonAction(sender: UIButton!) {

}
</code>```

I want to call the above label in the following button function? like

```<code>func buttonAction(sender: UIButton!) {
    changeLbl.ishidden = true
</code>```

// want to access label here, but it's not working this way.
    }

答:
If you want to Access changeLbl you need to define as instance variable like this way and give global scope inside the class.

```<code>class ViewController: UIViewController {

    var changeLbl : UILabel!
    var submitButton : UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

         //This is the UILabel
        changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

        self.view.addSubview(changeLbl)

         //This is the button
        submitButton = UIButton(type: .system) // let preferred over var here

        submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)
        self.view.addSubview(submitButton)

    }

    //and this is action of above button

    func buttonAction(sender: UIButton!) {
        changeLbl.isHidden = true
    }
}
</code>```

Body:
//This is the label

let changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

self.view.addSubview(changeLbl)

//This is the button

let submitButton = UIButton(type: .system) // let preferred over var here

submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)

self.view.addSubview(submitButton)

//and this is action of above button

func buttonAction(sender: UIButton!) {

}

I want to call the above label in the following button function? like

func buttonAction(sender: UIButton!) {
    changeLbl.ishidden = true

// want to access label here, but it's not working this way.
    }

Body:
If you want to Access changeLbl you need to define as instance variable like this way and give global scope inside the class.

class ViewController: UIViewController {

    var changeLbl : UILabel!
    var submitButton : UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

         //This is the UILabel
        changeLbl = UILabel(frame: CGRect(x: 20, y: 170, width: 300, height: 21))

        self.view.addSubview(changeLbl)

         //This is the button
        submitButton = UIButton(type: .system) // let preferred over var here

        submitButton.addTarget(self, action: #selector(buttonAction) , for: UIControlEvents.touchUpInside)
        self.view.addSubview(submitButton)

    }

    //and this is action of above button

    func buttonAction(sender: UIButton!) {
        changeLbl.isHidden = true
    }
}


问:
Why my music won't play on Android Studio?
I'm using Android Studio.I tried all the codes that I've seen on the internet but my app doesn't work. I have a raw folder which contains the music that I'll be use but still I don't know what is the error in my code.

Here's my code:

```<code> package com.example.aloja.babysteps;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

/**
 * Created by Aloja on 3/27/2017.
 */

public class A extends Activity {
    Button btnBack3,btnPlay;

    ImageView ivApple;
    MediaPlayer apple;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a);
        btnBack3 = (Button) findViewById(R.id.btnBack3);
        btnPlay =(Button) findViewById(R.id.btnPlay);
        ivApple = (ImageView) findViewById(R.id.ivApple);
        ivApple.setImageResource(R.drawable.apple);

        apple= MediaPlayer.create(this, R.raw.apple);

        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                apple.start();

            }
        });
    }

        protected void onPause(){
            super.onPause();
            apple.stop();
            apple.release();

    }

}
</code>```

P.S Sorry for my english. Hope you understand what I'm trying to ask

答:
Try this code hope it will help you.</p>

```<code>int resID=getResources().getIdentifier("filename", "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);

mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {

                        Log.e("MediaPlayer", "what=="+what);
                        Log.e("MediaPlayer", "extra=="+extra);

                        return false;
                    }
                });
mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {

                        Log.e("MediaPlayer", "what=="+what);
                        Log.e("MediaPlayer", "extra=="+extra);
                        return false;
                    }
                });

                mediaPlayer.start();
</code>```

Body:
I'm using Android Studio.I tried all the codes that I've seen on the internet but my app doesn't work. I have a raw folder which contains the music that I'll be use but still I don't know what is the error in my code.

Here's my code:

 package com.example.aloja.babysteps;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

/**
 * Created by Aloja on 3/27/2017.
 */

public class A extends Activity {
    Button btnBack3,btnPlay;

    ImageView ivApple;
    MediaPlayer apple;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a);
        btnBack3 = (Button) findViewById(R.id.btnBack3);
        btnPlay =(Button) findViewById(R.id.btnPlay);
        ivApple = (ImageView) findViewById(R.id.ivApple);
        ivApple.setImageResource(R.drawable.apple);

        apple= MediaPlayer.create(this, R.raw.apple);

        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                apple.start();

            }
        });
    }

        protected void onPause(){
            super.onPause();
            apple.stop();
            apple.release();

    }

}

P.S Sorry for my english. Hope you understand what I'm trying to ask

Body:
Try this code hope it will help you.

int resID=getResources().getIdentifier("filename", "raw", getPackageName());
MediaPlayer mediaPlayer=MediaPlayer.create(this,resID);

mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                    @Override
                    public boolean onError(MediaPlayer mp, int what, int extra) {

                        Log.e("MediaPlayer", "what=="+what);
                        Log.e("MediaPlayer", "extra=="+extra);

                        return false;
                    }
                });
mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(MediaPlayer mp, int what, int extra) {

                        Log.e("MediaPlayer", "what=="+what);
                        Log.e("MediaPlayer", "extra=="+extra);
                        return false;
                    }
                });

                mediaPlayer.start();


问:
Why I get [Laravel - Undefined variable: users (View..] if I tried to use POST and GET on the same view?
I am trying to make a simple search form using laravel.
the search page is supposed to be the same for results.
but I can't make it work, and i'm not sure why
It works on a different Route but can't get it to work on the same route.

Routes:

```<code>Route::get('searchuser',function(){
return view('searchuser');

 })->middleware('auth');

Route::post('searchuser', function(){
$q = Input::get('name');
$users = App\User::where('name_en','like',$q)->get();

return view('searchuser', ['users' => $users]);

 });
</code>```

Blade:

```<code>                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="searchuser">
                    {{ csrf_field() }}

                    <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                        <label for="name" class="col-md-4 control-label">Name</label>

                        <div class="col-md-6">
                            <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Search.." required autofocus>

                            @if ($errors->has('name'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('name') }}</strong>
                                </span>
                            @endif
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-md-6 col-md-offset-4">
                            <button type="submit" class="btn btn-primary">
                                Search
                            </button>

                        </div>
                    </div>
                </form>
                <div>
                    @foreach($users as $user)
                        {{$user->name_ar . '<br />'}}
                    @endforeach
                </div>
            </div>
</code>```

答:
Follow this

```<code>Route::post('searchuser', function(){
    $q = Input::get('name'); //problem in your code
    $q = \Illuminate\Support\Facades\Input::get('name'); //update
    $users2 = App\User::where('name_en','like',$q)->get();

    return view('searchuser', ['users' => $users2]);
});
</code>```

Use

return view('searchuser', ['users' => $users2]);

OR

$users = App\User::where('name_en','like',$q)->get();

I follow 1st one

Body:
I am trying to make a simple search form using laravel.
the search page is supposed to be the same for results.
but I can't make it work, and i'm not sure why
It works on a different Route but can't get it to work on the same route.

Routes:

Route::get('searchuser',function(){
return view('searchuser');

 })->middleware('auth');

Route::post('searchuser', function(){
$q = Input::get('name');
$users = App\User::where('name_en','like',$q)->get();

return view('searchuser', ['users' => $users]);

 });

Blade:

                    <form class="form-horizontal" role="form" method="POST" action="searchuser">
                    {{ csrf_field() }}

has('name') ? ' has-error' : '' }}">
                        Name

                            <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Search.." required autofocus>

                            @if ($errors->has('name'))

                                    {{ $errors->first('name') }}

                            @endif

                            <button type="submit" class="btn btn-primary">
                                Search
                            </button>

                </form>

                    @foreach($users as $user)
                        {{$user->name_ar . '
'}}
                    @endforeach

Body:
Follow this

Route::post('searchuser', function(){
    $q = Input::get('name'); //problem in your code
    $q = \Illuminate\Support\Facades\Input::get('name'); //update
    $users2 = App\User::where('name_en','like',$q)->get();

    return view('searchuser', ['users' => $users2]);
});

Use

return view('searchuser', ['users' => $users2]);

OR

$users = App\User::where('name_en','like',$q)->get();

I follow 1st one


问:
Replace nth char with sed
i wanna change or delete every 3rd and 4th chars of a string with sed.

For example the text:

abcdefghijklmnopqrstuvxz

Should be transformed to:

abefijmnqruv

Thanks in advance.

答:
Ok, I got the answer

echo abcdefghijklmnopqrstuvxz | sed 's/\(.\{4\}\).\{3\}/\1/g'

4 and 3 are examples... thanks a lot

Title: Replace nth char with sed


问:
Cannot get method annotation from JDK dynamic proxy
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this

In my client, I could get the annotation on my method using my Real Object, but not Proxy Object.

I used to think it was because of the lack of Retention Annotation on my own Annotation. But it doesn't work. Here is the code:

Annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}
```

<p><strong>Interface:</strong></p>

<pre class="lang-java prettyprint-override"><code>public interface UserDao {
    void save();
    void update();
}
</code>```

Implementation:

public class UserDaoImpl implements UserDao{
    @Override
    @MyAnnotation
    public void save() {
        System.out.println("save");
    }

    @Override
    public void update() {
        System.out.println("update");
    }
}
```

<p><strong>Client + driver application:</strong></p>

<pre class="lang-java prettyprint-override"><code>public class Client {
    public static void main(String[] args) {
        final UserDaoImpl dao = new UserDaoImpl();
        Method[] methods = dao.getClass().getMethods();
        for (Method m : methods){
            if(m.getAnnotation(MyAnnotation.class) != null)
                System.out.println("save method is enhanced");
        }

        UserDao proxy = (UserDao) Proxy.newProxyInstance(
            dao.getClass().getClassLoader(),
            dao.getClass().getInterfaces(),
            new InvocationHandler() {
                    @Override
                    public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
                        obj = dao;
                        if(method.getAnnotation(MyAnnotation.class) != null)
                            System.out.println("save method is enhanced2");
                        Object result = method.invoke(obj, args);
                        return result;
                    }
            }
        );

        proxy.save();
        System.out.println("-----------");
        proxy.update();
    }
}
</code>```

答:
The dynamic proxy directly implements the given interface, it does not extend the implementing class as you seem to assume. I have fixed your non-compiling code, added some more log output and moved all classes into one of my packages because the Java compiler does not like the default package.

Driver application (updated):

package de.scrum_master.so;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Client {
  public static void main(String[] args) {
    final UserDaoImpl dao = new UserDaoImpl();
    Method[] methods = dao.getClass().getMethods();
    for (Method method : methods) {
      if (method.getAnnotation(MyAnnotation.class) != null) {
        System.out.println(method + " -> " + method.getDeclaringClass());
        System.out.println("impl method is enhanced");
      }
    }
    System.out.println("-----------");

    UserDao proxy = (UserDao) Proxy.newProxyInstance(
      dao.getClass().getClassLoader(),
      dao.getClass().getInterfaces(),
      new InvocationHandler() {
        @Override
        public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
          obj = dao;
          System.out.println(method + " -> " + method.getDeclaringClass());
          if (method.getAnnotation(MyAnnotation.class) != null)
            System.out.println("proxy method is enhanced");
          Object result = method.invoke(obj, args);
          return result;
        }
      });

    proxy.save();
    System.out.println("-----------");
    proxy.update();
  }
}
```

<p><strong>Console log:</strong></p>

<pre class="lang-none prettyprint-override"><code>public void de.scrum_master.so.UserDaoImpl.save() -> class de.scrum_master.so.UserDaoImpl
impl method is enhanced
-----------
public abstract void de.scrum_master.so.UserDao.save() -> interface de.scrum_master.so.UserDao
save
-----------
public abstract void de.scrum_master.so.UserDao.update() -> interface de.scrum_master.so.UserDao
update
</code>```

Here you can see the difference between UserDaoImpl and the dynamic UserDao proxy.

I am unsure why you tagged this question with spring and aop because in your sample code there is no AOP and no Spring, but I suppose you want to use Spring AOP which is also based on dynamic proxies. There you have the option to enforce that also components implementing interfaces are to be created as CGLIB proxies, i.e. the proxies extend their base classes directly. Maybe then it works, but I am not sure how CGLIB proxies work in detail. If they would override each method, a JVM limitation would apply: Method annotations are never inherited by overriding methods.

So much for your technical problem. But what is it you really want to achieve? This is a mistake many people make here: They do not describe what they want to achieve but already have a technical solution in mind which might be inappropriate. This way they miss other options to solve their problem. Often the application design is flawed based on their false assumptions and could easily be fixed if they were not so fixated on their solution bias. Maybe if this does not help you, you create a new question, link it to this one, therein show your Spring AOP problem and describe what you want to achieve.

Update: If you want to access the original ("real") object from the proxy's invocation handler, you can do it like this:

Improved driver application:

package de.scrum_master.so;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Client {
  public static void main(String[] args) {
    final UserDaoImpl dao = new UserDaoImpl();
    Method[] methods = dao.getClass().getMethods();
    for (Method method : methods) {
      if (method.getAnnotation(MyAnnotation.class) != null) {
        System.out.println(method + " -> " + method.getDeclaringClass());
        System.out.println("impl method is enhanced");
      }
    }
    System.out.println("-----------");

    UserDao proxy = (UserDao) Proxy.newProxyInstance(
      dao.getClass().getClassLoader(),
      dao.getClass().getInterfaces(),
      new MyInvocationHandler(dao)
    );

    proxy.save();
    System.out.println("-----------");
    proxy.update();
  }

  private static class MyInvocationHandler implements InvocationHandler {
    private Object realObject;

    public MyInvocationHandler(Object realObject) {
      this.realObject = realObject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      System.out.println(method + " -> " + method.getDeclaringClass());
      if (method.getAnnotation(MyAnnotation.class) != null)
        System.out.println("proxy method is enhanced");
      if (realObject.getClass().getMethod(method.getName(), method.getParameterTypes()).getAnnotation(MyAnnotation.class) != null)
        System.out.println("real object method is enhanced");
      return method.invoke(realObject, args);
    }

  }
}
```

<p><strong>Console log:</strong></p>

<pre class="lang-none prettyprint-override"><code>public void de.scrum_master.so.UserDaoImpl.save() -> class de.scrum_master.so.UserDaoImpl
impl method is enhanced
-----------
public abstract void de.scrum_master.so.UserDao.save() -> interface de.scrum_master.so.UserDao
real object method is enhanced
save
-----------
public abstract void de.scrum_master.so.UserDao.update() -> interface de.scrum_master.so.UserDao
update
</code>```

Please note the line real object method is enhanced.

Body:
I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this

In my client, I could get the annotation on my method using my Real Object, but not Proxy Object.

I used to think it was because of the lack of Retention Annotation on my own Annotation. But it doesn't work. Here is the code:

Annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}

Interface:

public interface UserDao {
    void save();
    void update();
}

Implementation:

public class UserDaoImpl implements UserDao{
    @Override
    @MyAnnotation
    public void save() {
        System.out.println("save");
    }

    @Override
    public void update() {
        System.out.println("update");
    }
}

Client + driver application:

public class Client {
    public static void main(String[] args) {
        final UserDaoImpl dao = new UserDaoImpl();
        Method[] methods = dao.getClass().getMethods();
        for (Method m : methods){
            if(m.getAnnotation(MyAnnotation.class) != null)
                System.out.println("save method is enhanced");
        }

        UserDao proxy = (UserDao) Proxy.newProxyInstance(
            dao.getClass().getClassLoader(),
            dao.getClass().getInterfaces(),
            new InvocationHandler() {
                    @Override
                    public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
                        obj = dao;
                        if(method.getAnnotation(MyAnnotation.class) != null)
                            System.out.println("save method is enhanced2");
                        Object result = method.invoke(obj, args);
                        return result;
                    }
            }
        );

        proxy.save();
        System.out.println("-----------");
        proxy.update();
    }
}

Body:
The dynamic proxy directly implements the given interface, it does not extend the implementing class as you seem to assume. I have fixed your non-compiling code, added some more log output and moved all classes into one of my packages because the Java compiler does not like the default package.

Driver application (updated):

package de.scrum_master.so;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Client {
  public static void main(String[] args) {
    final UserDaoImpl dao = new UserDaoImpl();
    Method[] methods = dao.getClass().getMethods();
    for (Method method : methods) {
      if (method.getAnnotation(MyAnnotation.class) != null) {
        System.out.println(method + " -> " + method.getDeclaringClass());
        System.out.println("impl method is enhanced");
      }
    }
    System.out.println("-----------");

    UserDao proxy = (UserDao) Proxy.newProxyInstance(
      dao.getClass().getClassLoader(),
      dao.getClass().getInterfaces(),
      new InvocationHandler() {
        @Override
        public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
          obj = dao;
          System.out.println(method + " -> " + method.getDeclaringClass());
          if (method.getAnnotation(MyAnnotation.class) != null)
            System.out.println("proxy method is enhanced");
          Object result = method.invoke(obj, args);
          return result;
        }
      });

    proxy.save();
    System.out.println("-----------");
    proxy.update();
  }
}

Console log:

public void de.scrum_master.so.UserDaoImpl.save() -> class de.scrum_master.so.UserDaoImpl
impl method is enhanced
-----------
public abstract void de.scrum_master.so.UserDao.save() -> interface de.scrum_master.so.UserDao
save
-----------
public abstract void de.scrum_master.so.UserDao.update() -> interface de.scrum_master.so.UserDao
update

Here you can see the difference between UserDaoImpl and the dynamic UserDao proxy.

I am unsure why you tagged this question with spring and aop because in your sample code there is no AOP and no Spring, but I suppose you want to use Spring AOP which is also based on dynamic proxies. There you have the option to enforce that also components implementing interfaces are to be created as CGLIB proxies, i.e. the proxies extend their base classes directly. Maybe then it works, but I am not sure how CGLIB proxies work in detail. If they would override each method, a JVM limitation would apply: Method annotations are never inherited by overriding methods.

So much for your technical problem. But what is it you really want to achieve? This is a mistake many people make here: They do not describe what they want to achieve but already have a technical solution in mind which might be inappropriate. This way they miss other options to solve their problem. Often the application design is flawed based on their false assumptions and could easily be fixed if they were not so fixated on their solution bias. Maybe if this does not help you, you create a new question, link it to this one, therein show your Spring AOP problem and describe what you want to achieve.

Update: If you want to access the original ("real") object from the proxy's invocation handler, you can do it like this:

Improved driver application:

package de.scrum_master.so;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Client {
  public static void main(String[] args) {
    final UserDaoImpl dao = new UserDaoImpl();
    Method[] methods = dao.getClass().getMethods();
    for (Method method : methods) {
      if (method.getAnnotation(MyAnnotation.class) != null) {
        System.out.println(method + " -> " + method.getDeclaringClass());
        System.out.println("impl method is enhanced");
      }
    }
    System.out.println("-----------");

    UserDao proxy = (UserDao) Proxy.newProxyInstance(
      dao.getClass().getClassLoader(),
      dao.getClass().getInterfaces(),
      new MyInvocationHandler(dao)
    );

    proxy.save();
    System.out.println("-----------");
    proxy.update();
  }

  private static class MyInvocationHandler implements InvocationHandler {
    private Object realObject;

    public MyInvocationHandler(Object realObject) {
      this.realObject = realObject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      System.out.println(method + " -> " + method.getDeclaringClass());
      if (method.getAnnotation(MyAnnotation.class) != null)
        System.out.println("proxy method is enhanced");
      if (realObject.getClass().getMethod(method.getName(), method.getParameterTypes()).getAnnotation(MyAnnotation.class) != null)
        System.out.println("real object method is enhanced");
      return method.invoke(realObject, args);
    }

  }
}

Console log:

public void de.scrum_master.so.UserDaoImpl.save() -> class de.scrum_master.so.UserDaoImpl
impl method is enhanced
-----------
public abstract void de.scrum_master.so.UserDao.save() -> interface de.scrum_master.so.UserDao
real object method is enhanced
save
-----------
public abstract void de.scrum_master.so.UserDao.update() -> interface de.scrum_master.so.UserDao
update

Please note the line real object method is enhanced.


问:
What's the difference between using `.catch(function(error)` and `function(errResponse)` when handing errors from AngularJS promises?
I'm reading AngularJS Up and Running. In chapter 6, it mentions handing errors from promises like this:

```<code>$http.get('/api/server-config').then(function(configResponse) {
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}, function(error) {
    // Common error handling
});
</code>```

And in other places, I see .catch() being used (for example, the answer here: Assigning variable from a factory to a control doesn't work uses .catch() like so:

```<code>BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});
</code>```

My question is, what's the difference between the above menthod and the method shown in the book:

```<code>BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}, function(error) {
    self.cerrorMessages = errorResponse.data;
});
</code>```

What's preferred?

答:
The catch syntax is better as it separate the error handling to its own and single channel, away from the control flow, it is considered as good practice, promoted by bluebird.js and others, while the use of an error handler function as the second parameters of the then function can be considered as an anti-pattern.

You can find some really good read about them:

http://www.datchley.name/promise-patterns-anti-patterns/

http://taoofcode.net/promise-anti-patterns/

https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns

The different between the two can be illustrated via an example. As for first piece of code you posted:

```<code>$http.get('/api/server-config').then(function(configResponse) {
    // create another promising chain here
    $http.get("/something-else").then(function(response) {
       // Do something
    });
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}, function(error) {
    // Common error handling
});
</code>```

If instead of just returning the promise, I call another async function inside the first promise resolver, the error from this function will never reach the last error handler, if I forget to handle the error from that new function separately, it will be swallowed.

However, this problem can be fixed using a catch:

```<code>$http.get('/api/server-config').then(function(configResponse) {
    // create another promising chain here
    $http.get("/something-else").then(function(response) {
       // Do something
    });
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}).catch(function(error) {
    // error from nested function something else, can also be handled here
    // within a single error handling channel
});
</code>```

Body:
I'm reading AngularJS Up and Running. In chapter 6, it mentions handing errors from promises like this:

$http.get('/api/server-config').then(function(configResponse) {
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}, function(error) {
    // Common error handling
});

And in other places, I see .catch() being used (for example, the answer here: Assigning variable from a factory to a control doesn't work uses .catch() like so:

BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});

My question is, what's the difference between the above menthod and the method shown in the book:

BaseService.fetch.stuffs
.then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}, function(error) {
    self.cerrorMessages = errorResponse.data;
});

What's preferred?

Body:
The catch syntax is better as it separate the error handling to its own and single channel, away from the control flow, it is considered as good practice, promoted by bluebird.js and others, while the use of an error handler function as the second parameters of the then function can be considered as an anti-pattern.

You can find some really good read about them:

http://www.datchley.name/promise-patterns-anti-patterns/

http://taoofcode.net/promise-anti-patterns/

https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns

The different between the two can be illustrated via an example. As for first piece of code you posted:

$http.get('/api/server-config').then(function(configResponse) {
    // create another promising chain here
    $http.get("/something-else").then(function(response) {
       // Do something
    });
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}, function(error) {
    // Common error handling
});

If instead of just returning the promise, I call another async function inside the first promise resolver, the error from this function will never reach the last error handler, if I forget to handle the error from that new function separately, it will be swallowed.

However, this problem can be fixed using a catch:

$http.get('/api/server-config').then(function(configResponse) {
    // create another promising chain here
    $http.get("/something-else").then(function(response) {
       // Do something
    });
    return $http.get('/api/' + configResponse.data.USER_END_POINT);
}).then(function(userResponse) {
    return $http.get('/api/' + userResponse.data.id + '/items');
}).then(function(itemResponse) {
    // Display items here
}).catch(function(error) {
    // error from nested function something else, can also be handled here
    // within a single error handling channel
});


问:
Fetch Currency on the basis of Country or time zone PHP, Codeigniter
I want to get currency on the basis of country, suppose if i'm accessing my web page in US then my currency should be in Dollars and if i'm accessing my page in some other region lets suppose UAE so my currency should be in Durham.

i'm confused how to get such value, i've tried all posible way, such as geoip_time_zone_by_country_and_region();
geoip_region_by_name();
may be i'm not getting these in proper way. i'm doing it by using PHP and codeigniter.

答:
Currency Symbol

Country Flag

Currency Format

Other custom options

I am using all this in one of my project which is in production and I can share that with you.

Step-1

I am using a preferences table in which I keep the settings like this

Step-2

In my controller I get country by IP and save the code in a variable

```<code>$geo_data = geolocation_by_ip($ip);
</code>```

Reference : Geo Location by IP

In my model I create a function to get preferences via country code

```<code>$data['preferences']=$this->My_Model->getPrefByCountryCode($geo_data['country_code']);
</code>```

and save them in array and then I send it to the view

```<code>$this->load->view('path/to/my/view',$data);
</code>```

In my view I just echo them

Currency Format

For currency formats I use PHP money_format() function and for second parameter in

```<code>setlocale(LC_MONETARY,"en_US"); // I get money_format from database
</code>```

The rest is done by the function and the view is rendered. I save Symbols and Flags as icons and images, get their urls and echo them. Ofcourse this might not be the perfect way but it can save a lot of research

Body:
Currency Symbol

Country Flag

Currency Format

Other custom options

I am using all this in one of my project which is in production and I can share that with you.

Step-1

I am using a preferences table in which I keep the settings like this

Step-2

In my controller I get country by IP and save the code in a variable

$geo_data = geolocation_by_ip($ip);

Reference : Geo Location by IP

In my model I create a function to get preferences via country code

$data['preferences']=$this->My_Model->getPrefByCountryCode($geo_data['country_code']);

and save them in array and then I send it to the view

$this->load->view('path/to/my/view',$data);

In my view I just echo them

Currency Format

For currency formats I use PHP money_format() function and for second parameter in

setlocale(LC_MONETARY,"en_US"); // I get money_format from database

The rest is done by the function and the view is rendered. I save Symbols and Flags as icons and images, get their urls and echo them. Ofcourse this might not be the perfect way but it can save a lot of research


问:
OSGi: What happens if not to unget service
This is the way how I get OSGi service:

```<code>ServiceReference reference = bundleContext.getServiceReference(Foo.class.getName());
 Foo foo=(Foo) bundleContext.getService(reference);
</code>```

What happens if I don't do bunldeContext.ungetSerivice(reference) when I finished with service:

If I registered service manually, for example in activator

If I use declarative service and it is Singleton

答:
The OSGi framework maintains a use count of each service for your bundle. If your bundle does not unget the service, it will be released automatically by the framework when either your bundle stops or the service is unregistered.

It you are using Declarative Services, SCR will handle calling unget at the appropriate time in the life cycle of the component referencing the service.

Body:
This is the way how I get OSGi service:

ServiceReference reference = bundleContext.getServiceReference(Foo.class.getName());
 Foo foo=(Foo) bundleContext.getService(reference);

What happens if I don't do bunldeContext.ungetSerivice(reference) when I finished with service:

If I registered service manually, for example in activator

If I use declarative service and it is Singleton


问:
change job parameter value in Groovy System Script
My parameterized Freestyle job got one string parameter. MAIL_PARAM with the default value FREESTYLE_ERROR.

I am able to print the value with:

```<code>println "MAIL_PARAM=$Mail_Param"
</code>```

Inside an Groovy execute Script. Now I want to change the value of this parameter based on some conditions. But I am not able to change it. I tried:

```<code>MAIL_PARAM = 'String'
$MAIL_PARAM ='String'
${MAIL_PARAM} ='String'
def params = new StringParameterValue('MAIL_PARAM', 'String')
</code>```

and some more, but none of them are working. I have to change it because based on some results my groovy script has, I need different Strings inside of my parameter.

After the groovy script I need to pass this parameter to the next job. This works fine. But I only get the default value.

答:
If I understand correctly, replaceAction should do the trick (there is also addOrReplaceAction):

```<code>import hudson.model.ParametersAction
import hudson.model.ParameterValue
import hudson.model.StringParameterValue
def newMailParameter = new StringParameterValue('MAIL_PARAM', '...')
build.replaceAction(new ParametersAction(newMailParameter))
</code>```

Edit : if you get error "current build does not have any parameter" then please try "build.addOrReplaceAction" in place of "build.replaceAction".

Body:
My parameterized Freestyle job got one string parameter. MAIL_PARAM with the default value FREESTYLE_ERROR.

I am able to print the value with:

println "MAIL_PARAM=$Mail_Param"

Inside an Groovy execute Script. Now I want to change the value of this parameter based on some conditions. But I am not able to change it. I tried:

MAIL_PARAM = 'String'
$MAIL_PARAM ='String'
${MAIL_PARAM} ='String'
def params = new StringParameterValue('MAIL_PARAM', 'String')

and some more, but none of them are working. I have to change it because based on some results my groovy script has, I need different Strings inside of my parameter.

After the groovy script I need to pass this parameter to the next job. This works fine. But I only get the default value.

Body:
If I understand correctly, replaceAction should do the trick (there is also addOrReplaceAction):

import hudson.model.ParametersAction
import hudson.model.ParameterValue
import hudson.model.StringParameterValue
def newMailParameter = new StringParameterValue('MAIL_PARAM', '...')
build.replaceAction(new ParametersAction(newMailParameter))

Edit : if you get error "current build does not have any parameter" then please try "build.addOrReplaceAction" in place of "build.replaceAction".


问:
Virtual keyboard in Symbian S60 5th edition: Which API to use?
How (i.e. using which API) is the virtual keyboard opened on Symbian S60 5th edition? The documentation seems to lack information about this.</p>

答:
Tinkering with focus on a QLineEdit inside custom coded kinetic scroll area, I've had a simmilar problem (how to open virtual keyboard manually). Then, I found it, this obviously works in Qt 4.6.3 on a C7 Symbian^3 phone:

```<code>// lineEdit is an instance of QLineEdit
QApplication::postEvent(lineEdit, new QEvent(QEvent::RequestSoftwareInputPanel));
</code>```

Before that, I also had to post a QEvent::FocusIn event to that same lineedit, otherwise the QLineEdit did not update the content from virtual keyboard.

Hope this is helpful. I lost hours.

Body:
Tinkering with focus on a QLineEdit inside custom coded kinetic scroll area, I've had a simmilar problem (how to open virtual keyboard manually). Then, I found it, this obviously works in Qt 4.6.3 on a C7 Symbian^3 phone:

// lineEdit is an instance of QLineEdit
QApplication::postEvent(lineEdit, new QEvent(QEvent::RequestSoftwareInputPanel));

Before that, I also had to post a QEvent::FocusIn event to that same lineedit, otherwise the QLineEdit did not update the content from virtual keyboard.

Hope this is helpful. I lost hours.


问:
Values of the inserted row in a Trigger Oracle
I want a trigger that updates the value of a column, but I just want to update a small set of rows that depends of the values of the inserted row.
My trigger is:

```<code>CREATE OR REPLACE TRIGGER example
AFTER INSERT ON table1
FOR EACH ROW
BEGIN
UPDATE table1 t
SET column2 = 3
WHERE t.column1 = :new.column1;
END;
/
</code>```

But as I using FOR EACH ROW I have a problem when I try it, I get the mutating table runtime error.
Other option is not to set the FOR EACH ROW, but if I do this, I dont know the inserted "column1" for comparing (or I dont know how to known it).

What can I do for UPDATING a set of rows that depends of the last inserted row?

I am using Oracle 9.

答:
You should avoid the DML statements on the same table as defined in a trigger. Use before DML to change values of the current table.

```<code>create or replace trigger example
before insert on table1
for each row
begin
    :new.column2 := 3;
end;
/
</code>```

You can modify the same table with pragma autonomous_transaction:

```<code>create or replace trigger example
after insert on table1 for each row
declare
    procedure setValues(key number) is
        pragma autonomous_transaction;
    begin
        update table1 t
        set column2 = 3
        where t.column1 = key
        ;
    end setValues;
begin
    setValues(:new.column1);
end;
/
</code>```

But I suggest you follow @GordonLinoff answere to your question - it's a bad idea to modify the same table in the trigger body.

See also here

Body:
I want a trigger that updates the value of a column, but I just want to update a small set of rows that depends of the values of the inserted row.
My trigger is:

CREATE OR REPLACE TRIGGER example
AFTER INSERT ON table1
FOR EACH ROW
BEGIN
UPDATE table1 t
SET column2 = 3
WHERE t.column1 = :new.column1;
END;
/

But as I using FOR EACH ROW I have a problem when I try it, I get the mutating table runtime error.
Other option is not to set the FOR EACH ROW, but if I do this, I dont know the inserted "column1" for comparing (or I dont know how to known it).

What can I do for UPDATING a set of rows that depends of the last inserted row?

I am using Oracle 9.

Body:
You should avoid the DML statements on the same table as defined in a trigger. Use before DML to change values of the current table.

create or replace trigger example
before insert on table1
for each row
begin
    :new.column2 := 3;
end;
/

You can modify the same table with pragma autonomous_transaction:

create or replace trigger example
after insert on table1 for each row
declare
    procedure setValues(key number) is
        pragma autonomous_transaction;
    begin
        update table1 t
        set column2 = 3
        where t.column1 = key
        ;
    end setValues;
begin
    setValues(:new.column1);
end;
/

But I suggest you follow @GordonLinoff answere to your question - it's a bad idea to modify the same table in the trigger body.

See also here


问:
how extract special data from numpy like R
i stored a bed file in numpy like this:

```<code>>>> t
array([['chr1', '2488152', '2488153'],
       ['chr1', '2488397', '2488398'],
       ['chr1', '2491262', '2491417'],
       ...,
       ['chrX', '153628144', '153628282'],
       ['chrX', '154292795', '154292796'],
       ['chrX', '154294899', '154294900']],
      dtype='|S9')
</code>```

usually, I do this job with R

```<code>library(dplyr)
filter(t, chrom=='chr1')
</code>```

how can I get the same result with numpy? and is there any better way to stored bed file and extract the special lines I need?

thanks for any help.

答:
Create a boolean mask by comparing the first column of every row in t to some value, and then apply that mask to t

```<code>>>> t[:,0]
array([b'chr1', b'chr1', b'chr1', b'chrX', b'chrX', b'chrX'],
      dtype='|S9')
>>> mask = t[:,0]==b'chr1'
>>> mask
array([ True,  True,  True, False, False, False], dtype=bool)
>>> t[mask]
array([[b'chr1', b'2488152', b'2488153'],
       [b'chr1', b'2488397', b'2488398'],
       [b'chr1', b'2491262', b'2491417']],
      dtype='|S9')
</code>```

Body:
i stored a bed file in numpy like this:

>>> t
array([['chr1', '2488152', '2488153'],
       ['chr1', '2488397', '2488398'],
       ['chr1', '2491262', '2491417'],
       ...,
       ['chrX', '153628144', '153628282'],
       ['chrX', '154292795', '154292796'],
       ['chrX', '154294899', '154294900']],
      dtype='|S9')

usually, I do this job with R

library(dplyr)
filter(t, chrom=='chr1')

how can I get the same result with numpy? and is there any better way to stored bed file and extract the special lines I need?

thanks for any help.

Body:
Create a boolean mask by comparing the first column of every row in t to some value, and then apply that mask to t

>>> t[:,0]
array([b'chr1', b'chr1', b'chr1', b'chrX', b'chrX', b'chrX'],
      dtype='|S9')
>>> mask = t[:,0]==b'chr1'
>>> mask
array([ True,  True,  True, False, False, False], dtype=bool)
>>> t[mask]
array([[b'chr1', b'2488152', b'2488153'],
       [b'chr1', b'2488397', b'2488398'],
       [b'chr1', b'2491262', b'2491417']],
      dtype='|S9')


问:
twitter api response array
I've a (i hope small) porblem. I'm building a twitter bot with TwitterAPIExchange.php, but if I run the script the hole time I only see arrayon my screen. what do I wrong? here is my twitter.php code:

```<code>    <?php

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'consumer_key' => "xxx",
'consumer_secret' => "xxx",
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "xxx"
);
$url = "https://api.twitter.com/1.1/search/tweets.json";

 $requestMethod = "GET";

$getfield = '?q=kamerwatch';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(), true);
if($string["errors"][0]["message"] != "") {echo "<h3>Sorry, there was a             problem.</h3><p>Twitter returned the following error message:</p><p>                         <em>".$string[errors][0]["message"]."</em></p>";exit();}

echo $string;
foreach($string as $items)
{
echo "Screen name: ". $items['user']['screen_name']."<br />";
echo "Tweet: ". $items['text']."<br />";
echo "Time and Date of Tweet: ".$items['created_at']."<br />";
echo "Tweet ID: ".$items['id_str']."<br />";
echo "Followers: ". $items['user']['followers_count']."<br /><hr />";
}
?>
</code>```

code at the moment:

```<code><?php

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'consumer_key' => "xxx",
'consumer_secret' =>  "xxx",
'oauth_access_token' => "xxxx",
'oauth_access_token_secret' => "xxx"
);
$url = "https://api.twitter.com/1.1/search/tweets.json";

$requestMethod = "GET";

$getfield = '?q=kamerwatch&count=3'; /* added only 3 results for testing     purpose */
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
     ->buildOauth($url, $requestMethod)
     ->performRequest();

$string = json_decode($response, true);
#print_r($string); /* outputs what follows */

foreach ($string as $input => $items){
$userscreen_name = $items['user']['screen_name'];
$text = $items['text'];
$created_at = $items['created_at'];
$id_str = $items['id_str'];
$followers_count = $items['user']['followers_count'];

echo "Screen name:$userscreen_name<br />";
echo "Tweet: $text<br />";
echo "Time and Date of Tweet: $created_at<br />";
echo "Tweet ID: $id_str<br />";
echo "Followers: $followers_count<br />";

};
?>
</code>```

答:
This works fine when I test it :</p>

```<code>require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'consumer_key' => "xxx",
'consumer_secret' => "xxx",
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "xxx"
); /* don't forget to add your params ^^ */

$url = "https://api.twitter.com/1.1/search/tweets.json";

$requestMethod = "GET";

$getfield = '?q=kamerwatch&count=3'; /* added only 3 results for testing purpose */
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
         ->buildOauth($url, $requestMethod)
         ->performRequest();

$string = json_decode($response, true);
print_r($string); /* outputs the response */
/* below is the code to fetch through the array */
/* please note that your response array starts with -> Array ( [statuses] => Array ( [0] */
/* so we need to specify : $string['statuses'] to access the fields */
foreach($string['statuses'] as $items) {

$datecreate = $items['created_at'];
$id = $items['id'];
$twit = $items['text'];

echo "ID: $id<br />";
echo "Created: $datecreate<br />";
echo "Tweet: $twit<br />";

}
</code>```

Title: twitter api response array

Body:
I've a (i hope small) porblem. I'm building a twitter bot with TwitterAPIExchange.php, but if I run the script the hole time I only see arrayon my screen. what do I wrong? here is my twitter.php code:

    <?php

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'consumer_key' => "xxx",
'consumer_secret' => "xxx",
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "xxx"
);
$url = "https://api.twitter.com/1.1/search/tweets.json";

 $requestMethod = "GET";

$getfield = '?q=kamerwatch';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(), true);
if($string["errors"][0]["message"] != "") {echo "
Sorry, there was a             problem.

Twitter returned the following error message:

                         ".$string[errors][0]["message"]."
";exit();}

echo $string;
foreach($string as $items)
{
echo "Screen name: ". $items['user']['screen_name']."
";
echo "Tweet: ". $items['text']."
";
echo "Time and Date of Tweet: ".$items['created_at']."
";
echo "Tweet ID: ".$items['id_str']."
";
echo "Followers: ". $items['user']['followers_count']."

";
}
?>

code at the moment:

<?php

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'consumer_key' => "xxx",
'consumer_secret' =>  "xxx",
'oauth_access_token' => "xxxx",
'oauth_access_token_secret' => "xxx"
);
$url = "https://api.twitter.com/1.1/search/tweets.json";

$requestMethod = "GET";

$getfield = '?q=kamerwatch&count=3'; /* added only 3 results for testing     purpose */
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
     ->buildOauth($url, $requestMethod)
     ->performRequest();

$string = json_decode($response, true);
#print_r($string); /* outputs what follows */

foreach ($string as $input => $items){
$userscreen_name = $items['user']['screen_name'];
$text = $items['text'];
$created_at = $items['created_at'];
$id_str = $items['id_str'];
$followers_count = $items['user']['followers_count'];

echo "Screen name:$userscreen_name
";
echo "Tweet: $text
";
echo "Time and Date of Tweet: $created_at
";
echo "Tweet ID: $id_str
";
echo "Followers: $followers_count
";

};
?>

Body:
This works fine when I test it :

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'consumer_key' => "xxx",
'consumer_secret' => "xxx",
'oauth_access_token' => "xxx",
'oauth_access_token_secret' => "xxx"
); /* don't forget to add your params ^^ */

$url = "https://api.twitter.com/1.1/search/tweets.json";

$requestMethod = "GET";

$getfield = '?q=kamerwatch&count=3'; /* added only 3 results for testing purpose */
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
         ->buildOauth($url, $requestMethod)
         ->performRequest();

$string = json_decode($response, true);
print_r($string); /* outputs the response */
/* below is the code to fetch through the array */
/* please note that your response array starts with -> Array ( [statuses] => Array ( [0] */
/* so we need to specify : $string['statuses'] to access the fields */
foreach($string['statuses'] as $items) {

$datecreate = $items['created_at'];
$id = $items['id'];
$twit = $items['text'];

echo "ID: $id<br />";
echo "Created: $datecreate<br />";
echo "Tweet: $twit<br />";

}


问:
Depoying Jekyll themes on github pages - how to get github to treat repo as jekyll site?
So, I recently purchased a domain on godaddy and I'm trying to get a simple blog-like static site up and running. I tested it out using a 'jekyll now' theme and they both connected! However, the file structure seems a bit different to regular jekyll (it doesn't even have _posts folder- meaning, I have to write my content in the index.html). So now, I'm trying to get it up using regular jekyll (this theme to be specific: http://thephuse.github.io/strange_case/). I downloaded the repo on my machine and yes it does work locally. But when I upload those files from my desktop into a new github repo (named: .github.io) and access the site using https://.github.io, the front page displays but without the formatting or images etc. It also isn't able to open any of the links to the posts- simply displays a 404. I think this means that github is rendering it as a regular html file and not able to make out that this a jekyll theme or maybe something along those lines- but I'm not able to figure out what the issue is and how to resolve it - so I can have the theme up and running as well as connected to my custom domain (which I manage on godaddy btw).

Looking for some senior/experienced guys to throw some light on this issue?

Thanks, appreciate all inputs

答:
Make sure you are deploying it through bundle and you have the github-pages gem.

The following steps should be enough to fix you problem:

gem install bundle

gem update

Create file named Gemfile containing:

```<code>source 'https://rubygems.org'
gem 'github-pages'
</code>```

bundle install will now install the specified gem.

bundle exec jekyll serve --watch will show you exactly how the site would look on GitHub-Pages, but locally.

Hope this helps!

For some additional details, you could look at this great answer by VirtuaCreative, where she explains how you could also add any additional gems, you have used.

Body:
Make sure you are deploying it through bundle and you have the github-pages gem.

The following steps should be enough to fix you problem:

gem install bundle

gem update

Create file named Gemfile containing:

source 'https://rubygems.org'
gem 'github-pages'

bundle install will now install the specified gem.

bundle exec jekyll serve --watch will show you exactly how the site would look on GitHub-Pages, but locally.

Hope this helps!

For some additional details, you could look at this great answer by VirtuaCreative, where she explains how you could also add any additional gems, you have used.


问:
this and protoype javascript
Why does  alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?</p>

```<code>function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototype = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);
</code>```

答:
I think the drawing in http://mckoss.com/jscript/object.htm describes it (I can never remember this myself). There's a property __proto__ in Firefox that references the prototype, but other than that, going from an instance to prototype isn't done (except checking with instanceof).

Image is borrowed from above mentioned URL.

Title: this and protoype javascript

Body:
Why does  alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?

function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototype = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);