问:
Command only reads first line of text file
I have to make a program in which one of the functions is retrieval of usernames and results from  a text file. (All on the same line)
For some reason, when I run it, only the first line is printed out. Why is this ? Also, this only happens when I try to run the program at school (part of an assignment), it prints everything it needs to on my laptop at home. (Python versions are also the same)

Here is my code :

```<code>def results():
       username = input("Enter username :")
       for line in open("resultsfile.txt","r"):
             if username in line:
                  print (line)
             elif username not in line:
                   ("No such user")
</code>```

Also, this is what the text file looks like (without bullet points) :

tud16 CS Easy 2points

ser23 CH Med 4points

tud16 CS Hard 1points

答:
```<code>def results():
    username = input("Enter username :")
    for line in open("resultsfile.txt","r"):
        if username in line:
            print (line)
        else:
            print("No such user")
results()
</code>```

Body:
I have to make a program in which one of the functions is retrieval of usernames and results from  a text file. (All on the same line)
For some reason, when I run it, only the first line is printed out. Why is this ? Also, this only happens when I try to run the program at school (part of an assignment), it prints everything it needs to on my laptop at home. (Python versions are also the same)

Here is my code :

def results():
       username = input("Enter username :")
       for line in open("resultsfile.txt","r"):
             if username in line:
                  print (line)
             elif username not in line:
                   ("No such user")

Also, this is what the text file looks like (without bullet points) :

tud16 CS Easy 2points

ser23 CH Med 4points

tud16 CS Hard 1points


来源: stackexchange

问:
How to calculate time spent in each place
I have a data table as below:

```<code>DT1 <-
      read.table(text = "
                            id         time                 place_id
                            604        2017-08-10 18:44:14    15
                            604        2017-08-10 20:38:20    15
                            604        2017-08-10 20:54:26    24
                            604        2017-08-10 21:35:50    24
                            604        2017-08-11 12:05:42    30
                            604        2017-08-11 13:05:42    30

                          ", header = TRUE, stringsAsFactors = FALSE)
</code>```

From this I want to calculate the time spent in each place_id by each id.

```<code>id     time  place_id
604     6846   15
604     2484   24
604     3600   30
</code>```

I tried like this to get each group for each zone

```<code>DT1[,follow_group_new := cumsum(difftime(time, shift(time, fill=-Inf), units="mins") > 5), by=list(id,place_id)]
</code>```

This gives me each group .Not sure how to get the desired output from there.Any help is appreciated.

答:
You just need to compute the difference between the maximum amd the minimum timestamps per group of id and place_id. And of course you have to convert your time column to POSIXct before this operation.</p>

```<code>library(data.table)
setDT(DT1)
DT1[, time := as.POSIXct(time)]
DT1[, .(time = difftime(max(time), min(time), units = "secs")),
      by = .(id, place_id)]
#     id place_id      time
# 1: 604       15 6846 secs
# 2: 604       24 2484 secs
# 3: 604       30 3600 secs
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data table as below:

DT1 <-
      read.table(text = "
                            id         time                 place_id
                            604        2017-08-10 18:44:14    15
                            604        2017-08-10 20:38:20    15
                            604        2017-08-10 20:54:26    24
                            604        2017-08-10 21:35:50    24
                            604        2017-08-11 12:05:42    30
                            604        2017-08-11 13:05:42    30

                          ", header = TRUE, stringsAsFactors = FALSE)

From this I want to calculate the time spent in each place_id by each id.

id     time  place_id
604     6846   15
604     2484   24
604     3600   30

I tried like this to get each group for each zone

DT1[,follow_group_new := cumsum(difftime(time, shift(time, fill=-Inf), units="mins") > 5), by=list(id,place_id)]

This gives me each group .Not sure how to get the desired output from there.Any help is appreciated.

Body:
You just need to compute the difference between the maximum amd the minimum timestamps per group of id and place_id. And of course you have to convert your time column to POSIXct before this operation.

library(data.table)
setDT(DT1)
DT1[, time := as.POSIXct(time)]
DT1[, .(time = difftime(max(time), min(time), units = "secs")),
      by = .(id, place_id)]
#     id place_id      time
# 1: 604       15 6846 secs
# 2: 604       24 2484 secs
# 3: 604       30 3600 secs


问:
How to override background color of body without changing the existing background color?
how do i change the body background color red without overriding css or removing the css property?
https://i.stack.imgur.com/vNkRh.png</p>

答: Solved it by adding background-color white to each element. In this way, you are not overriding. background color red and even it will not be visible just reduce the opacity of newly added bg color you can see the red background color. This way you are not overriding the existing color.</p>


问:
AMQP server on localhost:5672 is unreachable: [Errno 111] ECONNREFUSED
i am trying to add additional compute node on different virtual machine to the pre-installed openstack. I disabled the firewall services,enable to ping other virtual machine.. but still compute node is not able to register with Rabbitmq service running on controller node..
Here it is my nova.conf file...

```<code>[DEFAULT]
dhcpbridge_flagfile=/etc/nova/nova.conf
dhcpbridge=/usr/bin/nova-dhcpbridge
state_path=/var/lib/nova
lock_path=/var/lock/nova
force_dhcp_release=True
iscsi_helper=tgtadm
libvirt_use_virtio_for_bridges=True
connection_type=libvirt
root_helper=sudo nova-rootwrap /etc/nova/rootwrap.conf
verbose=True
ec2_private_dns_show_ip=True
api_paste_config=/etc/nova/api-paste.ini
volumes_path=/var/lib/nova/volumes
enabled_apis=ec2,osapi_compute,metadata
rpc_backend = rabbit
auth_strategy = keystone
use_neutron = True
firewall_driver = nova.virt.firewall.NoopFirewallDriver
my_ip = #compute node ip
rabbit_host= #controller_node_ip
rabbit_port = 5672
rabbit_userid = stackrabbit
rabbit_password = devstack
rabbit_use_ssl = False
rabbit_virtual_host=/

[keystone_authtoken]
auth_uri = http://controller_node_ip:5000
auth_url = http://controller_node_ip:35357
memcached_servers = controller_node_ip:11211
auth_type = password
project_domain_name = default
user_domain_name = default
project_name = service
username = nova
password = devstack
auth_host = controller_node_ip
auth_port = 35357
auth_protocol = http

[vnc]
enabled = True
vncserver_listen = 0.0.0.0
vncserver_proxyclient_address = $my_ip
novncproxy_base_url = http://controller_node_ip:6080/vnc_auto.html

[glance]
api_servers = http://controller_node_ip:9292

[oslo_concurrency]
lock_path = /var/lib/nova/tmp
</code>```

Here it is my nova-compute.log:

```<code>2016-09-20 19:08:57.701 7201 INFO oslo.messaging._drivers.impl_rabbit [-] Reconnecting to AMQP server on localhost:5672
2016-09-20 19:08:57.701 7201 INFO oslo.messaging._drivers.impl_rabbit [-] Delaying reconnect for 1.0 seconds...
2016-09-20 19:08:58.708 7201 ERROR oslo.messaging._drivers.impl_rabbit [-] AMQP server on localhost:5672 is unreachable: [Errno 111] ECONNREFUSED. Trying again in 30 seconds...
</code>```

Please suggest me something so that i can resolve this issue...
Thank you in advance...

答:
I encountered this when expanding my nova-compute estate (although I'm not using Devstack).

In my newly created compute server, the following was seen in /var/log/nova/nova-compute.log : -

2017-11-14 11:40:53.287 52408 ERROR oslo.messaging._drivers.impl_rabbit [req-adfd6dc7-fe8c-4de5-8401-58d325c3b4a8 - - - - -] [be6e0302-dfc8-4512-8b48-0d824fc6ea14] AMQP server on 127.0.0.1:5672 is unreachable: [Errno 111] ECONNREFUSED. Trying again in 1 seconds. Client port: None

The solution was quite simple. I checked /var/log/sysinfo (I run ubuntu; /var/log/messages for those on Redhat systems) and could see the following lines:-

```<code>Nov 14 12:01:48 compute2 systemd[1]: Started OpenStack Compute.
Nov 14 12:01:49 compute2 nova-compute[3222]: Traceback (most recent call last):
Nov 14 12:01:49 compute2 nova-compute[3222]:   File "/usr/bin/nova-compute", line 10, in <module>
Nov 14 12:01:49 compute2 nova-compute[3222]:     sys.exit(main())
Nov 14 12:01:49 compute2 nova-compute[3222]:   File "/usr/lib/python2.7/dist-packages/nova/cmd/compute.py", line 42, in main
Nov 14 12:01:49 compute2 nova-compute[3222]:     config.parse_args(sys.argv)
Nov 14 12:01:49 compute2 nova-compute[3222]:   File "/usr/lib/python2.7/dist-packages/nova/config.py", line 52, in parse_args
Nov 14 12:01:49 compute2 nova-compute[3222]:     default_config_files=default_config_files)
Nov 14 12:01:49 compute2 nova-compute[3222]:   File "/usr/lib/python2.7/dist-packages/oslo_config/cfg.py", line 2355, in __call__
Nov 14 12:01:49 compute2 nova-compute[3222]:     self._namespace._files_permission_denied)
Nov 14 12:01:49 compute2 nova-compute[3222]: oslo_config.cfg.ConfigFilesPermissionDeniedError: Failed to open some config files: /etc/nova/nova.conf
Nov 14 12:01:49 compute2 systemd[1]: nova-compute.service: Main process exited, code=exited, status=1/FAILURE
</code>```

Which shows that my /etc/nova/nova.conf file was unreadable. It turns out this was because I used scp to copy the nova.conf from my first compute to my new machine, and the file was read-only to the root user. The solution was to (on my new compute)

```<code>cd /etc/nova/
chown nova:nova nova.conf
service nova-compute restart
</code>```

Body:
i am trying to add additional compute node on different virtual machine to the pre-installed openstack. I disabled the firewall services,enable to ping other virtual machine.. but still compute node is not able to register with Rabbitmq service running on controller node..
Here it is my nova.conf file...

[DEFAULT]
dhcpbridge_flagfile=/etc/nova/nova.conf
dhcpbridge=/usr/bin/nova-dhcpbridge
state_path=/var/lib/nova
lock_path=/var/lock/nova
force_dhcp_release=True
iscsi_helper=tgtadm
libvirt_use_virtio_for_bridges=True
connection_type=libvirt
root_helper=sudo nova-rootwrap /etc/nova/rootwrap.conf
verbose=True
ec2_private_dns_show_ip=True
api_paste_config=/etc/nova/api-paste.ini
volumes_path=/var/lib/nova/volumes
enabled_apis=ec2,osapi_compute,metadata
rpc_backend = rabbit
auth_strategy = keystone
use_neutron = True
firewall_driver = nova.virt.firewall.NoopFirewallDriver
my_ip = #compute node ip
rabbit_host= #controller_node_ip
rabbit_port = 5672
rabbit_userid = stackrabbit
rabbit_password = devstack
rabbit_use_ssl = False
rabbit_virtual_host=/

[keystone_authtoken]
auth_uri = http://controller_node_ip:5000
auth_url = http://controller_node_ip:35357
memcached_servers = controller_node_ip:11211
auth_type = password
project_domain_name = default
user_domain_name = default
project_name = service
username = nova
password = devstack
auth_host = controller_node_ip
auth_port = 35357
auth_protocol = http

[vnc]
enabled = True
vncserver_listen = 0.0.0.0
vncserver_proxyclient_address = $my_ip
novncproxy_base_url = http://controller_node_ip:6080/vnc_auto.html

[glance]
api_servers = http://controller_node_ip:9292

[oslo_concurrency]
lock_path = /var/lib/nova/tmp

Here it is my nova-compute.log:

2016-09-20 19:08:57.701 7201 INFO oslo.messaging._drivers.impl_rabbit [-] Reconnecting to AMQP server on localhost:5672
2016-09-20 19:08:57.701 7201 INFO oslo.messaging._drivers.impl_rabbit [-] Delaying reconnect for 1.0 seconds...
2016-09-20 19:08:58.708 7201 ERROR oslo.messaging._drivers.impl_rabbit [-] AMQP server on localhost:5672 is unreachable: [Errno 111] ECONNREFUSED. Trying again in 30 seconds...

Please suggest me something so that i can resolve this issue...
Thank you in advance...

Body:
I encountered this when expanding my nova-compute estate (although I'm not using Devstack).

In my newly created compute server, the following was seen in /var/log/nova/nova-compute.log : -

2017-11-14 11:40:53.287 52408 ERROR oslo.messaging._drivers.impl_rabbit [req-adfd6dc7-fe8c-4de5-8401-58d325c3b4a8 - - - - -] [be6e0302-dfc8-4512-8b48-0d824fc6ea14] AMQP server on 127.0.0.1:5672 is unreachable: [Errno 111] ECONNREFUSED. Trying again in 1 seconds. Client port: None

The solution was quite simple. I checked /var/log/sysinfo (I run ubuntu; /var/log/messages for those on Redhat systems) and could see the following lines:-

Nov 14 12:01:48 compute2 systemd[1]: Started OpenStack Compute.
Nov 14 12:01:49 compute2 nova-compute[3222]: Traceback (most recent call last):
Nov 14 12:01:49 compute2 nova-compute[3222]:   File "/usr/bin/nova-compute", line 10, in <module>
Nov 14 12:01:49 compute2 nova-compute[3222]:     sys.exit(main())
Nov 14 12:01:49 compute2 nova-compute[3222]:   File "/usr/lib/python2.7/dist-packages/nova/cmd/compute.py", line 42, in main
Nov 14 12:01:49 compute2 nova-compute[3222]:     config.parse_args(sys.argv)
Nov 14 12:01:49 compute2 nova-compute[3222]:   File "/usr/lib/python2.7/dist-packages/nova/config.py", line 52, in parse_args
Nov 14 12:01:49 compute2 nova-compute[3222]:     default_config_files=default_config_files)
Nov 14 12:01:49 compute2 nova-compute[3222]:   File "/usr/lib/python2.7/dist-packages/oslo_config/cfg.py", line 2355, in __call__
Nov 14 12:01:49 compute2 nova-compute[3222]:     self._namespace._files_permission_denied)
Nov 14 12:01:49 compute2 nova-compute[3222]: oslo_config.cfg.ConfigFilesPermissionDeniedError: Failed to open some config files: /etc/nova/nova.conf
Nov 14 12:01:49 compute2 systemd[1]: nova-compute.service: Main process exited, code=exited, status=1/FAILURE

Which shows that my /etc/nova/nova.conf file was unreadable. It turns out this was because I used scp to copy the nova.conf from my first compute to my new machine, and the file was read-only to the root user. The solution was to (on my new compute)

cd /etc/nova/
chown nova:nova nova.conf
service nova-compute restart


问:
Gulp copy all files inside a directory , without directory
This is my gulpfile

```<code>const gulp = require('gulp');
const runSequence = require('run-sequence');
const gulpCopy = require('gulp-copy');

//move client side library from client-lib to public folder
gulp.task('move-file',function(){
    console.log("Move-files");
    return gulp
        .src(['./client-lib/*.js'])
        .pipe(gulpCopy('./public'))

});

gulp.task('default',function(){
    runSequence('move-file');
});
</code>```

I need to copy all js files inside client-lib folder and copy to public folder . But this code copy with folder and my public folders look like

public->client-lib->myjsfiles

But I need

public->myjsfiles

答:
You can use a library called gulp-rename and here's  simple example:

```<code>    var gulp = require('gulp');
    var rename = require('gulp-rename');

   gulp.task('html', function(){
     return gulp.src('app/client/**/*.html')
         .pipe(rename({dirname: ''}))
        .pipe(gulp.dest('./dist'));
    });
</code>```

More answers:

Can you remove a folder structure when copying files in gulp?

Body:
This is my gulpfile

const gulp = require('gulp');
const runSequence = require('run-sequence');
const gulpCopy = require('gulp-copy');

//move client side library from client-lib to public folder
gulp.task('move-file',function(){
    console.log("Move-files");
    return gulp
        .src(['./client-lib/*.js'])
        .pipe(gulpCopy('./public'))

});

gulp.task('default',function(){
    runSequence('move-file');
});

I need to copy all js files inside client-lib folder and copy to public folder . But this code copy with folder and my public folders look like

public->client-lib->myjsfiles

But I need

public->myjsfiles

Body:
You can use a library called gulp-rename and here's  simple example:

    var gulp = require('gulp');
    var rename = require('gulp-rename');

   gulp.task('html', function(){
     return gulp.src('app/client/**/*.html')
         .pipe(rename({dirname: ''}))
        .pipe(gulp.dest('./dist'));
    });

More answers:

Can you remove a folder structure when copying files in gulp?


问:
PHP Website browser console Uncaught SyntaxError
I am facing issue Js Uncaught SyntaxError PHP Website

Details of query :

URL is http://www.matoshreenisarg.com/about-us/dg
This URL should be redirected to 404 but this is not redirecting appearing inspect  console error

```<code>*Uncaught SyntaxError: Unexpected token <
bootstrap.min.js:1
Uncaught SyntaxError: Unexpected token <
revolution.min.js:1
Uncaught SyntaxError: Unexpected token <
jquery.fancybox.pack.js:1
Uncaught SyntaxError: Unexpected token <
isotope.js:1
Uncaught SyntaxError: Unexpected token <
owl.js:1
Uncaught SyntaxError: Unexpected token <
jquery.gmap.js:1
Uncaught SyntaxError: Unexpected token <
jquery.easing.min.js:1
Uncaught SyntaxError: Unexpected token <
masterslider.js:1
Uncaught SyntaxError: Unexpected token <
wow.js:1
Uncaught SyntaxError: Unexpected token <
script.js:1
Uncaught SyntaxError: Unexpected token <*
</code>```

答:
use

/

in every external script/css call

For Example

src="/js/jquery.js" instead of src="js/jquery.js"

href="/css/style.css" instead of href="css/style.css"

Body:
I am facing issue Js Uncaught SyntaxError PHP Website

Details of query :

URL is http://www.matoshreenisarg.com/about-us/dg
This URL should be redirected to 404 but this is not redirecting appearing inspect  console error

*Uncaught SyntaxError: Unexpected token <
bootstrap.min.js:1
Uncaught SyntaxError: Unexpected token <
revolution.min.js:1
Uncaught SyntaxError: Unexpected token <
jquery.fancybox.pack.js:1
Uncaught SyntaxError: Unexpected token <
isotope.js:1
Uncaught SyntaxError: Unexpected token <
owl.js:1
Uncaught SyntaxError: Unexpected token <
jquery.gmap.js:1
Uncaught SyntaxError: Unexpected token <
jquery.easing.min.js:1
Uncaught SyntaxError: Unexpected token <
masterslider.js:1
Uncaught SyntaxError: Unexpected token <
wow.js:1
Uncaught SyntaxError: Unexpected token <
script.js:1
Uncaught SyntaxError: Unexpected token <*


问:
Get innerhtml from external page with Javascript
I'm trying to get innerHTML of a DIV that is located on external page. It is possible to do this using this kind javascript code?</p>

```<code>    <script type="text/javascript">
        $(document).ready(function(){
            var html = document.getElementById("glr1").src='/my_page.html'.innerHTML ;
            alert(html);
        });
    </script>
</code>```

答:
Since it looks like you are using jQuery, something like this should be pretty close:</p>

```<code> var html;
 $.get("my_page.html", function(data){
     html = $(data).find('#glr1').html();
 });
</code>```

Body:
Since it looks like you are using jQuery, something like this should be pretty close:

 var html;
 $.get("my_page.html", function(data){
     html = $(data).find('#glr1').html();
 });

ContentLicense: CC BY-SA 2.5


问:
Procedure select 1 and delete
I am trying to create a procedure that

  1. Selects the first record.

  2. Deletes the record and returns it to the caller.

I have the following code (mind you I am fairly new to PLSQL).
I got it from looking at other SO questions and the oracle docs.

```<code>CREATE PROCEDURE TAKE_1_DELETE_1
AS
BEGIN
DELETE FROM my_table
where rownum = 1
  RETURNING *
  INTO v_event;
END TAKE_1_DELETE_1;
</code>```

I get the following error:

```<code>[Error] PLS-00103 (7: 3): PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

   ; <an identifier> <a double-quoted delimited-identifier>
   current delete exists prior <a single-quoted SQL st
</code>```

I have tried numerous things, but none have worked thus far.

Our Data-Warehouse people are saying "We don't know what is wrong".

Dear SO gods... what do I need to do, to get my procedure to do what I want? :)

答:
There's a couple of errors here:

You haven't declared v_event so you're trying to return data into a uninstantiated variable/out parameter

You can't "return" * you have to explicitly state all columns - this is the actual error you're getting

Assuming a table that looks like this

```<code>create table my_table (a number, b number);
</code>```

Your procedure would look like the following:

```<code>create or replace procedure take_1_delete_1 is
   v_event my_table%rowtype;
begin

   delete from my_table
    where rownum = 1
   returning a, b
     into v_event;

end take_1_delete_1;
</code>```

Or, if you wanted to use the returning value outside the procedure you can use an OUT parameter rather than declaring a local variable

```<code>create or replace procedure take_1_delete_1 (p_event out my_table%rowtype) is
begin

   delete from my_table
    where rownum = 1
   returning a, b
     into p_event;

end take_1_delete_1;
</code>```

Title: Procedure select 1 and delete

Body:
I am trying to create a procedure that

  1. Selects the first record.

  2. Deletes the record and returns it to the caller.

I have the following code (mind you I am fairly new to PLSQL).
I got it from looking at other SO questions and the oracle docs.

CREATE PROCEDURE TAKE_1_DELETE_1
AS
BEGIN
DELETE FROM my_table
where rownum = 1
  RETURNING *
  INTO v_event;
END TAKE_1_DELETE_1;

I get the following error:

[Error] PLS-00103 (7: 3): PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

   ; <an identifier>
   current delete exists prior <a single-quoted SQL st

I have tried numerous things, but none have worked thus far.

Our Data-Warehouse people are saying "We don't know what is wrong".

Dear SO gods... what do I need to do, to get my procedure to do what I want? :)

Body:
There's a couple of errors here:

You haven't declared v_event so you're trying to return data into a uninstantiated variable/out parameter

You can't "return" * you have to explicitly state all columns - this is the actual error you're getting

Assuming a table that looks like this

create table my_table (a number, b number);

Your procedure would look like the following:

create or replace procedure take_1_delete_1 is
   v_event my_table%rowtype;
begin

   delete from my_table
    where rownum = 1
   returning a, b
     into v_event;

end take_1_delete_1;

Or, if you wanted to use the returning value outside the procedure you can use an OUT parameter rather than declaring a local variable

create or replace procedure take_1_delete_1 (p_event out my_table%rowtype) is
begin

   delete from my_table
    where rownum = 1
   returning a, b
     into p_event;

end take_1_delete_1;


问:
build/generated/source/apollo dictory not be generate

this is my project sturcture.the project from eclipse project, i want use graphQL,everything is ok,but build/generated/source/apollo dictory did not create.what should i do.for the project

答: First check if the "build/generated/source/apollo" directory already exist. If it is then check if the directory is "read-only"</p>


问:
Is Nagios the appropriate tool for monitoring based upon file dates?
We have a process wherein we send a file and some minutes later receive another file in response.  The process is synchronous, meaning we don't send a file until we receive the response to the previous file.

We keep requests and responses in separate directories.  We can determine the health of our system by examining the creation dates of the most recent file in each directory.  If we have sent a file at time X and don't receive a response by X+minutes, we know there's an issue.  I'd like Nagios to send an email to our help desk in this case.

Can Nagios grab file creation dates and compare them?  The Nagios guy at our company says it can't do it.  I am not believing it.

My google-fu is too weak to find answers to this question.

答:
I don't think there is a suitable out-of-the-box plugin for that, but writing your own Nagios plugins is really easy - the API is in its simplest form that your program (written in anything that can execute on the Nagios host) has to do this:

```<code>* Exit with one of several possible return values
* Return at least one line of text output to STDOUT
</code>```

If your Nagios administrator don't want custom plugins, you aren't out of options. If you can publish the current state of the process you want to monitor on a web server, the standard plugin check_http can be configured to look for certain strings on a web page.

You could also make use of passive checks, having your program feed the Nagios machine with test results either directly via the external_command_file or via a HTTP POST in the web interface.

Body:
I don't think there is a suitable out-of-the-box plugin for that, but writing your own Nagios plugins is really easy - the API is in its simplest form that your program (written in anything that can execute on the Nagios host) has to do this:

* Exit with one of several possible return values
* Return at least one line of text output to STDOUT

If your Nagios administrator don't want custom plugins, you aren't out of options. If you can publish the current state of the process you want to monitor on a web server, the standard plugin check_http can be configured to look for certain strings on a web page.

You could also make use of passive checks, having your program feed the Nagios machine with test results either directly via the external_command_file or via a HTTP POST in the web interface.


问:
Date range overlap per user rails
How can I make the validation of the date per user using the code below? When I logged in as a different user I am not able to create a reservation with the same dates. I have user_id which references id in the table users. I want to be able to make the date_start and date_end unique to only the user and still be able to create the same dates with a different user.

Link for more information:
Validation between two date rails

```<code>validate :no_reservation_overlap

 scope :overlapping, ->(period_start, period_end) do
    where "((date_start <= ?) and (date_end >= ?))", period_end, period_start
 end

private

def no_reservation_overlap
  if (Reservation.overlapping(date_start, date_end).any?)
     errors.add(:date_end, 'it overlaps another reservation')
  end
end
</code>```

答:
Guess you could try to add this to your validate:

```<code>validate :no_reservation_overlap, :uniqueness => { :scope => :user_id }
</code>```

Not sure if this works for you cause, but you should give it a try. Good luck!

EDIT:

I would suggest a different approach:

```<code>validate :no_reservation_overlap

def no_reservation_overlap
  if (Reservation.where("(? BETWEEN date_start AND date_end OR ? BETWEEN date_start AND date_end) AND user_id = ?", self.date_start, self.date_end, self.user_id).any?)
     errors.add(:date_end, 'it overlaps another reservation')
  end
end
</code>```

Guess this should work, please give it a try

Title: Date range overlap per user rails

Body:
How can I make the validation of the date per user using the code below? When I logged in as a different user I am not able to create a reservation with the same dates. I have user_id which references id in the table users. I want to be able to make the date_start and date_end unique to only the user and still be able to create the same dates with a different user.

Link for more information:
Validation between two date rails

validate :no_reservation_overlap

 scope :overlapping, ->(period_start, period_end) do
    where "((date_start <= ?) and (date_end >= ?))", period_end, period_start
 end

private

def no_reservation_overlap
  if (Reservation.overlapping(date_start, date_end).any?)
     errors.add(:date_end, 'it overlaps another reservation')
  end
end

Body:
Guess you could try to add this to your validate:

validate :no_reservation_overlap, :uniqueness => { :scope => :user_id }

Not sure if this works for you cause, but you should give it a try. Good luck!

EDIT:

I would suggest a different approach:

validate :no_reservation_overlap

def no_reservation_overlap
  if (Reservation.where("(? BETWEEN date_start AND date_end OR ? BETWEEN date_start AND date_end) AND user_id = ?", self.date_start, self.date_end, self.user_id).any?)
     errors.add(:date_end, 'it overlaps another reservation')
  end
end

Guess this should work, please give it a try


问:
Angular 4 call function in another component
I have a search bar in a header component, that are supposed to search in a list in another component. How do i get the headerComponent to call a function in the BooksComponent?</p>

```<code>export class HeaderComponent {
    search(){
        searchBooks($(".header-search-input").val());
    }
}

export class BooksComponent {

  searchBooks(searchWord){
    ...
}
</code>```

答:
First you should understand there is no way to call or access data from     another component from the current component.

By using the Input,Output attributes only the components will be interact     each other.

By Passing the input parameter as a child component by using Input attribute you can perform some operation on child component.

If you want to perform operation on parent component you should
use Output with event emitter.

I hope this will help you.

Body:
I have a search bar in a header component, that are supposed to search in a list in another component. How do i get the headerComponent to call a function in the BooksComponent?

export class HeaderComponent {
    search(){
        searchBooks($(".header-search-input").val());
    }
}

export class BooksComponent {

  searchBooks(searchWord){
    ...
}


问:
How can I create a new view in bigquery using the python API?
I have some code that automatically generates a bunch of different SQL queries that I would like to insert into the bigquery to generate views, though one of the issues that I have is that these views need to be generated dynamically every night because of the changing nature of the data.  So what I would like to be able to do is use the google bigquery api for python to be able to make a view.  I understand how to do it using the 'bq' command line tool, but I'd like to be able to have this built directly into the code as opposed to using a shell to run bq.  I have played with the code provided at

https://cloud.google.com/bigquery/bigquery-api-quickstart

I don't understand how to use this bit of code to create a view instead of just returning the results of a SELECT statement. I can see the documentation about doing table inserts here

https://cloud.google.com/bigquery/docs/reference/v2/tables/insert

but that refers to using the REST API to generate new tables as opposed to the example provided above.

Is it just not possible?  Should I just give in and use bq?

Thanks

*** Some additional questions in response to Felipe's comments.

The table resource document indicates that there are a number of required fields, some of which make sense even if I don't fully understand what they're asking for, others do not.  For example, externalDataConfiguration.schema. Does this refer to the schema for the database that I'm connecting to (I assume it does), or the schema for storing the data?

What about externalDataConfiguration.sourceFormat?  Since I'm trying to make a view of a pre-existing database, I'm not sure I understand how the source format is relevant. Is it the source format of the database I'm making a view from?  How would I identify that?

ANd externalDataConfiguration.sourceUris[], I'm not importing new data into the database, so I don't understand how this (or the previous element) are required.

What about schema?

tableReference.datasetId, tableReference.projectId, and tableReference.tableId are self explanatory.

Type would be view, and view.query would be the actual sql query used to make the view.  So I get why those are required for making a view, but I don't understand the other parts.

Can you help me understand these details?

Thanks,
Brad

答:
Note:  this changed a little bit with 0.28.0 of the library - see the following for further details:
Google BigQuery: creating a view via Python google-cloud-bigquery version 0.27.0 vs. 0.28.0

my example function

```<code># create a view via python
def create_view(dataset_name, view_name, sqlQuery, project=None):
    try:

        bigquery_client = bigquery.Client(project=project)
        dataset_ref = bigquery_client.dataset(dataset_name)
        table_ref = dataset_ref.table(view_name)
        table = Table(table_ref)
        table.view_query = sqlQuery
        table.view_use_legacy_sql = False
        bigquery_client.create_table(table)

        return True

    except Exception as e:
        errorStr = 'ERROR (create_view): ' + str(e)
        print(errorStr)
        raise
</code>```

Body:
Note:  this changed a little bit with 0.28.0 of the library - see the following for further details:
Google BigQuery: creating a view via Python google-cloud-bigquery version 0.27.0 vs. 0.28.0

my example function

# create a view via python
def create_view(dataset_name, view_name, sqlQuery, project=None):
    try:

        bigquery_client = bigquery.Client(project=project)
        dataset_ref = bigquery_client.dataset(dataset_name)
        table_ref = dataset_ref.table(view_name)
        table = Table(table_ref)
        table.view_query = sqlQuery
        table.view_use_legacy_sql = False
        bigquery_client.create_table(table)

        return True

    except Exception as e:
        errorStr = 'ERROR (create_view): ' + str(e)
        print(errorStr)
        raise


问:
mongoose autoincrement counter per unique value
I have the two models, entity and post, and I'm trying to create an auto incremented counter on post for each unique entity:

```<code>//entity
var entitySchema = mongoose.Schema({
    name: String,
    counter: Number,
});

//post
var postSchema = mongoose.Schema({
    test: String,
    entity: {
        type: Schema.Types.ObjectId,
        ref: 'entity'
    },
    ticketNumber: Number //this needs to auto increment starting at zero PER user, so entity A has a 1+, entity 2 has a 1+, etc
});
</code>```

I can have a sequence on entity, check it every time I create a post and use it, but that could possibly have duplicates.

I found a post suggesting an even on pre post'save', but that wouldn't be unique to each entity, just unique overall.

Any way to get this working on the model itself / a better way of doing this?

答:
You can use the npm package called  mongoose-auto-increment.

Your connection would look like this:

```<code>    var autoIncrement = require('mongoose-auto-increment');

    var connection = mongoose.connect('YOUR CONNECTION');

    autoIncrement.initialize(connection);
</code>```

your Schema would look like this:

```<code>    var postSchema = mongoose.Schema({
        test: String,
        entity: {
            type: Schema.Types.ObjectId,
            ref: 'entity'
        },
        ticketNumber: Number
    });

    postSchema.plugin(autoIncrement.plugin, { model: 'NAME YOUR MODEL', field: 'ticketNumber', startAt: 0, incrementBy: 1 });
</code>```

Body:
I have the two models, entity and post, and I'm trying to create an auto incremented counter on post for each unique entity:

//entity
var entitySchema = mongoose.Schema({
    name: String,
    counter: Number,
});

//post
var postSchema = mongoose.Schema({
    test: String,
    entity: {
        type: Schema.Types.ObjectId,
        ref: 'entity'
    },
    ticketNumber: Number //this needs to auto increment starting at zero PER user, so entity A has a 1+, entity 2 has a 1+, etc
});

I can have a sequence on entity, check it every time I create a post and use it, but that could possibly have duplicates.

I found a post suggesting an even on pre post'save', but that wouldn't be unique to each entity, just unique overall.

Any way to get this working on the model itself / a better way of doing this?

Body:
You can use the npm package called  mongoose-auto-increment.

Your connection would look like this:

    var autoIncrement = require('mongoose-auto-increment');

    var connection = mongoose.connect('YOUR CONNECTION');

    autoIncrement.initialize(connection);

your Schema would look like this:

    var postSchema = mongoose.Schema({
        test: String,
        entity: {
            type: Schema.Types.ObjectId,
            ref: 'entity'
        },
        ticketNumber: Number
    });

    postSchema.plugin(autoIncrement.plugin, { model: 'NAME YOUR MODEL', field: 'ticketNumber', startAt: 0, incrementBy: 1 });


问:
PyCryptodome RSA encryption
I am trying to use the pycryptodome example of encrypting a file with an RSA key. The example is as follows

```<code>from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

file_out = open("encrypted_data.bin", "wb")

recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
file_out.write(cipher_rsa.encrypt(session_key))

# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]
</code>```

And the error I receive is

AttributeError: module 'Crypto.PublicKey.RSA' has no attribute 'import_key'

I found another thread where this error was identified as a version problem with pyCrypto but I am trying to use PyCryptodome and I do have the latest version.

答:
The method import_key was added in PyCryptodome v3.4.
If you get that error message, it means you are in reality using PyCrypto or an older version of PyCryptodome.

ContentLicense: CC BY-SA 4.0

Title: PyCryptodome RSA encryption

Body:
I am trying to use the pycryptodome example of encrypting a file with an RSA key. The example is as follows

from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP

file_out = open("encrypted_data.bin", "wb")

recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
file_out.write(cipher_rsa.encrypt(session_key))

# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (cipher.nonce, tag, ciphertext) ]

And the error I receive is

AttributeError: module 'Crypto.PublicKey.RSA' has no attribute 'import_key'

I found another thread where this error was identified as a version problem with pyCrypto but I am trying to use PyCryptodome and I do have the latest version.


问:
SocialEngine - Hook before signup process complete
I want to add a new step in signup process of SocialEngine and I want after first step to send some verification code to the user's phone number. How can I set a hook for that like onUserCreateBefore. I added this in User/Plugin/Core.php but no result. When I pass step 1 that is main information about Account but that hook doesn't call even if I die('something')

What should I do?

答:
There is a third party plugin for mobile verification.

https://www.ipragmatech.com/products/socialengine-mobile-verification-plugin/


问:
iPhone application – reading SMS
I need to develop an iPhone application which needs to read the incoming SMS received by the user, manipulate the text, and then display it in the application.

Could someone clarify whether it is possible to read the SMS received within our application development?

Thanks!

答: Intercepting/reading incoming SMS is not possible on iOS (for privacy reasons).</p>

Title: iPhone application – reading SMS


问:
How to use vue.js with sails js
I want to use vue.js as frontend for sails.js i tried to configure using the method given at
http://filipbartus.name/integrate-vue-loader-with-sails-js/ but it was not working for vue latest version but i don't see any reason why? can someone explain why is it not working please?

latest version not working:  https://github.com/jeevansai502/kube

previous version from example working:  https://github.com/filipinyo/vue_sails_integration

答:
I think tha the best options is replacing Grunt with Webpack and vue loader.
Look at this repo https://github.com/Tarrask/sails-hook-webpack-vue. It's pretty easy with this hook.</p>

Title: How to use vue.js with sails js


问:
PDO-MySQL: Boolean values get converted to 1 or empty string on prepared statement binding
I'm trying to insert some boolean values into JSON-type columns.

```<code>$taskSql = "INSERT INTO Tasks (data, taskListId) VALUES (JSON_OBJECT('title', :title, 'done', :done), :taskListId)";
$taskStatement = $connection->prepare($taskSql);
$taskStatement->execute([":title" => $task->title, ":done" => $task->done, ":taskListId" => $id]);
</code>```

Which results in following SQL being executed.

```<code>-- $task->done is false
INSERT INTO Tasks (data, taskListId) VALUES (JSON_OBJECT('title', 'New Task', 'done', ''), '12')
-- $task->done is true
INSERT INTO Tasks (data, taskListId) VALUES (JSON_OBJECT('title', 'New Task', 'done', '1'), '12')
</code>```

Is there a way to make PDO turn those into TRUE or FALSE in the SQL-statement, which would then convert them into proper JSON-boolean-values.

EDIT:

I've  now tried using bindParam and bindValue instead of the argument to execute. Those don't fix the problem as PDO still converts the boolean values to 0 or 1.

EDIT: Looks like there is an 11 year old bug report, that still hasn't been addressed.

答:
I endet up changing the insert line to

```<code>INSERT INTO Tasks (data, taskListId) VALUES (JSON_OBJECT('title', :title, 'done', :done = TRUE || :done = '1'), :taskListId);
</code>```

Not a solution but a workaround.

Body:
I'm trying to insert some boolean values into JSON-type columns.

$taskSql = "INSERT INTO Tasks (data, taskListId) VALUES (JSON_OBJECT('title', :title, 'done', :done), :taskListId)";
$taskStatement = $connection->prepare($taskSql);
$taskStatement->execute([":title" => $task->title, ":done" => $task->done, ":taskListId" => $id]);

Which results in following SQL being executed.

-- $task->done is false
INSERT INTO Tasks (data, taskListId) VALUES (JSON_OBJECT('title', 'New Task', 'done', ''), '12')
-- $task->done is true
INSERT INTO Tasks (data, taskListId) VALUES (JSON_OBJECT('title', 'New Task', 'done', '1'), '12')

Is there a way to make PDO turn those into TRUE or FALSE in the SQL-statement, which would then convert them into proper JSON-boolean-values.

EDIT:

I've  now tried using bindParam and bindValue instead of the argument to execute. Those don't fix the problem as PDO still converts the boolean values to 0 or 1.

EDIT: Looks like there is an 11 year old bug report, that still hasn't been addressed.

Body:
I endet up changing the insert line to

INSERT INTO Tasks (data, taskListId) VALUES (JSON_OBJECT('title', :title, 'done', :done = TRUE || :done = '1'), :taskListId);

Not a solution but a workaround.


问:
How to show menu and title on all activities?
I have created three activities explore/deals and packages. I have created my menu using drawer layout. I would like to saw my menu icon on each activity screen. I have created a base activity for menu items and extends that to all activities. I'm attaching my homeactivity code, base activity code and explore activity code below

enter image description here

Here is explore activity code

```<code>package com.example.windows81.travelspoc;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class ExploreActivity extends BaseActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_explore);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //getMenuInflater().inflate(R.menu.menu_second, menu);  <- remove this
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
}
</code>```

Here is my homeactivity code

```<code>package com.example.windows81.travelspoc;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{

ViewPager viewPager;
LinearLayout sliderDotspanel;
NavigationView mNavigationView;
private int dotscount;
private ImageView[] dots;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;

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

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open,
R.string.close);
    NavigationView mNavigationView = (NavigationView)
findViewById(R.id.navigation);
    mNavigationView.setNavigationItemSelectedListener(this);

    mDrawerLayout.addDrawerListener(mtoggle);
    mtoggle.syncState();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewPager);

    sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
    viewPager.setAdapter(viewPagerAdapter);

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

    dotscount = viewPagerAdapter.getCount();
    dots = new ImageView[dotscount];

    for (int i = 0; i < dotscount; i++){
        dots[i] = new ImageView(this);

dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));

        LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

        params.setMargins(8, 0, 8,0);

        sliderDotspanel.addView(dots[i], params);
    }

dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.ic_active));
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            for (int i = 0; i < dotscount; i++){

dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));
            }

dots[position].setImageDrawable(ContextCompat.getDrawable
(getApplicationContext(), R.drawable.ic_active));

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(mtoggle.onOptionsItemSelected(item)){
        return true;
    }
    switch (item.getItemId()) {
        case R.id.explore:
            // do what you want here
            myMethod();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public class MyTimerTask extends TimerTask{

    @Override
    public void run() {

        HomeActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (viewPager.getCurrentItem() == 0){
                    viewPager.setCurrentItem(1);
                }else if (viewPager.getCurrentItem() == 1){
                    viewPager.setCurrentItem(2);
                }else{
                    viewPager.setCurrentItem(0);
                }

            }
        });

    }
}

public void myMethod(){
    Intent intent = new Intent(this,ExploreActivity.class);
    startActivity(intent);
}
public void exploreActivity(View view){
    myMethod();
}

public void packagesActivity(View view){
    Intent intent = new Intent(this,PackagesActivity.class);
    startActivity(intent);
}

public void dealsActivity(View view){
    Intent intent = new Intent(this,DealsActivity.class);
    startActivity(intent);
}
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.explore) {
        myMethod();
    }
    return false;
}
}
</code>```

Here is my Base activity code

```<code>package com.example.windows81.travelspoc;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

/**
 * Created by Windows 8.1 on 11/15/2017.
 */

public class BaseActivity extends AppCompatActivity{
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.explore:
            myMethod();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void myMethod(){
    Intent intent = new Intent(this,ExploreActivity.class);
    startActivity(intent);
}
public void exploreActivity(View view){
    myMethod();
}

public void packagesActivity(View view){
    Intent intent = new Intent(this,PackagesActivity.class);
    startActivity(intent);
}

public void dealsActivity(View view){
    Intent intent = new Intent(this,DealsActivity.class);
    startActivity(intent);
}
}
</code>```

答:
If you have same menu through out all activities then i will advice you to create one

BaseActivity then extends it to AppcompatActivity

Make Activity1 -> extends BaseActivity

Magic comes here -> You don't have to use setContentView for all the time.

Make BaseActivity with One XML -> FrameLayout -> with Your

ToolBar & FrameLayout

Now in the Activity1 inflate your view in FrameLayout of BaseActivity

And follow the same system for all the activities.

I had the same situation -> I had to display sideMenu in every Activity so i ended up with this solution.

Body:
I have created three activities explore/deals and packages. I have created my menu using drawer layout. I would like to saw my menu icon on each activity screen. I have created a base activity for menu items and extends that to all activities. I'm attaching my homeactivity code, base activity code and explore activity code below

enter image description here

Here is explore activity code

package com.example.windows81.travelspoc;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class ExploreActivity extends BaseActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_explore);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //getMenuInflater().inflate(R.menu.menu_second, menu);  <- remove this
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}
}

Here is my homeactivity code

package com.example.windows81.travelspoc;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{

ViewPager viewPager;
LinearLayout sliderDotspanel;
NavigationView mNavigationView;
private int dotscount;
private ImageView[] dots;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mtoggle;

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

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open,
R.string.close);
    NavigationView mNavigationView = (NavigationView)
findViewById(R.id.navigation);
    mNavigationView.setNavigationItemSelectedListener(this);

    mDrawerLayout.addDrawerListener(mtoggle);
    mtoggle.syncState();

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewPager);

    sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

    ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
    viewPager.setAdapter(viewPagerAdapter);

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

    dotscount = viewPagerAdapter.getCount();
    dots = new ImageView[dotscount];

    for (int i = 0; i < dotscount; i++){
        dots[i] = new ImageView(this);

dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));

        LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);

        params.setMargins(8, 0, 8,0);

        sliderDotspanel.addView(dots[i], params);
    }

dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.ic_active));
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            for (int i = 0; i < dotscount; i++){

dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),
R.drawable.incative_dot));
            }

dots[position].setImageDrawable(ContextCompat.getDrawable
(getApplicationContext(), R.drawable.ic_active));

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(mtoggle.onOptionsItemSelected(item)){
        return true;
    }
    switch (item.getItemId()) {
        case R.id.explore:
            // do what you want here
            myMethod();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public class MyTimerTask extends TimerTask{

    @Override
    public void run() {

        HomeActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                if (viewPager.getCurrentItem() == 0){
                    viewPager.setCurrentItem(1);
                }else if (viewPager.getCurrentItem() == 1){
                    viewPager.setCurrentItem(2);
                }else{
                    viewPager.setCurrentItem(0);
                }

            }
        });

    }
}

public void myMethod(){
    Intent intent = new Intent(this,ExploreActivity.class);
    startActivity(intent);
}
public void exploreActivity(View view){
    myMethod();
}

public void packagesActivity(View view){
    Intent intent = new Intent(this,PackagesActivity.class);
    startActivity(intent);
}

public void dealsActivity(View view){
    Intent intent = new Intent(this,DealsActivity.class);
    startActivity(intent);
}
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.explore) {
        myMethod();
    }
    return false;
}
}

Here is my Base activity code

package com.example.windows81.travelspoc;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

/**
 * Created by Windows 8.1 on 11/15/2017.
 */

public class BaseActivity extends AppCompatActivity{
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.navigation_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.explore:
            myMethod();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

public void myMethod(){
    Intent intent = new Intent(this,ExploreActivity.class);
    startActivity(intent);
}
public void exploreActivity(View view){
    myMethod();
}

public void packagesActivity(View view){
    Intent intent = new Intent(this,PackagesActivity.class);
    startActivity(intent);
}

public void dealsActivity(View view){
    Intent intent = new Intent(this,DealsActivity.class);
    startActivity(intent);
}
}


问:
Existing li gets overridden in todolist instead of adding a new li
I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

let addNewFunc = function () {
  let name = ul.appendChild(addNew);
  name.textContent = input.value
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>spooky</h1>

<input type="text" class="input">
<ul>
  <li>1</li>
  <li>2</li>
</ul></code>```

答:
This should help u.

please note: I have minute changes to your html; here u enter in inputbox and click button to add it to list

here is the fiddle : https://jsfiddle.net/5o2vwdqc/

html

```<code><h1>spooky</h1>

    <input type="text" class="input">
    <button id="addToList">
    Add to List
    </button>
    <ul id="theList">
        <li>1</li>
        <li>2</li>
    </ul>
</code>```

js

```<code>let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

document.getElementById("addToList").onclick = function() {
  let inputValue = document.getElementsByClassName("input")[0].value;
  let addNew = document.createElement("li");
  let textNode = document.createTextNode(inputValue);
  addNew.appendChild(textNode);
  document.getElementById("theList").appendChild(addNew);
}
</code>```

Body:
I am creating a Todolist, when I write something in the input and use the function addNewFunc() it adds a new li, the problem is that it always just overrides that li, it never makes a new li. (example: I write 1 in the input, use the function and 1 will be added as an li, if i write 2 in the input and use the function, that 1 will now become 2, instead of having a 1 and 2)

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

let addNewFunc = function () {
  let name = ul.appendChild(addNew);
  name.textContent = input.value
};

spooky

<input type="text" class="input">

1

2

Body:
This should help u.

please note: I have minute changes to your html; here u enter in inputbox and click button to add it to list

here is the fiddle : https://jsfiddle.net/5o2vwdqc/

html

<h1>spooky</h1>

    <input type="text" class="input">
    <button id="addToList">
    Add to List
    </button>
    <ul id="theList">
        <li>1</li>
        <li>2</li>
    </ul>

js

let input = document.querySelector(".input");
let ul = document.querySelector("ul");
let addNew = document.createElement("li");

document.getElementById("addToList").onclick = function() {
  let inputValue = document.getElementsByClassName("input")[0].value;
  let addNew = document.createElement("li");
  let textNode = document.createTextNode(inputValue);
  addNew.appendChild(textNode);
  document.getElementById("theList").appendChild(addNew);
}


问:
Advanced filter with multiple criteria
Does anyone know how after applying the advanced filter in the code below, I can apply another one in col E to show unique values on the filtered data (without getting rid of what is already filtered?) - Any help would be much appreciated</p>

```<code>Sub difficultQ()

    Dim x
    Dim Y

    x = "Match"

    Y = "Match1"

    Range("A1").Value = x

    Range("A2").Value = Y

    Range("M4").Select

    Range(Selection, Selection.End(xlDown)).Select

    Selection.AdvancedFilter Action:=xlFilterInPlace, criteriarange:=Range("A1:A2")

    ' In here I would like to have code that filtered col E
    ' on unique values, without getting rid of the advanced filter above

End Sub
</code>```

答:
You can't apply two advanced filters. You'd need to amend the filter criteria and use a formula for example like this:</p>

```<code>Sub difficultQ()

    Dim x
    Dim Y
    Dim lastRow As Long

    Y = "Match1"

    Range("A1").Value = vbNullString

    Range("A2").Formula = "=AND(M5=""" & Y & """,COUNTIFS($E$5:$E5,E5,M$5:M5,""" & Y & """)=1)"
    lastRow = Cells(Rows.Count, "M").End(xlUp).Row
    Range("E4:M" & lastRow).AdvancedFilter Action:=xlFilterInPlace, criteriarange:=Range("A1:A2")

End Sub
</code>```

Title: Advanced filter with multiple criteria

Body:
Does anyone know how after applying the advanced filter in the code below, I can apply another one in col E to show unique values on the filtered data (without getting rid of what is already filtered?) - Any help would be much appreciated

Sub difficultQ()

    Dim x
    Dim Y

    x = "Match"

    Y = "Match1"

    Range("A1").Value = x

    Range("A2").Value = Y

    Range("M4").Select

    Range(Selection, Selection.End(xlDown)).Select

    Selection.AdvancedFilter Action:=xlFilterInPlace, criteriarange:=Range("A1:A2")

    ' In here I would like to have code that filtered col E
    ' on unique values, without getting rid of the advanced filter above

End Sub

Body:
You can't apply two advanced filters. You'd need to amend the filter criteria and use a formula for example like this:

Sub difficultQ()

    Dim x
    Dim Y
    Dim lastRow As Long

    Y = "Match1"

    Range("A1").Value = vbNullString

    Range("A2").Formula = "=AND(M5=""" & Y & """,COUNTIFS($E$5:$E5,E5,M$5:M5,""" & Y & """)=1)"
    lastRow = Cells(Rows.Count, "M").End(xlUp).Row
    Range("E4:M" & lastRow).AdvancedFilter Action:=xlFilterInPlace, criteriarange:=Range("A1:A2")

End Sub


问:
Add Picture to header of Word through vba
I am trying to insert a picture to the header of a word file through MS Access VBA. I cannot seem to get the code working:

```<code>Sub Insertpictoheader()
    Dim oHeader As Word.HeaderFooter
    Dim sh As Word.Shape, ils As Word.InlineShape

    Set oSec = ActiveDocument.Sections(1)
    Set oHeader = oSec.Headers(wdHeaderFooterFirstPage)
    oHeader.Range.InlineShapes.AddPicture "C:\Desktop\Logo.png"
End Sub
</code>```

Nothing appears, I can get the image into the file but not the header.

答:
The method below creates a table in header and adds an image. Just provide the path for the image.

Modify it if needed to fit your needs.

```<code>Public Sub UpdateHeader(oDoc As Word.Document)
    Dim oSec As Word.Section, rng As Range

    For Each oSec In oDoc.Sections
        Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
            With rng
                .Tables.Add Range:=rng, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitWindow
                With .Tables(1)
                    .Borders.InsideLineStyle = wdLineStyleNone
                    .Borders.OutsideLineStyle = wdLineStyleNone
                    .Rows.SetLeftIndent LeftIndent:=-37, RulerStyle:=wdAdjustNone
                    .Cell(1, 1).Range.InlineShapes.AddPicture filename:="Your file path", LinkToFile:=False, SaveWithDocument:=True
                End With
            End With
    Next oSec
End Sub
</code>```

Body:
I am trying to insert a picture to the header of a word file through MS Access VBA. I cannot seem to get the code working:

Sub Insertpictoheader()
    Dim oHeader As Word.HeaderFooter
    Dim sh As Word.Shape, ils As Word.InlineShape

    Set oSec = ActiveDocument.Sections(1)
    Set oHeader = oSec.Headers(wdHeaderFooterFirstPage)
    oHeader.Range.InlineShapes.AddPicture "C:\Desktop\Logo.png"
End Sub

Nothing appears, I can get the image into the file but not the header.

Body:
The method below creates a table in header and adds an image. Just provide the path for the image.

Modify it if needed to fit your needs.

Public Sub UpdateHeader(oDoc As Word.Document)
    Dim oSec As Word.Section, rng As Range

    For Each oSec In oDoc.Sections
        Set rng = oSec.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterPrimary).Range
            With rng
                .Tables.Add Range:=rng, NumRows:=1, NumColumns:=1, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:=wdAutoFitWindow
                With .Tables(1)
                    .Borders.InsideLineStyle = wdLineStyleNone
                    .Borders.OutsideLineStyle = wdLineStyleNone
                    .Rows.SetLeftIndent LeftIndent:=-37, RulerStyle:=wdAdjustNone
                    .Cell(1, 1).Range.InlineShapes.AddPicture filename:="Your file path", LinkToFile:=False, SaveWithDocument:=True
                End With
            End With
    Next oSec
End Sub


问:
SocialEngine(Zend) returns error when instantiating a model of table
When I want to instantiate a model from a table with this code below:

Articlemanagement/Model/DbTable/Articles.php:

```<code>class Articlemanagement_Model_DbTable_Articles extends Engine_Db_Table
{
    protected $_rowClass = 'Articlemanagement_Model_Article';
}
</code>```

Articlemanagement/Model/Article.php:

```<code>class Articlemanagement_Model_Article extends Core_Model_Item_Abstract
{
    protected $_owner_type = 'user';
}
</code>```

Articlemanagement/controllers/AdminIndexController.php:

```<code>class Articlemanagement_AdminIndexController extends Core_Controller_Action_Admin
{
  public function indexAction()
  {
      $table = Engine_Api::_()->getDbtable('articles', 'articlemanagement');
  }
}
</code>```

it returns this error below:
exception 'Engine_Loader_Exception' with message 'Could not load class: Articlemanagement_Model_DbTable_Articles' in public_html/application/libraries/Engine/Loader.php:131

How can I fix it?

答: Must be some spelling mistake. Recheck your code</p>

Body:
When I want to instantiate a model from a table with this code below:

Articlemanagement/Model/DbTable/Articles.php:

class Articlemanagement_Model_DbTable_Articles extends Engine_Db_Table
{
    protected $_rowClass = 'Articlemanagement_Model_Article';
}

Articlemanagement/Model/Article.php:

class Articlemanagement_Model_Article extends Core_Model_Item_Abstract
{
    protected $_owner_type = 'user';
}

Articlemanagement/controllers/AdminIndexController.php:

class Articlemanagement_AdminIndexController extends Core_Controller_Action_Admin
{
  public function indexAction()
  {
      $table = Engine_Api::_()->getDbtable('articles', 'articlemanagement');
  }
}

it returns this error below:
exception 'Engine_Loader_Exception' with message 'Could not load class: Articlemanagement_Model_DbTable_Articles' in public_html/application/libraries/Engine/Loader.php:131

How can I fix it?


问:
How to execute a same query for 7 days in Oracle sql developer
I have a query

```<code>select count(*)
from purchases
where START_TIME>=TO_DATE('10-NOV-2017 00:00','DD-MON-YY HH24:MI') AND START_TIME<TO_DATE('10-NOV-2017 01:00','DD-MON-YY HH24:MI') and
      CLIENT_ID in (1,54);
</code>```

and by using this I am gathering stats for an hour. But I am going to need stats everyday for the same time for past 7 days.

I mean, from above query I am gathering between 10-NOV-2017 00:00 and 10-NOV-2017 01:00 and similarly I need to gather for 09-NOV-2017 00:00 to 09-NOV-2017 01:00 and so on for past 7 days.

And it should print like

```<code>  Date        | Count
+-------------+-------+
  10-NOV-2017 | 100
  09-NOV-2017 | 110
</code>```

Is it achievable ?

答:
try this</p>

```<code> SELECT to_char(START_TIME,'DD-MON-YY') date,
  count(*) count
FROM
  purchases
 WHERE
  START_TIME  >=TO_DATE('10-NOV-2017 00:01','DD-MON-YY HH24:MI') -7
AND START_TIME <TO_DATE('10-NOV-2017 00:02','DD-MON-YY HH24:MI')
AND CLIENT_ID IN (1,54)
 group by to_char(START_TIME,'DD-MON-YY') ;
</code>```

Body:
I have a query

select count(*)
from purchases
where START_TIME>=TO_DATE('10-NOV-2017 00:00','DD-MON-YY HH24:MI') AND START_TIME<TO_DATE('10-NOV-2017 01:00','DD-MON-YY HH24:MI') and
      CLIENT_ID in (1,54);

and by using this I am gathering stats for an hour. But I am going to need stats everyday for the same time for past 7 days.

I mean, from above query I am gathering between 10-NOV-2017 00:00 and 10-NOV-2017 01:00 and similarly I need to gather for 09-NOV-2017 00:00 to 09-NOV-2017 01:00 and so on for past 7 days.

And it should print like

  Date        | Count
+-------------+-------+
  10-NOV-2017 | 100
  09-NOV-2017 | 110

Is it achievable ?

Body:
try this

 SELECT to_char(START_TIME,'DD-MON-YY') date,
  count(*) count
FROM
  purchases
 WHERE
  START_TIME  >=TO_DATE('10-NOV-2017 00:01','DD-MON-YY HH24:MI') -7
AND START_TIME <TO_DATE('10-NOV-2017 00:02','DD-MON-YY HH24:MI')
AND CLIENT_ID IN (1,54)
 group by to_char(START_TIME,'DD-MON-YY') ;


问:
virtual directory address in web.config
My applications appSettings is located in a virtual directory called "Resources"

how to reference it in root web.config files <appSettings file="__??___">

Thanks

答:
try this:</p>

```<code><appSettings file="~/Resources/ResourceFile" />
</code>```

Title: virtual directory address in web.config

Body:
try this:

<appSettings file="~/Resources/ResourceFile" />


问:
VBA prevent closing of UserForm with "End" in code
In my spreadsheet, I have a UserForm that is supposed to be open at all times.

Once in a while, my code will contain an "End" where I exit the code based on some if statement.

The problem is that this closes the UserForm, is there a way to prevent this from happening?

EDIT:

```<code>Sub Test1()
    'Random code
    Call Test2(Variable)
    'Random code
End Sub

Sub Test2(ByVal Variable as Double)
    If Variable = 0 then
        'Random code
    End If
    If Variable = 1 then
        Call Test3
        End 'Original placement of End
    End If
End Sub

Sub Test3()
    'Random code
End Sub
</code>```

This is a rough example of how the code is build (its rather long at this point). So depending on the "variable" different things happen in Test2. But if the Variable is 1, then the "random code" back in Test1 can't be executed thus, so I have to stop the code. I tried replace "End" with "Exit Sub" this only stops the code in Test2 from running, is it will give me an error when it goes back to Test1.

EDIT2:
Test1() is actually four different subs (at this point, more will be added) that all call Test2(). That is why I choose to split it up into so many subs and call them from within the subs.

答:
You somehow need to tell Test1 that it needs to stop.  One approach to this problem is to change your subs to functions and return a value indicating status.  Something like this would work:</p>

```<code>Function Test1() As Integer
    Dim i As Integer

    'Random code
    i = Test2(Variable)
    If i = 1 Then Exit Function
    'Random code
End Function

Function Test2(ByVal Variable As Double) As Integer
    Test2 = 0

    If Variable = 0 Then
        'Random code
    End If
    If Variable = 1 Then
        Call Test3
        Test2 = 1
        Exit Function
    End If
End Function

Function Test3() As Integer
    'Random code
End Function
</code>```

Body:
In my spreadsheet, I have a UserForm that is supposed to be open at all times.

Once in a while, my code will contain an "End" where I exit the code based on some if statement.

The problem is that this closes the UserForm, is there a way to prevent this from happening?

EDIT:

Sub Test1()
    'Random code
    Call Test2(Variable)
    'Random code
End Sub

Sub Test2(ByVal Variable as Double)
    If Variable = 0 then
        'Random code
    End If
    If Variable = 1 then
        Call Test3
        End 'Original placement of End
    End If
End Sub

Sub Test3()
    'Random code
End Sub

This is a rough example of how the code is build (its rather long at this point). So depending on the "variable" different things happen in Test2. But if the Variable is 1, then the "random code" back in Test1 can't be executed thus, so I have to stop the code. I tried replace "End" with "Exit Sub" this only stops the code in Test2 from running, is it will give me an error when it goes back to Test1.

EDIT2:
Test1() is actually four different subs (at this point, more will be added) that all call Test2(). That is why I choose to split it up into so many subs and call them from within the subs.

Body:
You somehow need to tell Test1 that it needs to stop.  One approach to this problem is to change your subs to functions and return a value indicating status.  Something like this would work:

Function Test1() As Integer
    Dim i As Integer

    'Random code
    i = Test2(Variable)
    If i = 1 Then Exit Function
    'Random code
End Function

Function Test2(ByVal Variable As Double) As Integer
    Test2 = 0

    If Variable = 0 Then
        'Random code
    End If
    If Variable = 1 Then
        Call Test3
        Test2 = 1
        Exit Function
    End If
End Function

Function Test3() As Integer
    'Random code
End Function


问:
Read Free baggage from Sabre without WP
Is there  a way to read the free baggage for a   given flight without calling WP before calling

wp*bag

答:
If a WP is stored as a PQ it can be read from there.

If it's a ticketed PNR, the baggage allowance is on the e-ticket. It can be viewed with command WETR*2/E - Where "2" is the line number of the ticket in *T field.

Title: Read Free baggage from Sabre without WP


问:
GROUP BY with JOIN not giving correct result
How can I find the number of persons from each country

Person table

country_id, fName, lName

Countries table

country_id, country_name

I can find the number of persons from each country with their country IDs, using the below SQL statement

```<code>select
 p.country_id, COUNT(p.country_id) as [Count]
from
 persons p
GROUP BY
 p.country_id
</code>```

But what if I want to fetch country_name instead of country_id?
I tried this so far but it does not work as expected so I am missing something here.

```<code>select
    c.country_name, COUNT(p.country_id) as [Count]
from
    persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY
    p.country_id
</code>```

SQL Server 2000

答:
GROUP BY the columns in the SELECT:

```<code>SELECT c.country_name, COUNT(p.country_id) as [Count]
FROM persons p INNER JOIN
     countries c
     ON p.country_id = c.country_id
GROUP BY c.country_name;
</code>```

Notes:

Under some circumstances, you would want to include both the id and the name in the GROUP BY -- this would happen if two countries had the same name.

You can use COUNT(*) instead of COUNT(p.country_id).  There is no problem counting rows instead of NULL-values.

If you wanted all countries, even those without people, then you would use an outer JOIN:

```<code>SELECT c.country_name, COUNT(p.country_id) as [Count]
FROM countries c LEFT JOIN
     persons p
     ON p.country_id = c.country_id
GROUP BY c.country_name;
</code>```

Body:
How can I find the number of persons from each country

Person table

country_id, fName, lName

Countries table

country_id, country_name

I can find the number of persons from each country with their country IDs, using the below SQL statement

select
 p.country_id, COUNT(p.country_id) as [Count]
from
 persons p
GROUP BY
 p.country_id

But what if I want to fetch country_name instead of country_id?
I tried this so far but it does not work as expected so I am missing something here.

select
    c.country_name, COUNT(p.country_id) as [Count]
from
    persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY
    p.country_id

SQL Server 2000

Body:
GROUP BY the columns in the SELECT:

SELECT c.country_name, COUNT(p.country_id) as [Count]
FROM persons p INNER JOIN
     countries c
     ON p.country_id = c.country_id
GROUP BY c.country_name;

Notes:

Under some circumstances, you would want to include both the id and the name in the GROUP BY -- this would happen if two countries had the same name.

You can use COUNT(*) instead of COUNT(p.country_id).  There is no problem counting rows instead of NULL-values.

If you wanted all countries, even those without people, then you would use an outer JOIN:

SELECT c.country_name, COUNT(p.country_id) as [Count]
FROM countries c LEFT JOIN
     persons p
     ON p.country_id = c.country_id
GROUP BY c.country_name;


答:
You need to mention the column_name which is mentioned in select .

```<code>select
    c.country_name, COUNT(p.country_id) as [Count]
from
    persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY
    c.country_name
</code>```

Title: GROUP BY with JOIN not giving correct result

Body:
You need to mention the column_name which is mentioned in select .

select
    c.country_name, COUNT(p.country_id) as [Count]
from
    persons p INNER JOIN countries c ON p.country_id = c.country_id
GROUP BY
    c.country_name


问:
Get innerhtml from external page with Javascript
I'm trying to get innerHTML of a DIV that is located on external page. It is possible to do this using this kind javascript code?</p>

```<code>    <script type="text/javascript">
        $(document).ready(function(){
            var html = document.getElementById("glr1").src='/my_page.html'.innerHTML ;
            alert(html);
        });
    </script>
</code>```

答:
You could create a hidden  element, load the page into that, and then dive into it to locate your content.

```<code> $(function() {
   $('body').append($('<iframe></iframe>', {
     css: { display: none },
     src: 'my_page.html',
     id: 'my_mage',
     load: function() {
       var html = $('#my_page').contents().find('whatever').html();
     }
   });
 });
</code>```

Body:
You could create a hidden <iframe> element, load the page into that, and then dive into it to locate your content.

 $(function() {
   $('body').append($('<iframe></iframe>', {
     css: { display: none },
     src: 'my_page.html',
     id: 'my_mage',
     load: function() {
       var html = $('#my_page').contents().find('whatever').html();
     }
   });
 });


问:
Create pipe for angular2 for iterating JSON to array
I'm trying to use the following JSON data and convert it into an array, so I can run *ngFor='let item of items' and display data in terms of item.name etc...

I tried the following:

```<code>var out = [];
for(var key1 in object) {
    out[key1] = key1;
  for(var key2 in object[key1]) {
    for(var key3 in object[key2]) {
        out[key1][key2] = key3;
        }
  }
  console.log(out);
}
</code>```

But Im just getting the title as key and value.

```<code>var object = {
  "compressorClutch": {
    "name": "compressorClutch",
    "param": "Y",
    "register": "64",
    "type": "b"
  },
  "batteryLive": {
    "name": "batteryLive",
    "param": "Y",
    "register": "53",
    "type": "b"
  },
  "batteryGround": {
    "name": "batteryGround",
    "param": "Y",
    "register": "85",
    "type": "b"
  },
  "mainsCable": {
    "name": "mainsCable",
    "param": "N",
    "register": "",
    "type": "b"
  },
  "kcb": {
    "name": "kcb",
    "param": "13",
    "register": "337",
    "type": "i"
  },
  "config": "LorA-F"
}
</code>```

答:
Use Object.keys(object) to iterate over object's keys, it will return an array, and then use array's map method to iterate over this array of keys and return each item from the json object and assign it to a position in an array.</p>

```<code>const items = Object.keys(object).map( key => object[key] )
</code>```

Body:
I'm trying to use the following JSON data and convert it into an array, so I can run *ngFor='let item of items' and display data in terms of item.name etc...

I tried the following:

var out = [];
for(var key1 in object) {
    out[key1] = key1;
  for(var key2 in object[key1]) {
    for(var key3 in object[key2]) {
        out[key1][key2] = key3;
        }
  }
  console.log(out);
}

But Im just getting the title as key and value.

var object = {
  "compressorClutch": {
    "name": "compressorClutch",
    "param": "Y",
    "register": "64",
    "type": "b"
  },
  "batteryLive": {
    "name": "batteryLive",
    "param": "Y",
    "register": "53",
    "type": "b"
  },
  "batteryGround": {
    "name": "batteryGround",
    "param": "Y",
    "register": "85",
    "type": "b"
  },
  "mainsCable": {
    "name": "mainsCable",
    "param": "N",
    "register": "",
    "type": "b"
  },
  "kcb": {
    "name": "kcb",
    "param": "13",
    "register": "337",
    "type": "i"
  },
  "config": "LorA-F"
}

Body:
Use Object.keys(object) to iterate over object's keys, it will return an array, and then use array's map method to iterate over this array of keys and return each item from the json object and assign it to a position in an array.

const items = Object.keys(object).map( key => object[key] )


问:
How to update an "array of objects" with Firestore?
I'm currently trying Firestore, and I'm stuck at something very simple: "updating an array (aka a subdocument)".

My DB structure is super simple. For example:

```<code>proprietary: "John Doe",
sharedWith:
  [
    {who: "first@test.com", when:timestamp},
    {who: "another@test.com", when:timestamp},
  ],
</code>```

I'm trying (without success) to push new records into shareWith array of objects.

I've tried:

```<code>// With SET
firebase.firestore()
.collection('proprietary')
.doc(docID)
.set(
  { sharedWith: [{ who: "third@test.com", when: new Date() }] },
  { merge: true }
)

// With UPDATE
firebase.firestore()
.collection('proprietary')
.doc(docID)
.update({ sharedWith: [{ who: "third@test.com", when: new Date() }] })
</code>```

None works. These queries overwrite my array.

The answer might be simple, but I could'nt find it...

答:
Other than the answers mentioned above. This will do it.
Using Angular 5 and AngularFire2. or use firebase.firestore() instead of this.afs

```<code>  // say you have have the following object and
  // database structure as you mentioned in your post
  data = { who: "third@test.com", when: new Date() };

  ...othercode

  addSharedWith(data) {

    const postDocRef = this.afs.collection('posts').doc('docID');

    postDocRef.subscribe( post => {

      // Grab the existing sharedWith Array
      // If post.sharedWith doesn`t exsit initiated with empty array
      const foo = { 'sharedWith' : post.sharedWith || []};

      // Grab the existing sharedWith Array
      foo['sharedWith'].push(data);

      // pass updated to fireStore
      postsDocRef.update(foo);
      // using .set() will overwrite everything
      // .update will only update existing values,
      // so we initiated sharedWith with empty array
    });
 }
</code>```

Body:
I'm currently trying Firestore, and I'm stuck at something very simple: "updating an array (aka a subdocument)".

My DB structure is super simple. For example:

proprietary: "John Doe",
sharedWith:
  [
    {who: "first@test.com", when:timestamp},
    {who: "another@test.com", when:timestamp},
  ],

I'm trying (without success) to push new records into shareWith array of objects.

I've tried:

// With SET
firebase.firestore()
.collection('proprietary')
.doc(docID)
.set(
  { sharedWith: [{ who: "third@test.com", when: new Date() }] },
  { merge: true }
)

// With UPDATE
firebase.firestore()
.collection('proprietary')
.doc(docID)
.update({ sharedWith: [{ who: "third@test.com", when: new Date() }] })

None works. These queries overwrite my array.

The answer might be simple, but I could'nt find it...

Body:
Other than the answers mentioned above. This will do it.
Using Angular 5 and AngularFire2. or use firebase.firestore() instead of this.afs

  // say you have have the following object and
  // database structure as you mentioned in your post
  data = { who: "third@test.com", when: new Date() };

  ...othercode

  addSharedWith(data) {

    const postDocRef = this.afs.collection('posts').doc('docID');

    postDocRef.subscribe( post => {

      // Grab the existing sharedWith Array
      // If post.sharedWith doesn`t exsit initiated with empty array
      const foo = { 'sharedWith' : post.sharedWith || []};

      // Grab the existing sharedWith Array
      foo['sharedWith'].push(data);

      // pass updated to fireStore
      postsDocRef.update(foo);
      // using .set() will overwrite everything
      // .update will only update existing values,
      // so we initiated sharedWith with empty array
    });
 }


问:
Laravel 5.5 three table join
Edit: I am using API routes, so i have no views and such

I have a database like this

```<code>User:
   id
   name

card:
   id
   card_number
   user_id

swipe:
   id
   time
   card_number
</code>```

the relationships go as followed  user has one card one card has many swipe

the joins would be as such

```<code>user.id = card.user_id
card.card_number = swipe.card_number
</code>```

In Larvel i have 3 models.

```<code>user
card
swipe
</code>```

user Model

```<code>class user extends Model
{

    public function card()
    {
        return $this->hasOne('App\card','user_id','id');
    }

}
</code>```

in a controller if i do

```<code>$model = user::with('card')->get();
</code>```

i get the card data joined with the user data as expected.

```<code>class card extends Model
{

    public function person()
    {
       return $this->belongsTo('App\user');
    }

    public function swipe(){
        return $this->hasMany('App\swipe','card_number','card_number');
    }
}
</code>```

if i now do

$model = user::with('card.swipe')->get();

which i would expect to return all the users with their cards, and swipes associated to that card.

However what i get is

500 internal server error

What am i doing wrong here?

答:
You cant use like this,

```<code>user::with('card.swipe')->get();
</code>```

Use Has many Through

```<code>https://laravel.com/docs/5.5/eloquent-relationships#has-many-through

user - countries (in docs)
card - users (in docs)
swipe - posts (in docs)

$country->posts;
$user->swipe;
</code>```

Title: Laravel 5.5 three table join

Body:
Edit: I am using API routes, so i have no views and such

I have a database like this

User:
   id
   name

card:
   id
   card_number
   user_id

swipe:
   id
   time
   card_number

the relationships go as followed  user has one card one card has many swipe

the joins would be as such

user.id = card.user_id
card.card_number = swipe.card_number

In Larvel i have 3 models.

user
card
swipe

user Model

class user extends Model
{

    public function card()
    {
        return $this->hasOne('App\card','user_id','id');
    }

}

in a controller if i do

$model = user::with('card')->get();

i get the card data joined with the user data as expected.

class card extends Model
{

    public function person()
    {
       return $this->belongsTo('App\user');
    }

    public function swipe(){
        return $this->hasMany('App\swipe','card_number','card_number');
    }
}

if i now do

$model = user::with('card.swipe')->get();

which i would expect to return all the users with their cards, and swipes associated to that card.

However what i get is

500 internal server error

What am i doing wrong here?

Body:
You cant use like this,

user::with('card.swipe')->get();

Use Has many Through

https://laravel.com/docs/5.5/eloquent-relationships#has-many-through

user - countries (in docs)
card - users (in docs)
swipe - posts (in docs)

$country->posts;
$user->swipe;


问:
Convert date-time string to class Date
I have a data frame with a character column of date-times.

When I use as.Date, most of my strings are parsed correctly, except for a few instances.  The example below will hopefully show you what is going on.

```<code># my attempt to parse the string to Date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1,
                str_locate(prods.all$Date, " ")[1]-1),
                "%m/%d/%Y")

# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]
temp
#                    Date      Date2
# 1925  10/9/2009 0:00:00 2009-10-09
# 1926 10/15/2009 0:00:00 0200-10-15
</code>```

As you can see, the year of some of the dates is inaccurate.  The pattern seems to occur when the day is double digit.

Any help you can provide will be greatly appreciated.

答:
library(lubridate)
if your date format is like this '04/24/2017 05:35:00'then change it like below
prods.all$Date2<-gsub("/","-",prods.all$Date2)
 then change the date format
parse_date_time(prods.all$Date2, orders="mdy hms")

Title: Convert date-time string to class Date

Body:
I have a data frame with a character column of date-times.

When I use as.Date, most of my strings are parsed correctly, except for a few instances.  The example below will hopefully show you what is going on.

# my attempt to parse the string to Date -- uses the stringr package
prods.all$Date2 <- as.Date(str_sub(prods.all$Date, 1,
                str_locate(prods.all$Date, " ")[1]-1),
                "%m/%d/%Y")

# grab two rows to highlight my issue
temp <- prods.all[c(1925:1926), c(1,8)]
temp
#                    Date      Date2
# 1925  10/9/2009 0:00:00 2009-10-09
# 1926 10/15/2009 0:00:00 0200-10-15

As you can see, the year of some of the dates is inaccurate.  The pattern seems to occur when the day is double digit.

Any help you can provide will be greatly appreciated.


问:
Configure Apache Ignite in Docker Swarm Mode
I try to create a cluser of Apache Ignite in Docker Swarm mode. For some reason the service does not seem to pick up my configuration file. Any ideas of what I do wrong?

my docker compose file is like:

```<code>version: "3.3"
services:
  ignite:
    image: apacheignite/ignite
    environment:
      - "CONFIG_URI=file:///data/ignite/ignite.xml"
    configs:
      - source: ignite-config
        target: /data/ignite/ignite.xml
    #ports:
    #  - 8080:8080
    deploy:
      replicas: 1
configs:
  ignite-config:
    file: ./ignite.xml
</code>```

The ignite.xml looks like

```<code><?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">
    <bean abstract="true" id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">

        <!-- Explicitly configure TCP discovery SPI to provide list of initial nodes. -->
        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
                        <property name="addresses">
                            <list>
                                <value>tasks.ignite</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>
</code>```

The error I get from ignite (through docker service logs) is:

```<code>Failed to start grid: Failed to find configuration in: file:/data/ignite/ignite.xml
</code>```

答: The main problem here is that you have abstract="true" in org.apache.ignite.configuration.IgniteConfiguration bean definition in ignite.xml config file</p>

Body:
I try to create a cluser of Apache Ignite in Docker Swarm mode. For some reason the service does not seem to pick up my configuration file. Any ideas of what I do wrong?

my docker compose file is like:

version: "3.3"
services:
  ignite:
    image: apacheignite/ignite
    environment:
      - "CONFIG_URI=file:///data/ignite/ignite.xml"
    configs:
      - source: ignite-config
        target: /data/ignite/ignite.xml
    #ports:
    #  - 8080:8080
    deploy:
      replicas: 1
configs:
  ignite-config:
    file: ./ignite.xml

The ignite.xml looks like

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">
    <bean abstract="true" id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">

        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
                        <property name="addresses">
                            <list>
                                <value>tasks.ignite</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>

The error I get from ignite (through docker service logs) is:

Failed to start grid: Failed to find configuration in: file:/data/ignite/ignite.xml