问:
php - PDOException could not find driver
I get PDOException could not find driver when connecting to mysql database with

```<code>$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
</code>```

on localhost on windows 10. I also tried replace localhost with 127.0.0.1.

phpinfo():

C:\php\php.ini:

```<code>extension_dir = "C:/php/ext"
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_fileinfo.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_gmp.dll
;extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_ldap.dll
;extension=php_mbstring.dll
;extension=php_exif.dll
extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_oci8_12c.dll
;extension=php_openssl.dll
;extension=php_pdo.dll
;extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
;extension=php_pdo_sqlite.dll
;extension=php_pgsql.dll
;extension=php_shmop.dll
</code>```

C:\Apache24\conf\httpd.conf:

```<code>LoadModule php5_module "C:/php/php5apache2_4.dll"
AddHandler application/x-httpd-php .php
PHPIniDir "C:/php"
</code>```

php -m

```<code>[PHP Modules]
bcmath
calendar
Core
ctype
date
dom
ereg
filter
ftp
hash
iconv
json
libxml
mcrypt
mhash
mysql
mysqli
mysqlnd
odbc
pcre
PDO
pdo_mysql
Phar
Reflection
session
SimpleXML
SPL
standard
tokenizer
wddx
xml
xmlreader
xmlwriter
zip
zlib

[Zend Modules]
</code>```

C:\php\ext content:

```<code>25.10.2017  15:23            79 872 php_bz2.dll
25.10.2017  15:23            87 040 php_com_dotnet.dll
25.10.2017  15:23           478 208 php_curl.dll
25.10.2017  15:23            23 040 php_enchant.dll
25.10.2017  15:23            56 320 php_exif.dll
25.10.2017  15:23         2 874 880 php_fileinfo.dll
25.10.2017  15:23         1 504 768 php_gd2.dll
25.10.2017  15:23            48 128 php_gettext.dll
25.10.2017  15:23           359 936 php_gmp.dll
25.10.2017  15:23           911 360 php_imap.dll
25.10.2017  15:23            80 896 php_interbase.dll
25.10.2017  15:23           326 656 php_intl.dll
25.10.2017  15:23           218 624 php_ldap.dll
25.10.2017  15:23         1 413 632 php_mbstring.dll
25.10.2017  15:23            45 056 php_mysql.dll
25.10.2017  15:23           113 664 php_mysqli.dll
25.10.2017  15:23           147 456 php_oci8_12c.dll
25.10.2017  15:23           158 208 php_opcache.dll
25.10.2017  15:23           105 472 php_openssl.dll
25.10.2017  15:23            24 576 php_pdo_firebird.dll
25.10.2017  15:23            28 672 php_pdo_mysql.dll
25.10.2017  15:23            28 672 php_pdo_oci.dll
25.10.2017  15:23            24 576 php_pdo_odbc.dll
25.10.2017  15:23            39 936 php_pdo_pgsql.dll
25.10.2017  15:23           603 648 php_pdo_sqlite.dll
25.10.2017  15:23           117 760 php_pgsql.dll
25.10.2017  15:23            14 336 php_shmop.dll
25.10.2017  15:23           406 528 php_snmp.dll
25.10.2017  15:23           285 184 php_soap.dll
25.10.2017  15:23            68 608 php_sockets.dll
25.10.2017  15:23           761 856 php_sqlite3.dll
25.10.2017  15:23            38 912 php_sybase_ct.dll
25.10.2017  15:23           284 160 php_tidy.dll
25.10.2017  15:23            63 488 php_xmlrpc.dll
25.10.2017  15:23           285 696 php_xsl.dll
</code>```

System Path:

```<code>C:\php
C:\php\ext
C:\Apache24
C:\Apache24/bin
</code>```

Do I need any more drivers? Or is there any other problem?

If you need any more info I will provide it.

Thank you for any suggestions

答:
Remove the ; from before the ;extension=php_pdo.dll. And also from before other pdo extensions. If you want to use those. And then restart the server.

The ; actually comments a line in ini files. So, you have to un-comment those lines to use them.

Edit: Instead of going through all of this trouble, you can instead use Xampp or Wamp or EasyPHP or something.

Body:
I get PDOException could not find driver when connecting to mysql database with

$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);

on localhost on windows 10. I also tried replace localhost with 127.0.0.1.

phpinfo():

C:\php\php.ini:

extension_dir = "C:/php/ext"
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_fileinfo.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_gmp.dll
;extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_ldap.dll
;extension=php_mbstring.dll
;extension=php_exif.dll
extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_oci8_12c.dll
;extension=php_openssl.dll
;extension=php_pdo.dll
;extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
;extension=php_pdo_sqlite.dll
;extension=php_pgsql.dll
;extension=php_shmop.dll

C:\Apache24\conf\httpd.conf:

LoadModule php5_module "C:/php/php5apache2_4.dll"
AddHandler application/x-httpd-php .php
PHPIniDir "C:/php"

php -m

[PHP Modules]
bcmath
calendar
Core
ctype
date
dom
ereg
filter
ftp
hash
iconv
json
libxml
mcrypt
mhash
mysql
mysqli
mysqlnd
odbc
pcre
PDO
pdo_mysql
Phar
Reflection
session
SimpleXML
SPL
standard
tokenizer
wddx
xml
xmlreader
xmlwriter
zip
zlib

[Zend Modules]

C:\php\ext content:

25.10.2017  15:23            79 872 php_bz2.dll
25.10.2017  15:23            87 040 php_com_dotnet.dll
25.10.2017  15:23           478 208 php_curl.dll
25.10.2017  15:23            23 040 php_enchant.dll
25.10.2017  15:23            56 320 php_exif.dll
25.10.2017  15:23         2 874 880 php_fileinfo.dll
25.10.2017  15:23         1 504 768 php_gd2.dll
25.10.2017  15:23            48 128 php_gettext.dll
25.10.2017  15:23           359 936 php_gmp.dll
25.10.2017  15:23           911 360 php_imap.dll
25.10.2017  15:23            80 896 php_interbase.dll
25.10.2017  15:23           326 656 php_intl.dll
25.10.2017  15:23           218 624 php_ldap.dll
25.10.2017  15:23         1 413 632 php_mbstring.dll
25.10.2017  15:23            45 056 php_mysql.dll
25.10.2017  15:23           113 664 php_mysqli.dll
25.10.2017  15:23           147 456 php_oci8_12c.dll
25.10.2017  15:23           158 208 php_opcache.dll
25.10.2017  15:23           105 472 php_openssl.dll
25.10.2017  15:23            24 576 php_pdo_firebird.dll
25.10.2017  15:23            28 672 php_pdo_mysql.dll
25.10.2017  15:23            28 672 php_pdo_oci.dll
25.10.2017  15:23            24 576 php_pdo_odbc.dll
25.10.2017  15:23            39 936 php_pdo_pgsql.dll
25.10.2017  15:23           603 648 php_pdo_sqlite.dll
25.10.2017  15:23           117 760 php_pgsql.dll
25.10.2017  15:23            14 336 php_shmop.dll
25.10.2017  15:23           406 528 php_snmp.dll
25.10.2017  15:23           285 184 php_soap.dll
25.10.2017  15:23            68 608 php_sockets.dll
25.10.2017  15:23           761 856 php_sqlite3.dll
25.10.2017  15:23            38 912 php_sybase_ct.dll
25.10.2017  15:23           284 160 php_tidy.dll
25.10.2017  15:23            63 488 php_xmlrpc.dll
25.10.2017  15:23           285 696 php_xsl.dll

System Path:

C:\php
C:\php\ext
C:\Apache24
C:\Apache24/bin

Do I need any more drivers? Or is there any other problem?

If you need any more info I will provide it.

Thank you for any suggestions


来源: stackexchange

问:
jQuery / Dojo - How do I use jQuery with Dojo toolkit
How do I use jQuery with Dojo toolkit? I've heard of both libraries being used simultaneously, jQuery for DOM-related and Dojo for UI (dijit), but I can't find any tutorials or examples of this.  Will I run into any conflicts or issues if I load both libraries?</p>

答:
jQuery supports AMD for quite a while now.

You can use the "paths" property of your ADM config to tell your AMD loader where to find jQuery :

```<code>var amdconfig = {
  baseUrl: __AMD_CONFIG_BASE_URL__,
  packages: [
    {name: "dojo", location: "./lib/dojo"},
    {name: "app", location: "./app"}
  ],
  paths: {
    jquery: "./lib/jquery/jquery-1.12.4"
  }
};
</code>```

Then, you can import jQuery into your ADM modules the same way you import any other AMD module, and use it alongside your Dojo modules:

```<code>define([
  "dojo/dom",
  "jquery"
], function(
  dom,
  $
) {

  ...

});
</code>```

Note

You can use the same config for AMD projects that use RequireJS instead of Dojo :

```<code>if (require.config) {
  // RequireJS
  require.config(amdconfig);
} else {
  // Dojo
  require(amdconfig);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
jQuery supports AMD for quite a while now.

You can use the "paths" property of your ADM config to tell your AMD loader where to find jQuery :

var amdconfig = {
  baseUrl: __AMD_CONFIG_BASE_URL__,
  packages: [
    {name: "dojo", location: "./lib/dojo"},
    {name: "app", location: "./app"}
  ],
  paths: {
    jquery: "./lib/jquery/jquery-1.12.4"
  }
};

Then, you can import jQuery into your ADM modules the same way you import any other AMD module, and use it alongside your Dojo modules:

define([
  "dojo/dom",
  "jquery"
], function(
  dom,
  $
) {

  ...

});

Note

You can use the same config for AMD projects that use RequireJS instead of Dojo :

if (require.config) {
  // RequireJS
  require.config(amdconfig);
} else {
  // Dojo
  require(amdconfig);
}

ContentLicense: CC BY-SA 3.0


问:
how to log the response and request in API Management
how to log the response size ,request size, error message from API management instance?
If yes then how can I fetch the data from it.</p>

答:
There is an inbuilt "log-to-event-hub" policy that you can use to send basically any information that exists on the context object (meaning the request/response + a bit more) to an event hub. From there you can use any regular method for processing the events

How to log events to Azure Event Hubs in Azure API Management.


问:
How to set a window height is maximize in qooxdoo?
I want to set window height is the full size of my parent component but not possible to set the full size of height.Thank in advance.
    The following code is a sample snippet of our requirement.</p>

```<code>var win = new qx.ui.window.Window("First Window");
win.setAllowMaximize(true)
win.setWidth(300);
//We want to set full height window
win.setBackgroundColor("green");

this.getRoot().add(win, {left:20, top:20});
win.open();
</code>```

答:
Setting the height depends upon the layout. Using the playground, as it appears you did for this example, the default layout is Canvas, where distances from individual edges can be specified. To accomplish what you're looking for with the Canvas layout, your example would be modified like this:

```<code>var win = new qx.ui.window.Window("First Window");
win.setAllowMaximize(true)
win.setWidth(300);
win.setBackgroundColor("green");

this.getRoot().add(win, {left:20, top:0, bottom:0});
win.open();
</code>```

Alternatively, and likely what you need for your real application, you have a Vertical Box Layout in which to place the window. In that case, you would use the flex layout capability to have this widget take up a proportional amount of space in the container (in this case, it'll use the full height of the container):

```<code>// Use a vertical box layout instead of the default canvas layout
this.getRoot().setLayout(new qx.ui.layout.VBox());

// Create a window
var win = new qx.ui.window.Window("First Window");
win.setMaxWidth(200);
win.setShowMinimize(false);

// Add the window to the root with flex so that it takes up available space
this.getRoot().add(win, {flex : 1});
win.open();
</code>```

Derrell

Body:
I want to set window height is the full size of my parent component but not possible to set the full size of height.Thank in advance.
    The following code is a sample snippet of our requirement.

var win = new qx.ui.window.Window("First Window");
win.setAllowMaximize(true)
win.setWidth(300);
//We want to set full height window
win.setBackgroundColor("green");

this.getRoot().add(win, {left:20, top:20});
win.open();

Body:
Setting the height depends upon the layout. Using the playground, as it appears you did for this example, the default layout is Canvas, where distances from individual edges can be specified. To accomplish what you're looking for with the Canvas layout, your example would be modified like this:

var win = new qx.ui.window.Window("First Window");
win.setAllowMaximize(true)
win.setWidth(300);
win.setBackgroundColor("green");

this.getRoot().add(win, {left:20, top:0, bottom:0});
win.open();

Alternatively, and likely what you need for your real application, you have a Vertical Box Layout in which to place the window. In that case, you would use the flex layout capability to have this widget take up a proportional amount of space in the container (in this case, it'll use the full height of the container):

// Use a vertical box layout instead of the default canvas layout
this.getRoot().setLayout(new qx.ui.layout.VBox());

// Create a window
var win = new qx.ui.window.Window("First Window");
win.setMaxWidth(200);
win.setShowMinimize(false);

// Add the window to the root with flex so that it takes up available space
this.getRoot().add(win, {flex : 1});
win.open();

Derrell


问:
Print line if line starts with any letter of the alphabet
I'm trying to print all of my reptile subspecies in my python program. I have a text file with a bunch of subspecies and their DNA sequence IDs. I just want to create a dictionary of subspecies (keys) and their respective DNA sequence IDs (values). But to do that I need to first learn how to separate the two.

So I want to print all of the subspecies names only, and to ignore the sequence IDs.

So far I have

```<code>import re
file = open('repCleanSubs2.txt')
for line in file:
    if line.startswith('[a-zA-Z]'):
        print line
</code>```

I believe the compiler takes the '[a-zA-Z]'as a string literal, rather than a search for any letter of the alphabet regardless the case sensitivity, which is what I want.

Is there some syntax that I'm missing in my if statement?

Thanks!

答:
It can be done without regular expression

```<code>data = open('repCleanSubs2.txt').read().splitlines() ## Read file and extract data as list

print [i for i in data if i[0].isalpha()]
</code>```

Body:
I'm trying to print all of my reptile subspecies in my python program. I have a text file with a bunch of subspecies and their DNA sequence IDs. I just want to create a dictionary of subspecies (keys) and their respective DNA sequence IDs (values). But to do that I need to first learn how to separate the two.

So I want to print all of the subspecies names only, and to ignore the sequence IDs.

So far I have

import re
file = open('repCleanSubs2.txt')
for line in file:
    if line.startswith('[a-zA-Z]'):
        print line

I believe the compiler takes the '[a-zA-Z]'as a string literal, rather than a search for any letter of the alphabet regardless the case sensitivity, which is what I want.

Is there some syntax that I'm missing in my if statement?

Thanks!

Body:
It can be done without regular expression

data = open('repCleanSubs2.txt').read().splitlines() ## Read file and extract data as list

print [i for i in data if i[0].isalpha()]


问:
Ansible - Filter a dict with a list of keys
I have a list which is actually a list of keys of a dict. And I want to get a concatenated string with the dict filtered on this list of keys and use it in a module option.

My use case here is users that have a list of public keys's name to generate an authorized_keys file.

```<code> 1 ---
 2 - hosts: localhost
 3   become: false
 4   vars:
 5     pub_keys:
 6       key01: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[…]5/ someuser@somehost
 7       key02: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[…]ea otheruser@somewher
 8       key03: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[…]dN anyser@anyhost
 9     users:
10       root:
11         home: /root
12         shell: /bin/bash
13         authorized_keys:
14           - key01
15       mgmtusr:
16         home: /home/mgmtusr
17         shell: /bin/bash
18         authorized_keys:
19           - key01
20           - key02
21           - key03
22
23   tasks:
24     - name: Debug Authorized Keys
25       debug:
26         msg: "USER:{{ item.key }} AUTHKEYSLIST:{{ pub_keys|selectattr(item.authorized_keys) }}"
27       with_dict: "{{ users }}"
28
29     - name: Manage users Authorized Keys
30       authorized_key:
31         user: "{{ item.key }}"
32         key: "{{ pub_keys|selectattr(item.authorized_keys) }}"
33         exclusive: yes
34       with_dict: "{{ users }}"
35
</code>```

As you can see here, I give it a try with dict|selectattr(list) but it fails.

Getting <generator object select_or_reject at 0x…> in the debug module and of course an invalid key specified in the authorized_key module.

```
TASK [Debug Authorized Keys] **************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => (item={'key': u'mgmtusr', 'value': {u'home': u'/home/mgmtusr', u'shell': u'/bin/bash', u'authorized_keys': [u'key01', u'key02', u'key03']}}) => {
    "item": {
        "key": "mgmtusr",
        "value": {
            "authorized_keys": [
                "key01",
                "key02",
                "key03"
            ],
            "home": "/home/mgmtusr",
            "shell": "/bin/bash"
        }
    },
    "msg": "USER:mgmtusr AUTHKEYSLIST:"
}
ok: [localhost] => (item={'key': u'root', 'value': {u'home': u'/root', u'shell': u'/bin/bash', u'authorized_keys': [u'key01']}}) => {
    "item": {
        "key": "root",
        "value": {
            "authorized_keys": [
                "key01"
            ],
            "home": "/root",
            "shell": "/bin/bash"
        }
    },
    "msg": "USER:root AUTHKEYSLIST:"
}

TASK [Manage users Authorized Keys] *******************************************************************************************************************************************************************************************************************************************
failed: [localhost] (item={'key': u'mgmtusr', 'value': {u'home': u'/home/mgmtusr', u'shell': u'/bin/bash', u'authorized_keys': [u'key01', u'key02', u'key03']}}) => {"changed": false, "failed": true, "item": {"key": "mgmtusr", "value": {"authorized_keys": ["key01", "key02", "key03"], "home": "/home/mgmtusr", "shell": "/bin/bash"}}, "msg": "Failed to lookup user mgmtusr: 'getpwnam(): name not found: mgmtusr'"}
failed: [localhost] (item={'key': u'root', 'value': {u'home': u'/root', u'shell': u'/bin/bash', u'authorized_keys': [u'key01']}}) => {"changed": false, "failed": true, "item": {"key": "root", "value": {"authorized_keys": ["key01"], "home": "/root", "shell": "/bin/bash"}}, "msg": "invalid key specified: "}
```

Like other tries (with_subelements, lookup('template', …) selectattr does not seems the solution.
Any proposition?

答:
Here you go:

```<code>- name: Manage users Authorized Keys
  authorized_key:
    user: "{{ item.key }}"
    key: "{{ item.value.authorized_keys | map('extract',pub_keys) | list | join('\n') }}"
    exclusive: yes
  with_dict: "{{ users }}"
</code>```

See extract filter usage.

Also when you use map you should almost always typecast it to list to prevent generator object value.

Body:
I have a list which is actually a list of keys of a dict. And I want to get a concatenated string with the dict filtered on this list of keys and use it in a module option.

My use case here is users that have a list of public keys's name to generate an authorized_keys file.

 1 ---
 2 - hosts: localhost
 3   become: false
 4   vars:
 5     pub_keys:
 6       key01: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[…]5/ someuser@somehost
 7       key02: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[…]ea otheruser@somewher
 8       key03: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ[…]dN anyser@anyhost
 9     users:
10       root:
11         home: /root
12         shell: /bin/bash
13         authorized_keys:
14           - key01
15       mgmtusr:
16         home: /home/mgmtusr
17         shell: /bin/bash
18         authorized_keys:
19           - key01
20           - key02
21           - key03
22
23   tasks:
24     - name: Debug Authorized Keys
25       debug:
26         msg: "USER:{{ item.key }} AUTHKEYSLIST:{{ pub_keys|selectattr(item.authorized_keys) }}"
27       with_dict: "{{ users }}"
28
29     - name: Manage users Authorized Keys
30       authorized_key:
31         user: "{{ item.key }}"
32         key: "{{ pub_keys|selectattr(item.authorized_keys) }}"
33         exclusive: yes
34       with_dict: "{{ users }}"
35

As you can see here, I give it a try with dict|selectattr(list) but it fails.

Getting <generator object select_or_reject at 0x…> in the debug module and of course an invalid key specified in the authorized_key module.

TASK [Debug Authorized Keys] **************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => (item={'key': u'mgmtusr', 'value': {u'home': u'/home/mgmtusr', u'shell': u'/bin/bash', u'authorized_keys': [u'key01', u'key02', u'key03']}}) => {
    "item": {
        "key": "mgmtusr",
        "value": {
            "authorized_keys": [
                "key01",
                "key02",
                "key03"
            ],
            "home": "/home/mgmtusr",
            "shell": "/bin/bash"
        }
    },
    "msg": "USER:mgmtusr AUTHKEYSLIST:"
}
ok: [localhost] => (item={'key': u'root', 'value': {u'home': u'/root', u'shell': u'/bin/bash', u'authorized_keys': [u'key01']}}) => {
    "item": {
        "key": "root",
        "value": {
            "authorized_keys": [
                "key01"
            ],
            "home": "/root",
            "shell": "/bin/bash"
        }
    },
    "msg": "USER:root AUTHKEYSLIST:"
}

TASK [Manage users Authorized Keys] *******************************************************************************************************************************************************************************************************************************************
failed: [localhost] (item={'key': u'mgmtusr', 'value': {u'home': u'/home/mgmtusr', u'shell': u'/bin/bash', u'authorized_keys': [u'key01', u'key02', u'key03']}}) => {"changed": false, "failed": true, "item": {"key": "mgmtusr", "value": {"authorized_keys": ["key01", "key02", "key03"], "home": "/home/mgmtusr", "shell": "/bin/bash"}}, "msg": "Failed to lookup user mgmtusr: 'getpwnam(): name not found: mgmtusr'"}
failed: [localhost] (item={'key': u'root', 'value': {u'home': u'/root', u'shell': u'/bin/bash', u'authorized_keys': [u'key01']}}) => {"changed": false, "failed": true, "item": {"key": "root", "value": {"authorized_keys": ["key01"], "home": "/root", "shell": "/bin/bash"}}, "msg": "invalid key specified: "}

Like other tries (with_subelements, lookup('template', …) selectattr does not seems the solution.
Any proposition?

Body:
Here you go:

- name: Manage users Authorized Keys
  authorized_key:
    user: "{{ item.key }}"
    key: "{{ item.value.authorized_keys | map('extract',pub_keys) | list | join('\n') }}"
    exclusive: yes
  with_dict: "{{ users }}"

See extract filter usage.

Also when you use map you should almost always typecast it to list to prevent generator object value.


问:
rerender rich:dataTable
I am having trouble re-rendering a rich:dataTable

My bean has list of strings, when I modify the list I want to re-render the table

I tried

```<code><a4j:commandButton value="Add" action="#{bean.add}" reRender="table">
</a4j:commandButton>
</code>```

In the been list I have the element but the rich:datatable with the id table doesn't rerender

I am using richfaces 4

答:
Try to put your data table in an a4j:outputPanel and re-render the output panel instead:

```<code><a4j:outputPanel id="tablePanel">
    <rich:dataTable ... >
    ..
    </rich:dataTable>
</a4j:outputPanel>
</code>```

OutputPanel must be visible on first page load (rendered=true). You can not re-render elements which are not rendered on first page load.

Title: rerender rich:dataTable

Body:
I am having trouble re-rendering a rich:dataTable

My bean has list of strings, when I modify the list I want to re-render the table

I tried

<a4j:commandButton value="Add" action="#{bean.add}" reRender="table">
</a4j:commandButton>

In the been list I have the element but the rich:datatable with the id table doesn't rerender

I am using richfaces 4

Body:
Try to put your data table in an a4j:outputPanel and re-render the output panel instead:

<a4j:outputPanel id="tablePanel">
    <rich:dataTable ... >
    ..
    </rich:dataTable>
</a4j:outputPanel>

OutputPanel must be visible on first page load (rendered=true). You can not re-render elements which are not rendered on first page load.


问:
Loop program back to start point after it's finished
So I've created this program which manipulates a word that the user gives as input, by taking the moving the first character to the end of the word, spells the rest of the word backwards, then checks if the original word and the new word are the same. It's designed to run until the user enters the word "quit" as the chosen word. I've managed to get the majority of the code working, except, instead of looping back to ask the user for a new word after its checked the previous one, it just continues running forever. The code I've currently got is below:

```<code>package uploadTask9_wordPlay;

import java.util.Scanner;

public class wordPlay {

    public static void main(String[] args) {
        // creates scanner object to get a name from the user input
        Scanner userInput = new Scanner(System.in);

            System.out.println("Enter a name to be tested, or 'quit' to exit
program: ");
            // stores the user input into string testedName
            String testedName = userInput.nextLine();

            // if the user input is "quit", program exits
            if (testedName.equals("quit")) {
                System.out.println("Thanks for using the program");
                System.exit(0);
            }

            // else, do the rest of the code with the given word
            else {

                while (testedName != "quit") {

            // takes first character from userInput
            char firstLetter = testedName.charAt(0);

            // removes first character from testedName
            StringBuilder removeChar = new StringBuilder(testedName);
            removeChar.deleteCharAt(0);

            // adds first character of testedName to the end of removeChar
            String newString = removeChar.toString() + firstLetter;

            // prints newString backwards
            String reverseWord = new
StringBuffer(newString).reverse().toString();

            // if statement - far simpler way to carry this task out than loops
            // if statement to check if the words are the same
            if (testedName.equals(reverseWord)) {
                System.out.println(testedName + " is the same as " + reverseWord); }

            else {
                System.out.println(testedName + " is not the same as " + reverseWord); }

        }
    }
}
}
</code>```

Does anyone know why the program doesn't loop back to the start each time its checked a word?

答:
Don't compare Strings like this:

```<code>testedName != "quit"
</code>```

Do this:

```<code>!testedName.equals("quit")
</code>```

Body:
So I've created this program which manipulates a word that the user gives as input, by taking the moving the first character to the end of the word, spells the rest of the word backwards, then checks if the original word and the new word are the same. It's designed to run until the user enters the word "quit" as the chosen word. I've managed to get the majority of the code working, except, instead of looping back to ask the user for a new word after its checked the previous one, it just continues running forever. The code I've currently got is below:

package uploadTask9_wordPlay;

import java.util.Scanner;

public class wordPlay {

    public static void main(String[] args) {
        // creates scanner object to get a name from the user input
        Scanner userInput = new Scanner(System.in);

            System.out.println("Enter a name to be tested, or 'quit' to exit
program: ");
            // stores the user input into string testedName
            String testedName = userInput.nextLine();

            // if the user input is "quit", program exits
            if (testedName.equals("quit")) {
                System.out.println("Thanks for using the program");
                System.exit(0);
            }

            // else, do the rest of the code with the given word
            else {

                while (testedName != "quit") {

            // takes first character from userInput
            char firstLetter = testedName.charAt(0);

            // removes first character from testedName
            StringBuilder removeChar = new StringBuilder(testedName);
            removeChar.deleteCharAt(0);

            // adds first character of testedName to the end of removeChar
            String newString = removeChar.toString() + firstLetter;

            // prints newString backwards
            String reverseWord = new
StringBuffer(newString).reverse().toString();

            // if statement - far simpler way to carry this task out than loops
            // if statement to check if the words are the same
            if (testedName.equals(reverseWord)) {
                System.out.println(testedName + " is the same as " + reverseWord); }

            else {
                System.out.println(testedName + " is not the same as " + reverseWord); }

        }
    }
}
}

Does anyone know why the program doesn't loop back to the start each time its checked a word?

Body:
Don't compare Strings like this:

testedName != "quit"

Do this:

!testedName.equals("quit")


问:
how to change cell values in datagridview according to a cell
I have a datagridView in which there are predefined columns. Suppose there are four columns,let's say A,B,C and D. Column A is for quantity and Column B is for rate and Column C is for discount and Column D is for total.I need a textchanged event like thing for when i enter in Column C the value in Column D should automatically change according to calculation as D=A*B-C. So please advice me how to achieve this. Thank You.

```<code>private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex > -1)
{
    dataGridView1.Rows[e.RowIndex].Cells[14].Value =
    ((Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells[3].Value)) * (Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells[7].Value))
    - Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells[13].Value));/*taxable*/
}
</code>```

答:
If you want to change grid when some cell changed value, you can use CellEndEdit Event

like here:

```<code>private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        int editedRow = e.RowIndex;
        int editedColumn = e.ColumnIndex;

        int sum = 0;
        for (int i=0;i< dataGridView1.Columns.Count-1 ;i++)
            sum += dataGridView1[i, e.RowIndex];

        dataGridView1[dataGridView1.Columns.Count-1, editedRow] = sum;
    }
</code>```

Body:
I have a datagridView in which there are predefined columns. Suppose there are four columns,let's say A,B,C and D. Column A is for quantity and Column B is for rate and Column C is for discount and Column D is for total.I need a textchanged event like thing for when i enter in Column C the value in Column D should automatically change according to calculation as D=A*B-C. So please advice me how to achieve this. Thank You.

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex > -1)
{
    dataGridView1.Rows[e.RowIndex].Cells[14].Value =
    ((Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells[3].Value)) * (Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells[7].Value))
    - Convert.ToDecimal(dataGridView1.Rows[e.RowIndex].Cells[13].Value));/*taxable*/
}

Body:
If you want to change grid when some cell changed value, you can use CellEndEdit Event

like here:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        int editedRow = e.RowIndex;
        int editedColumn = e.ColumnIndex;

        int sum = 0;
        for (int i=0;i< dataGridView1.Columns.Count-1 ;i++)
            sum += dataGridView1[i, e.RowIndex];

        dataGridView1[dataGridView1.Columns.Count-1, editedRow] = sum;
    }


问:
Pixel launcher keeps stopping, after updating SDK
After updating the SDK, I'm having this problem when I run the emulator:

Pixel launcher keeps stopping,

Please help me and thank you very much

Note: I use android studio 2.3.3

答:
Actually, anas darai's comment is the answer, but I'll expand it a bit.
The general workaround is the following:

Delete the AVD and the system image;

Download the system image;

Create a new AVD;

Start the Android Emulator;

4.a. Click on the More button (those 3 horizontal dots) in the Nav Controls (the bar next to the emulator);

4.b. Click on Settings;

4.c. Select from the OpenGL ES renderer dropdown the option ANGLE(D3D11);

4.d. Restart the Android Emulator.

Steps 1 to 3 are optional in most of the cases.

If it still isn't working, you should check the following:

does your CPU meet the requirements? solution: check out the Hardware requirements from Installation Instructions for HAXM;

does HAXM have enough RAM and heap space so it can run the AVD? solution: reinstall HAXM and use at least the recommended settings;

for slightly different solutions, check out Pixel launcher keeps stopping.


问:
How to write mapping for an array of array in elastic search?
I have a field which is a 3d array, and don't want ES to index it.

The problem is how to write its type in mapping? Should I use {index: false} or {enabled: false}?

答:
You can use enabled only at the mapping type level (i.e. for the whole type) or for object types.

Since you have an array, you simply need to use index: false instead.

The field can simply have a type text (+ keyword if you need exact matches) since the array will be flattened:

```<code>      "my_field": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }
</code>```

Body:
You can use enabled only at the mapping type level (i.e. for the whole type) or for object types.

Since you have an array, you simply need to use index: false instead.

The field can simply have a type text (+ keyword if you need exact matches) since the array will be flattened:

      "my_field": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      }


问:
how to validate an array in json response karate framework
In the example bellow if warehouse is an array, how I can validate a json response like in this example:

```<code>Scenario: using karate's simpler alternative to json-schema
* def warehouseLocation = { latitude: '#number', longitude: '#number' }
* def productStructure =
"""
{
 id: '#number',
 name: '#string',
 price: '#number? _ > 0',
 tags: '##[_ > 0] #string',
   dimensions: {
     length: '#number',
     width: '#number',
     height: '#number'
   },
 warehouseLocation: '##(warehouseLocation)'
}
"""
* def json = read('products.json')
* match json == '#[] productStructure'
</code>```

Where I have ti put #array.
I've tried different issues, but it doesn't work. Thanks

答:
Your question is asking for warehouse which I can't find at all in your example. I assume you are asking for this:

warehouseLocation: '#[] warehouseLocation'

Body:
In the example bellow if warehouse is an array, how I can validate a json response like in this example:

Scenario: using karate's simpler alternative to json-schema
* def warehouseLocation = { latitude: '#number', longitude: '#number' }
* def productStructure =
"""
{
 id: '#number',
 name: '#string',
 price: '#number? _ > 0',
 tags: '##[_ > 0] #string',
   dimensions: {
     length: '#number',
     width: '#number',
     height: '#number'
   },
 warehouseLocation: '##(warehouseLocation)'
}
"""
* def json = read('products.json')
* match json == '#[] productStructure'

Where I have ti put #array.
I've tried different issues, but it doesn't work. Thanks


问:
How to iterate through json object and form a new object with concatenated values using Javascript?
I have been working on  api which gives data in JSON object and i have no control with it at all. I need to pull data on select box. I have managed to populate it but it allows single value binding only. ie firstName or lastName or middleName and not both. Here is my current JSON Object:

```<code>.employeesList = [
  {
    id: 1,
    firstName: 'firstName',
    middleName: 'middleName',
    lastName: 'lastName',
  },
  {
    id: 2,
    firstName: 'firstName2',
    middleName: 'middleName2',
    lastName: 'lastName2',
  },
  {
    id: 3,
    firstName: 'firstName3',
    middleName: 'middleName3',
    lastName: 'lastName3',
  },
  {
    id: 4,
    firstName: 'firstName4',
    middleName: 'middleName4',
    lastName: 'lastName4',
  },
  {
    id: 5,
    firstName: 'firstName5',
    middleName: 'middleName5',
    lastName: 'lastName5',
  }
]
</code>```

I would like to merge firstName, middleName and lastName in each data and form a new JSON Object having only ids and fullNames like so:

```<code>.employeesList = [
  {
    id: 1,
    fullName: 'firstName MiddleName LastName'
  },
  {
    id: 2,
    fullName: 'firstName2 MiddleName2 LastName2'
  },
  {
    id: 3,
    fullName: 'firstName3 MiddleName3 LastName3'
  },
  {
    id: 4,
    fullName: 'firstName4 MiddleName4 LastName4'
  },
  {
    id: 5,
    fullName: 'firstName5 MiddleName5 LastName5'
  }
]
</code>```

How can i achieve that using Javascript?

答:
I use this code and work fine for me. (need JQuery).    </p>

```<code>var newEmployeesList = [];
$.each(employeesList, function(key, item) {

    var f_name = item.firstName;

    var m_name = item.middleName;

    var l_name = item.lastName;

    var obj = new Object();
    obj.id = key;
    obj.fullName = f_name + " " + m_name + " " + l_name;

    newEmployeesList.push(obj);

});
</code>```

Body:
I have been working on  api which gives data in JSON object and i have no control with it at all. I need to pull data on select box. I have managed to populate it but it allows single value binding only. ie firstName or lastName or middleName and not both. Here is my current JSON Object:

.employeesList = [
  {
    id: 1,
    firstName: 'firstName',
    middleName: 'middleName',
    lastName: 'lastName',
  },
  {
    id: 2,
    firstName: 'firstName2',
    middleName: 'middleName2',
    lastName: 'lastName2',
  },
  {
    id: 3,
    firstName: 'firstName3',
    middleName: 'middleName3',
    lastName: 'lastName3',
  },
  {
    id: 4,
    firstName: 'firstName4',
    middleName: 'middleName4',
    lastName: 'lastName4',
  },
  {
    id: 5,
    firstName: 'firstName5',
    middleName: 'middleName5',
    lastName: 'lastName5',
  }
]

I would like to merge firstName, middleName and lastName in each data and form a new JSON Object having only ids and fullNames like so:

.employeesList = [
  {
    id: 1,
    fullName: 'firstName MiddleName LastName'
  },
  {
    id: 2,
    fullName: 'firstName2 MiddleName2 LastName2'
  },
  {
    id: 3,
    fullName: 'firstName3 MiddleName3 LastName3'
  },
  {
    id: 4,
    fullName: 'firstName4 MiddleName4 LastName4'
  },
  {
    id: 5,
    fullName: 'firstName5 MiddleName5 LastName5'
  }
]

How can i achieve that using Javascript?

Body:
I use this code and work fine for me. (need JQuery).

var newEmployeesList = [];
$.each(employeesList, function(key, item) {

    var f_name = item.firstName;

    var m_name = item.middleName;

    var l_name = item.lastName;

    var obj = new Object();
    obj.id = key;
    obj.fullName = f_name + " " + m_name + " " + l_name;

    newEmployeesList.push(obj);

});


问:
How to change the attributes of the
```

<p>How can i change the value of <code>data-amount="100"</code> to my desired value</p>

<p>I tried like</p>

```document.getElementById("paymentWidget").attr("data-amount") = total
```

<p>But it is showing error like </p>

```document.getElementById(...).attr is not a function
```

How can i fix this and set values dynamically ?

答:
First include reference to the jquery library file.
Then rewrite the code as follows,</p>

```<code>  $('#paymentWidget').attr("data-amount",desired-value);
</code>```

Title: How to change the attributes of the <script> tag

Body:
Here is my script tag

How can i change the value of data-amount="100" to my desired value

I tried like

document.getElementById("paymentWidget").attr("data-amount") = total

But it is showing error like

document.getElementById(...).attr is not a function

How can i fix this and set values dynamically ?

Body:
First include reference to the jquery library file.
Then rewrite the code as follows,

  $('#paymentWidget').attr("data-amount",desired-value);


问:
Replace Index values with matched values in other dataframe
I have the following DataFrame:

df1:

```<code>   Index   ColA
     a      10
     b       9
     c      12
     d      13
</code>```

df2:

```<code>   Index  Letter  Names
     0      d     Waylon
     1      a     Marcus
     2      z     Eddie
     3      q     Justine
     4      c     Angela
     5      b     Joanna
</code>```

I want to make to replace the index values in df1 with the corresponding values in df2, so the result would look like:

df1:

```<code>   Index   ColA
   Marcus   10
   Joanna    9
   Angela   12
   Waylon   13
</code>```

Any ideas?

答:
You need rename by dictionary created by set_index with to_dict:

```<code>df1 = df1.rename(index=df1.set_index('Letter')['Names'].to_dict())
</code>```

Body:
I have the following DataFrame:

df1:

   Index   ColA
     a      10
     b       9
     c      12
     d      13

df2:

   Index  Letter  Names
     0      d     Waylon
     1      a     Marcus
     2      z     Eddie
     3      q     Justine
     4      c     Angela
     5      b     Joanna

I want to make to replace the index values in df1 with the corresponding values in df2, so the result would look like:

df1:

   Index   ColA
   Marcus   10
   Joanna    9
   Angela   12
   Waylon   13

Any ideas?

Body:
You need rename by dictionary created by set_index with to_dict:

df1 = df1.rename(index=df1.set_index('Letter')['Names'].to_dict())


问:
alert after php-formular has send
I have a E-Mail formular on my Webside. After the Mail is send i will give the user a feedback. How can i give the alert on my side with the formular?
Now I will be forwarded to sendMail.php with the alerttext writen on the page.

html-code (in index.html):

```<code><form ... action="sendMail.php">
   ...
</form>
</code>```

php-code (in sendMail.php):

```<code>$mail_senden = mail($empfaenger,$betreff,$msg,$header);

if($mail_senden){
  echo "nachricht1";
  exit();
} else{
  echo "nachricht2";
  exit();
}
</code>```

答:
You can send message back via $_GET. For example

```<code><form action="sendMail.php">
    ...
    <?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
</form>
</code>```

And in sendMail.php write

```<code>$mail_senden = mail($empfaenger,$betreff,$msg,$header);
$referer = $_SERVER['HTTP_REFERER'];

if($mail_senden){
    header("Location: $referer?message=nachricht1");
    exit();
} else {
    header("Location: $referer?message=nachricht2");
    exit();
}
</code>```

Title: alert after php-formular has send

Body:
I have a E-Mail formular on my Webside. After the Mail is send i will give the user a feedback. How can i give the alert on my side with the formular?
Now I will be forwarded to sendMail.php with the alerttext writen on the page.

html-code (in index.html):

<form ... action="sendMail.php">
   ...
</form>

php-code (in sendMail.php):

$mail_senden = mail($empfaenger,$betreff,$msg,$header);

if($mail_senden){
  echo "nachricht1";
  exit();
} else{
  echo "nachricht2";
  exit();
}

Body:
You can send message back via $_GET. For example

<form action="sendMail.php">
    ...
    <?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
</form>

And in sendMail.php write

$mail_senden = mail($empfaenger,$betreff,$msg,$header);
$referer = $_SERVER['HTTP_REFERER'];

if($mail_senden){
    header("Location: $referer?message=nachricht1");
    exit();
} else {
    header("Location: $referer?message=nachricht2");
    exit();
}


问:
Replace every two items in a list for a respective value in a dictionary
I used a program to convert an integer vector to binary, now I need to do the reverse operation, but I believe the logic I am using it's not correct.

```<code>population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]

def BinaryConversion2(population):
    binary_return = []
    binary_index = {(0,0): 0, (0,1): 1, (1,0): 2, (1,1): 3}
    for game in range (0, len(population)):
        converted = [s for num in population[game][0] for s in binary_index[num]]
        binary_return.append(converted)
    return (binary_return)
</code>```

I need to replace every two bits of the binary strings in brackets for the respective dictionary value, but I believe the problem here is that the program is indexing single bits, so it is not working properly.

Does anyone know how to reference every two items in the list for the dictionary respective values? Or anything else that might be useful in this case.

Thank you!

答:
```<code>for game in population:
    binary_return = [binary_index[(i,j)] for i,j in zip(game[0][0::2], game[0][1::2])]
</code>```

Body:
I used a program to convert an integer vector to binary, now I need to do the reverse operation, but I believe the logic I am using it's not correct.

population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [6], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [4], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [6], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [4], [3]]]

def BinaryConversion2(population):
    binary_return = []
    binary_index = {(0,0): 0, (0,1): 1, (1,0): 2, (1,1): 3}
    for game in range (0, len(population)):
        converted = [s for num in population[game][0] for s in binary_index[num]]
        binary_return.append(converted)
    return (binary_return)

I need to replace every two bits of the binary strings in brackets for the respective dictionary value, but I believe the problem here is that the program is indexing single bits, so it is not working properly.

Does anyone know how to reference every two items in the list for the dictionary respective values? Or anything else that might be useful in this case.

Thank you!


问:
Get iframe element of current CKEDITOR instance
CKEditor 4 or above

I have a CKEDITOR instance that I can access without problem parent.CKEDITOR.instances[instance_id]

I want to add bootstrap file to the head of the iframe generated by CKEDITOR (kind of hack, because normal way to add optional css file was not working).

I tried to get the iframe head and to inject the bootstrap file, but it fails always.

Any Suggestion?

答:
I found it finally, I post it here so maybe it will be helpful for someone in the future.

I just added the bootstrap file to the body tag (it is a bad practice but it works).


问:
Selecting rows from sql table having multiple values in the field
Here i  have a table 'tbllead' which is having column'leademployees' which contains the values such as

```<code>(450,449,451)- row1
(450,449,451)-row 2
(455,449,454,451)- row3
(450,449,451)-row 4
(450)-row5 )
</code>```

then how to get the rows if my query is

```<code>select *
from TblLead
where LeadEmployees=451
</code>```

The desired result should be...
row 25,26,27,28,29,31,32,33,34,35

答: It is very common scenerio where employee manage employees erds easily available.  May be this is helpfull

Body:
Here i  have a table 'tbllead' which is having column'leademployees' which contains the values such as

(450,449,451)- row1
(450,449,451)-row 2
(455,449,454,451)- row3
(450,449,451)-row 4
(450)-row5 )

then how to get the rows if my query is

select *
from TblLead
where LeadEmployees=451

The desired result should be...
row 25,26,27,28,29,31,32,33,34,35


问:
php - PDOException could not find driver
I get PDOException could not find driver when connecting to mysql database with

```<code>$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
</code>```

on localhost on windows 10. I also tried replace localhost with 127.0.0.1.

phpinfo():

C:\php\php.ini:

```<code>extension_dir = "C:/php/ext"
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_fileinfo.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_gmp.dll
;extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_ldap.dll
;extension=php_mbstring.dll
;extension=php_exif.dll
extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_oci8_12c.dll
;extension=php_openssl.dll
;extension=php_pdo.dll
;extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
;extension=php_pdo_sqlite.dll
;extension=php_pgsql.dll
;extension=php_shmop.dll
</code>```

C:\Apache24\conf\httpd.conf:

```<code>LoadModule php5_module "C:/php/php5apache2_4.dll"
AddHandler application/x-httpd-php .php
PHPIniDir "C:/php"
</code>```

php -m

```<code>[PHP Modules]
bcmath
calendar
Core
ctype
date
dom
ereg
filter
ftp
hash
iconv
json
libxml
mcrypt
mhash
mysql
mysqli
mysqlnd
odbc
pcre
PDO
pdo_mysql
Phar
Reflection
session
SimpleXML
SPL
standard
tokenizer
wddx
xml
xmlreader
xmlwriter
zip
zlib

[Zend Modules]
</code>```

C:\php\ext content:

```<code>25.10.2017  15:23            79 872 php_bz2.dll
25.10.2017  15:23            87 040 php_com_dotnet.dll
25.10.2017  15:23           478 208 php_curl.dll
25.10.2017  15:23            23 040 php_enchant.dll
25.10.2017  15:23            56 320 php_exif.dll
25.10.2017  15:23         2 874 880 php_fileinfo.dll
25.10.2017  15:23         1 504 768 php_gd2.dll
25.10.2017  15:23            48 128 php_gettext.dll
25.10.2017  15:23           359 936 php_gmp.dll
25.10.2017  15:23           911 360 php_imap.dll
25.10.2017  15:23            80 896 php_interbase.dll
25.10.2017  15:23           326 656 php_intl.dll
25.10.2017  15:23           218 624 php_ldap.dll
25.10.2017  15:23         1 413 632 php_mbstring.dll
25.10.2017  15:23            45 056 php_mysql.dll
25.10.2017  15:23           113 664 php_mysqli.dll
25.10.2017  15:23           147 456 php_oci8_12c.dll
25.10.2017  15:23           158 208 php_opcache.dll
25.10.2017  15:23           105 472 php_openssl.dll
25.10.2017  15:23            24 576 php_pdo_firebird.dll
25.10.2017  15:23            28 672 php_pdo_mysql.dll
25.10.2017  15:23            28 672 php_pdo_oci.dll
25.10.2017  15:23            24 576 php_pdo_odbc.dll
25.10.2017  15:23            39 936 php_pdo_pgsql.dll
25.10.2017  15:23           603 648 php_pdo_sqlite.dll
25.10.2017  15:23           117 760 php_pgsql.dll
25.10.2017  15:23            14 336 php_shmop.dll
25.10.2017  15:23           406 528 php_snmp.dll
25.10.2017  15:23           285 184 php_soap.dll
25.10.2017  15:23            68 608 php_sockets.dll
25.10.2017  15:23           761 856 php_sqlite3.dll
25.10.2017  15:23            38 912 php_sybase_ct.dll
25.10.2017  15:23           284 160 php_tidy.dll
25.10.2017  15:23            63 488 php_xmlrpc.dll
25.10.2017  15:23           285 696 php_xsl.dll
</code>```

System Path:

```<code>C:\php
C:\php\ext
C:\Apache24
C:\Apache24/bin
</code>```

Do I need any more drivers? Or is there any other problem?

If you need any more info I will provide it.

Thank you for any suggestions

答:
Please remove ; before ;extension=php_pdo.dll and restart the Apache server.

Here ; means commenting...so you need yo uncomment it by removing ;.

Body:
I get PDOException could not find driver when connecting to mysql database with

$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);

on localhost on windows 10. I also tried replace localhost with 127.0.0.1.

phpinfo():

C:\php\php.ini:

extension_dir = "C:/php/ext"
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_fileinfo.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_gmp.dll
;extension=php_intl.dll
;extension=php_imap.dll
;extension=php_interbase.dll
;extension=php_ldap.dll
;extension=php_mbstring.dll
;extension=php_exif.dll
extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_oci8_12c.dll
;extension=php_openssl.dll
;extension=php_pdo.dll
;extension=php_pdo_firebird.dll
extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
;extension=php_pdo_pgsql.dll
;extension=php_pdo_sqlite.dll
;extension=php_pgsql.dll
;extension=php_shmop.dll

C:\Apache24\conf\httpd.conf:

LoadModule php5_module "C:/php/php5apache2_4.dll"
AddHandler application/x-httpd-php .php
PHPIniDir "C:/php"

php -m

[PHP Modules]
bcmath
calendar
Core
ctype
date
dom
ereg
filter
ftp
hash
iconv
json
libxml
mcrypt
mhash
mysql
mysqli
mysqlnd
odbc
pcre
PDO
pdo_mysql
Phar
Reflection
session
SimpleXML
SPL
standard
tokenizer
wddx
xml
xmlreader
xmlwriter
zip
zlib

[Zend Modules]

C:\php\ext content:

25.10.2017  15:23            79 872 php_bz2.dll
25.10.2017  15:23            87 040 php_com_dotnet.dll
25.10.2017  15:23           478 208 php_curl.dll
25.10.2017  15:23            23 040 php_enchant.dll
25.10.2017  15:23            56 320 php_exif.dll
25.10.2017  15:23         2 874 880 php_fileinfo.dll
25.10.2017  15:23         1 504 768 php_gd2.dll
25.10.2017  15:23            48 128 php_gettext.dll
25.10.2017  15:23           359 936 php_gmp.dll
25.10.2017  15:23           911 360 php_imap.dll
25.10.2017  15:23            80 896 php_interbase.dll
25.10.2017  15:23           326 656 php_intl.dll
25.10.2017  15:23           218 624 php_ldap.dll
25.10.2017  15:23         1 413 632 php_mbstring.dll
25.10.2017  15:23            45 056 php_mysql.dll
25.10.2017  15:23           113 664 php_mysqli.dll
25.10.2017  15:23           147 456 php_oci8_12c.dll
25.10.2017  15:23           158 208 php_opcache.dll
25.10.2017  15:23           105 472 php_openssl.dll
25.10.2017  15:23            24 576 php_pdo_firebird.dll
25.10.2017  15:23            28 672 php_pdo_mysql.dll
25.10.2017  15:23            28 672 php_pdo_oci.dll
25.10.2017  15:23            24 576 php_pdo_odbc.dll
25.10.2017  15:23            39 936 php_pdo_pgsql.dll
25.10.2017  15:23           603 648 php_pdo_sqlite.dll
25.10.2017  15:23           117 760 php_pgsql.dll
25.10.2017  15:23            14 336 php_shmop.dll
25.10.2017  15:23           406 528 php_snmp.dll
25.10.2017  15:23           285 184 php_soap.dll
25.10.2017  15:23            68 608 php_sockets.dll
25.10.2017  15:23           761 856 php_sqlite3.dll
25.10.2017  15:23            38 912 php_sybase_ct.dll
25.10.2017  15:23           284 160 php_tidy.dll
25.10.2017  15:23            63 488 php_xmlrpc.dll
25.10.2017  15:23           285 696 php_xsl.dll

System Path:

C:\php
C:\php\ext
C:\Apache24
C:\Apache24/bin

Do I need any more drivers? Or is there any other problem?

If you need any more info I will provide it.

Thank you for any suggestions


问:
Optional monad and the Law of Demeter in Java
while I was reviewing some code, I came across this snippet.

```<code>List<User> users = /* Some code that initializes the list */;
users.stream()
     .filter(user -> user.getAddress().isPresent())
     .map(/* Some code */)
// And so on...
</code>```

The call of method user.getAddress() returns an Optional<Address>. Following the famous Law of Demeter (LoD), the above code is not clean. However, I cannot figure out how to refactor it to make it cleaner.

As a first attempt could be to add to the User class a method hasAddress(), but this method overcomes the need of having an Optional<Address>, IMO.

How should I refactor the above code? In this case, is it worth to satisfy the LoD?

EDIT: I missed specifying that in the map method I do not want to return the address.

答:
I believe you have already answered the question yourself.

You have two distinct use cases here:

Determine if the user has an address

Access the user address in a null-safe way

The first use case can be solved by adding the method hasAddress(), like you stated.
The second use case can be solved using the Optional to wrap the address. There is nothing wrong with that.

Body:
while I was reviewing some code, I came across this snippet.

List<User> users = /* Some code that initializes the list */;
users.stream()
     .filter(user -> user.getAddress().isPresent())
     .map(/* Some code */)
// And so on...

The call of method user.getAddress() returns an Optional<Address>. Following the famous Law of Demeter (LoD), the above code is not clean. However, I cannot figure out how to refactor it to make it cleaner.

As a first attempt could be to add to the User class a method hasAddress(), but this method overcomes the need of having an Optional<Address>, IMO.

How should I refactor the above code? In this case, is it worth to satisfy the LoD?

EDIT: I missed specifying that in the map method I do not want to return the address.


问:
My Application Is crashing when I'm using Daily repeating Alarm
I am trying to fire alarm everyday on fix time but my application is crashing when click the button to fire alarm.
Please help to find solution. Thanks in Advance .

Here is my Main Activity code :-

```<code>import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import java.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar calendar = Calendar.getInstance();

                calendar.set(Calendar.HOUR_OF_DAY,15);
                calendar.set(Calendar.MINUTE,9);
                calendar.set(Calendar.SECOND,20);

                Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

                alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

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

Here is my Notification_receiver.java file:-

```<code>import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

class Notification_receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent repeating_intent = new Intent(context,Repeating_activity.class);
        repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent .getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setSmallIcon(android.R.drawable.sym_def_app_icon)
                .setContentTitle("Notification Tittle")
                .setContentText("Notification Text")
                .setAutoCancel(true);

        notificationManager.notify(100,builder.build());
    }
}
</code>```

Here is Manifest if needed :-

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hacker.timernotification">

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> //I tried with and without this but still crashing my app
    <uses-permission android:name="android.permission.WAKE_LOCK"/> // this is at the time of fire alarm

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Repeating_activity"/>
        <receiver android:name=".Notification_receiver"></receiver>
            <!--android:enabled="true"
            android:exported="true-->"/>
    </application>

</manifest>
</code>```

Here is Repeating_activity.java file :-

```<code>import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

class Repeating_activity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repeating_activity_layout);
    }
}
</code>```

activity_main.xml and repeating_activity_layout.xml I have in my projecte not pasting here because I don't think it's need.

Here is error getting after crashing my application :-

```<code>16297-16297/com.example.hacker.timernotification E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                java.lang.RuntimeException: Unable to instantiate receiver com.example.hacker.timernotification.Notification_receiver: java.lang.IllegalAccessException: access to class not allowed
                                                                                at android.app.ActivityThread.handleReceiver(ActivityThread.java:2436)
                                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1365)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:176)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: java.lang.IllegalAccessException: access to class not allowed
                                                                                at java.lang.Class.newInstanceImpl(Native Method)
                                                                                at java.lang.Class.newInstance(Class.java:1319)
                                                                                at android.app.ActivityThread.handleReceiver(ActivityThread.java:2431)
                                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1365)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:176)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                at dalvik.system.NativeStart.main(Native Method)
</code>```

Please help to find solution . Any help will be Appreciated

答:
Update your manifest as below

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hacker.timernotification">

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Repeating_activity"/>
    <receiver android:name=".Notification_receiver"
         android:directBootAware="true">
          <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

</application>
</code>```

bootAware is required because your alarm will get disabled after restarting your device, in order to enable it again will have to use. Hope this helps

Dint notice it, agreed with gautam's answer

Body:
I am trying to fire alarm everyday on fix time but my application is crashing when click the button to fire alarm.
Please help to find solution. Thanks in Advance .

Here is my Main Activity code :-

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import java.util.Calendar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Calendar calendar = Calendar.getInstance();

                calendar.set(Calendar.HOUR_OF_DAY,15);
                calendar.set(Calendar.MINUTE,9);
                calendar.set(Calendar.SECOND,20);

                Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

                alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

            }
        });
    }
}

Here is my Notification_receiver.java file:-

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

class Notification_receiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent repeating_intent = new Intent(context,Repeating_activity.class);
        repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent .getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setSmallIcon(android.R.drawable.sym_def_app_icon)
                .setContentTitle("Notification Tittle")
                .setContentText("Notification Text")
                .setAutoCancel(true);

        notificationManager.notify(100,builder.build());
    }
}

Here is Manifest if needed :-

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hacker.timernotification">

    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/> //I tried with and without this but still crashing my app
    <uses-permission android:name="android.permission.WAKE_LOCK"/> // this is at the time of fire alarm

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Repeating_activity"/>
        <receiver android:name=".Notification_receiver"></receiver>
            "/>
    </application>

</manifest>

Here is Repeating_activity.java file :-

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

class Repeating_activity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.repeating_activity_layout);
    }
}

activity_main.xml and repeating_activity_layout.xml I have in my projecte not pasting here because I don't think it's need.

Here is error getting after crashing my application :-

16297-16297/com.example.hacker.timernotification E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                java.lang.RuntimeException: Unable to instantiate receiver com.example.hacker.timernotification.Notification_receiver: java.lang.IllegalAccessException: access to class not allowed
                                                                                at android.app.ActivityThread.handleReceiver(ActivityThread.java:2436)
                                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1365)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:176)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: java.lang.IllegalAccessException: access to class not allowed
                                                                                at java.lang.Class.newInstanceImpl(Native Method)
                                                                                at java.lang.Class.newInstance(Class.java:1319)
                                                                                at android.app.ActivityThread.handleReceiver(ActivityThread.java:2431)
                                                                                at android.app.ActivityThread.access$1600(ActivityThread.java:157)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1365)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                at android.os.Looper.loop(Looper.java:176)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5317)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                at dalvik.system.NativeStart.main(Native Method)

Please help to find solution . Any help will be Appreciated

Body:
Update your manifest as below

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hacker.timernotification">

<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".Repeating_activity"/>
    <receiver android:name=".Notification_receiver"
         android:directBootAware="true">
          <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

</application>

bootAware is required because your alarm will get disabled after restarting your device, in order to enable it again will have to use. Hope this helps

Dint notice it, agreed with gautam's answer


问:
Performing requests to ETSY store allowing access automatically PHP OAUTH
I am using a library to connect to my ETSY store and pull data from receipts to bring them into my personal website (database).

After making the request using OAuth, I get to the ETSY site to "Allow Access"

https://www.etsy.com/images/apps/documentation/oauth_authorize.png

Then, I need to manually click on Allow Access and my request will be completed and will display the data requested.

I would like to avoid the process of manually clicking on "Allow Access", since I want my personal site to automatically display information pulled from ETSY orders.

Here is my current code for page etsyRequest.php:

```<code>    $credentials = new Credentials(
    $servicesCredentials['etsy']['key'],
    $servicesCredentials['etsy']['secret'],
    $currentUri->getAbsoluteUri()
);

// Instantiate the Etsy service using the credentials, http client and storage mechanism for the token
/** @var $etsyService Etsy */
$etsyService = $serviceFactory->createService('Etsy', $credentials, $storage);

if (!empty($_GET['oauth_token'])) {
    $token = $storage->retrieveAccessToken('Etsy');

    // This was a callback request from Etsy, get the token
    $etsyService->requestAccessToken(
        $_GET['oauth_token'],
        $_GET['oauth_verifier'],
        $token->getRequestTokenSecret()
    );

    // Send a request now that we have access token
    $result2 = json_decode($etsyService->request('/receipts/111111'));

    //echo 'result: ```' . print_r($result, true) . '```';
    echo $result2->results[0]->seller_user_id;
</code>```

How could I automate the Allow Access part and get the returned value for my request by just running this page?

答: You need to save the access token when you have requested the Etsy store for the first time and then the same access token can be used for later calls. This would prevent you from clicking ALLOW ACCESS again and again when requesting Etsy store through API.</p>

Body:
I am using a library to connect to my ETSY store and pull data from receipts to bring them into my personal website (database).

After making the request using OAuth, I get to the ETSY site to "Allow Access"

https://www.etsy.com/images/apps/documentation/oauth_authorize.png

Then, I need to manually click on Allow Access and my request will be completed and will display the data requested.

I would like to avoid the process of manually clicking on "Allow Access", since I want my personal site to automatically display information pulled from ETSY orders.

Here is my current code for page etsyRequest.php:

    $credentials = new Credentials(
    $servicesCredentials['etsy']['key'],
    $servicesCredentials['etsy']['secret'],
    $currentUri->getAbsoluteUri()
);

// Instantiate the Etsy service using the credentials, http client and storage mechanism for the token
/** @var $etsyService Etsy */
$etsyService = $serviceFactory->createService('Etsy', $credentials, $storage);

if (!empty($_GET['oauth_token'])) {
    $token = $storage->retrieveAccessToken('Etsy');

    // This was a callback request from Etsy, get the token
    $etsyService->requestAccessToken(
        $_GET['oauth_token'],
        $_GET['oauth_verifier'],
        $token->getRequestTokenSecret()
    );

    // Send a request now that we have access token
    $result2 = json_decode($etsyService->request('/receipts/111111'));

    //echo 'result:
' . print_r($result, true) . '
';
    echo $result2->results[0]->seller_user_id;

How could I automate the Allow Access part and get the returned value for my request by just running this page?


问:
Is checking for true explicity bad by design?
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

```<code>var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);
</code>```

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.

答:
I'm in two minds about this myself.

In one respect, the code sample you've posted is good, because of the way Javascript handles type coercion.  A simple if (success) would enter the if block so long as success was truthy - e.g. a non-empty string would do the case.  The triple-equals guarantees that success is indeed the boolean value true, which is a stronger guarantee than you'd get with the shorter version (and probably one that you want).

However, if you need this - i.e. you don't know whether success will be a boolean, or a string, or an integer - I'd say that's a code smell in itself.  Regardless of how you perform the comparison, I'd always compare with a variable that's going to unavoidably be a boolean; at which point, it doesn't matter which form of comparison is used as they'd be equivalent.  In fact, I'd even introduce a "redundant" variable like so:

```<code>var successCount = items.size(); // or some other way to get an integer
var success = successCount > 0;
if (success) {
   ...
}
</code>```

So, erm, yeah.  I don't think anyone could really complain about the (explicit) use of === in the comparison because of its functional difference.  But by the same token, if you're clearly using boolean success flags then I don't think someone should complain about the short style either.

(Regarding your first sentence though, I don't think it's bad to explicitly check for the boolean value true in a dynamically typed language, if that value is actually what you want.  It's only superfluous when static typing already constrains the variable to be a boolean.)

Body:
Is it considered bad to explicitly check for the boolean true. Would it be better to do a simple if(success) ?

I've seen various jokes made about how if (someBoolean === true) is horrible code in a strongly typed language but is it also considered bad in weakly typed languages?

This would apply for any weakly typed language that does type coercion on an if statement.

A specific example would be :

var onSuccess = function (JSONfromServer) {
    // explicitly check for the boolean value `true`
    if (JSONfromServer === true) {
         // do some things
    }
}

// pass it to an ajax as a callback
doSomeAjax(onSuccess);

[Edit]

In this particular case the success variable is any valid JSON returned from a server. So it could be anything. if its the boolean true then a success happened. If it's some error handling object then it will be handled. If it's something else then it will probably be handled quietly.

The question was is getting the server to return true as JSON and checking for a good way to handle the case where the action succeeded.

I wanted to avoid being specific to JavaScript & AJAX though.

Body:
I'm in two minds about this myself.

In one respect, the code sample you've posted is good, because of the way Javascript handles type coercion.  A simple if (success) would enter the if block so long as success was truthy - e.g. a non-empty string would do the case.  The triple-equals guarantees that success is indeed the boolean value true, which is a stronger guarantee than you'd get with the shorter version (and probably one that you want).

However, if you need this - i.e. you don't know whether success will be a boolean, or a string, or an integer - I'd say that's a code smell in itself.  Regardless of how you perform the comparison, I'd always compare with a variable that's going to unavoidably be a boolean; at which point, it doesn't matter which form of comparison is used as they'd be equivalent.  In fact, I'd even introduce a "redundant" variable like so:

var successCount = items.size(); // or some other way to get an integer
var success = successCount > 0;
if (success) {
   ...
}

So, erm, yeah.  I don't think anyone could really complain about the (explicit) use of === in the comparison because of its functional difference.  But by the same token, if you're clearly using boolean success flags then I don't think someone should complain about the short style either.

(Regarding your first sentence though, I don't think it's bad to explicitly check for the boolean value true in a dynamically typed language, if that value is actually what you want.  It's only superfluous when static typing already constrains the variable to be a boolean.)


问:
Uploading File in Ajax Spring MVC Not Working
I am uploading a file using ajax to spring mvc controller using the following code

```<code>var formData = new FormData();
formData.append('file', file);

  $.ajax({
         url: url,
         data: formData,
         cache: false,
         contentType: false,
         processData: false,
         type: 'POST',
     });
</code>```

I can see my data in the http post but i am getting null value in controller.

```<code> @RequestMapping(value = { "/file.htm" }, method = RequestMethod.POST)

    public @ResponseBody String upload(@RequestParam(value="file",required=false) CommonsMultipartFile file

            ) throws IOException {

        String response="";
}
</code>```

I have tried with MultipartFile also. I have even tried to use MultipartHttpServletRequest and tried to obtain data from the request but cannot get it. Please let me know how to resolve it. Thanks

答:
```<code>var fd = new FormData();
fd.append( "file", $("input[name=file]").files[0]);

var ajaxReq =  $.ajax({
    url : 'kolfileUpload',
    type : 'POST',
    data : fd,
    cache : false,
    contentType : false,
    processData : false,

});
</code>```

Body:
I am uploading a file using ajax to spring mvc controller using the following code

var formData = new FormData();
formData.append('file', file);

  $.ajax({
         url: url,
         data: formData,
         cache: false,
         contentType: false,
         processData: false,
         type: 'POST',
     });

I can see my data in the http post but i am getting null value in controller.

 @RequestMapping(value = { "/file.htm" }, method = RequestMethod.POST)

    public @ResponseBody String upload(@RequestParam(value="file",required=false) CommonsMultipartFile file

            ) throws IOException {

        String response="";
}

I have tried with MultipartFile also. I have even tried to use MultipartHttpServletRequest and tried to obtain data from the request but cannot get it. Please let me know how to resolve it. Thanks


问:
mysql_field_table equivalent for mysqli
What's the equivalent of the following functions for mysqli:

```<code>$result = mysqli_query($this->link_id, $sql);
$k = 0;

mysql_field_table($result, $k)
mysql_field_name
mysql_field_type
mysql_field_len
mysql_field_flags
</code>```

I have a function that queries database tables and displays table information such as name, type, flags and length. Now I need to convert it into mysqli

答:
The function that you are looking for is mysqli_fetch_field_direct, this return an object with all the value that you are looking for on your case,

here is the example:

```<code>$table_info = mysqli_fetch_field_direct($result, $k);
$lenght = $table_info->length;
$name = $table_info->name;
$type = $table_info->type;
$flag = $table_info->flags;
</code>```

This is should be enough.

Here is the full description on the php documentation website:
http://php.net/manual/en/mysqli-result.fetch-field-direct.php

Title: mysql_field_table equivalent for mysqli

Body:
What's the equivalent of the following functions for mysqli:

$result = mysqli_query($this->link_id, $sql);
$k = 0;

mysql_field_table($result, $k)
mysql_field_name
mysql_field_type
mysql_field_len
mysql_field_flags

I have a function that queries database tables and displays table information such as name, type, flags and length. Now I need to convert it into mysqli

Body:
The function that you are looking for is mysqli_fetch_field_direct, this return an object with all the value that you are looking for on your case,

here is the example:

$table_info = mysqli_fetch_field_direct($result, $k);
$lenght = $table_info->length;
$name = $table_info->name;
$type = $table_info->type;
$flag = $table_info->flags;

This is should be enough.

Here is the full description on the php documentation website:
http://php.net/manual/en/mysqli-result.fetch-field-direct.php


问:
Can i use Watson TTS in my C++ project?
I'm working on a chat bot in C++ on a Linux system and I just need to give it a voice.

I know Watson TTS is awesome, I can even work on the tone of the voice and customize it.

How can I use Watson TTS for my C++ project? I saw on the official website that the SDKs are available for Node, java, python, .Net, Unity and Salesforce.

Is there any way I can use it to read the answers of my chat bot?

答: You can use the IBM Watson TTS service from a C++ program. AFAIK there is no SDK, but you have the documented Watson TTS API here. You would need to send the http requests via a C++ library. </p>

Title: Can i use Watson TTS in my C++ project?


问:
What GWT widget should I use to display String attributes from an Object?
In my GWT application my onSuccess(Object result) method ultimately retreives an Object with an ArrayList attribute.

This attribute contains Objects which has String attributes.

I'd like to display those String attributes to my GUI, and after researching CellTable and other widgets, I can't find a simple way to do so. I can't seem modify this CellTable source code example to fit my needs.

What would be the simplest way for me to achieve this? (Simple in the context of a novice).

Edit* Each String attribute would need to be displayed in a titled column and there will be more than one row of information.

答:
FlexTable http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FlexTable.html ?

or Grid http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/Grid.html ?

These are essentially the same. But Grid is faster, but needs to know its number of columns and rows before hand.