问:
Ldap connection with Openstack could not find user : admin
I am confuring Ldap with openstack but when openstack send request to my ldap server, an error occured like could not find user: admin. Logs are below. Ldap server should send its information to my openstack environment. Is below warning important?

ldap_build_search_req ATTRS: cn userPassword enabled sn mail
  description

How can I handle this situation?

```<code>ldap_url_parse_ext(ldap://localhost/)
ldap_init: trying /etc/ldap/ldap.conf
ldap_init: using /etc/ldap/ldap.conf
ldap_init: HOME env is /var/lib/keystone
ldap_init: trying /var/lib/keystone/ldaprc
ldap_init: trying /var/lib/keystone/.ldaprc
ldap_init: trying ldaprc
ldap_init: LDAPCONF env is NULL
ldap_create
ldap_url_parse_ext(ldap://10.0.0.23)
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP 10.0.0.23:389
ldap_new_socket: 18
ldap_prepare_socket: 18
ldap_connect_to_host: Trying 10.0.0.23:389
ldap_pvt_connect: fd: 18 tm: -1 async: 0
attempting to connect:
connect success
ldap_open_defconn: successful
ldap_send_server_request
ldap_result ld 0x7f0e31c9b150 msgid 1
wait4msg ld 0x7f0e31c9b150 msgid 1 (infinite timeout)
wait4msg continue ld 0x7f0e31c9b150 msgid 1 all 1
** ld 0x7f0e31c9b150 Connections:
* host: 10.0.0.23  port: 389  (default)
  refcnt: 2  status: Connected
  last used: Thu Jun  1 12:11:40 2017

** ld 0x7f0e31c9b150 Outstanding Requests:
 * msgid 1,  origid 1, status InProgress
   outstanding referrals 0, parent count 0
  ld 0x7f0e31c9b150 request count 1 (abandoned 0)
** ld 0x7f0e31c9b150 Response Queue:
   Empty
  ld 0x7f0e31c9b150 response count 0
ldap_chkResponseList ld 0x7f0e31c9b150 msgid 1 all 1
ldap_chkResponseList returns ld 0x7f0e31c9b150 NULL
ldap_int_select
read1msg: ld 0x7f0e31c9b150 msgid 1 all 1
read1msg: ld 0x7f0e31c9b150 msgid 1 message type bind
read1msg: ld 0x7f0e31c9b150 0 new referrals
read1msg:  mark request completed, ld 0x7f0e31c9b150 msgid 1
request done: ld 0x7f0e31c9b150 msgid 1
res_errno: 0, res_error: <>, res_matched: <>
ldap_free_request (origid 1, msgid 1)
ldap_parse_result
ldap_msgfree
ldap_search_ext
put_filter: "(&(sn=admin)(objectClass=organizationalUnit)(cn=*))"
put_filter: AND
put_filter_list "(sn=admin)(objectClass=organizationalUnit)(cn=*)"
put_filter: "(sn=admin)"
put_filter: simple
put_simple_filter: "sn=admin"
put_filter: "(objectClass=organizationalUnit)"
put_filter: simple
put_simple_filter: "objectClass=organizationalUnit"
put_filter: "(cn=*)"
put_filter: simple
put_simple_filter: "cn=*"
ldap_build_search_req ATTRS: cn userPassword enabled sn mail description
ldap_send_initial_request
ldap_send_server_request
ldap_result ld 0x7f0e31c9b150 msgid 2
wait4msg ld 0x7f0e31c9b150 msgid 2 (infinite timeout)
wait4msg continue ld 0x7f0e31c9b150 msgid 2 all 1
** ld 0x7f0e31c9b150 Connections:
* host: 10.0.0.23  port: 389  (default)
  refcnt: 2  status: Connected
  last used: Thu Jun  1 12:11:40 2017

** ld 0x7f0e31c9b150 Outstanding Requests:
 * msgid 2,  origid 2, status InProgress
   outstanding referrals 0, parent count 0
  ld 0x7f0e31c9b150 request count 1 (abandoned 0)
** ld 0x7f0e31c9b150 Response Queue:
   Empty
  ld 0x7f0e31c9b150 response count 0
ldap_chkResponseList ld 0x7f0e31c9b150 msgid 2 all 1
ldap_chkResponseList returns ld 0x7f0e31c9b150 NULL
ldap_int_select
read1msg: ld 0x7f0e31c9b150 msgid 2 all 1
read1msg: ld 0x7f0e31c9b150 msgid 2 message type search-result
read1msg: ld 0x7f0e31c9b150 0 new referrals
read1msg:  mark request completed, ld 0x7f0e31c9b150 msgid 2
request done: ld 0x7f0e31c9b150 msgid 2
res_errno: 0, res_error: <>, res_matched: <>
ldap_free_request (origid 2, msgid 2)
ldap_parse_result
ldap_msgfree
2017-06-01 12:11:40.512893 2017-06-01 12:11:40.512 5767 WARNING keystone.auth.plugins.core [req-07b3f423-d9fd-419a-836c-2d59fb53ac9d - - - - -] Could not find user: admin
2017-06-01 12:11:40.513608 2017-06-01 12:11:40.513 5767 WARNING keystone.common.wsgi [req-07b3f423-d9fd-419a-836c-2d59fb53ac9d - - - - -] Authorization failed. Could not find user: admin (Disable insecure_debug mode to suppress these det$
</code>```

My keystone.ldap.conf like below

```<code>[identity]
driver = keystone.identity.backends.ldap.Identity
[assignment]
driver = keystone.assignment.backends.sql.Assignment
[ldap]
url = ldap://10.0.0.23
suffix = dc=openstack,dc=org
user = cn=admin,dc=openstack,dc=org
password = toor
user_tree_dn = ou=Users,dc=openstack,dc=org
user_objectclass = organizationalUnit
group_tree_dn = ou=Groups,dc=openstack,dc=org
group_objectclass = organizationalUnit
use_dumb_member = True
dumb_member = keystone_ldap
page_size = 0
alias_dereferencing = always
query_scope = sub
</code>```

EDIT: Ldap structure

```<code># openstack.org
dn: dc=openstack,dc=org
objectClass: top
objectClass: dcObject
objectClass: organization
o: openstack
dc: openstack

# admin, openstack.org
dn: cn=admin,dc=openstack,dc=org
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: admin
description: LDAP administrator

# Groups, openstack.org
dn: ou=Groups,dc=openstack,dc=org
objectClass: top
objectClass: organizationalUnit
ou: groups

# Users, openstack.org
dn: ou=Users,dc=openstack,dc=org
objectClass: top
objectClass: organizationalUnit
ou: users
</code>```

EDIT:
Inside keystone.conf I did not add any sn property but ldap always searching sn=admin as filter.

filter="(&(sn=admin)(objectClass=inetOrgPerson)(cn=*))"

Also I added ldap admin as user field of keystone.conf . Ldap searches this admin user inside user_tree but admin is not included user_tree. If someone knows working mechanism of keystone ldap, then problem could be easily solved.

答:
According to the below source code keystone adds filter

filter="(&(sn=admin)(objectClass=inetOrgPerson)(cn=*))"

if you do not specify user_name_attribute. Make

```<code>user_name_attribute=cn
</code>```

https://github.com/openstack/keystone/blob/master/keystone/conf/ldap.py

Body:
I am confuring Ldap with openstack but when openstack send request to my ldap server, an error occured like could not find user: admin. Logs are below. Ldap server should send its information to my openstack environment. Is below warning important?

ldap_build_search_req ATTRS: cn userPassword enabled sn mail
  description

How can I handle this situation?

ldap_url_parse_ext(ldap://localhost/)
ldap_init: trying /etc/ldap/ldap.conf
ldap_init: using /etc/ldap/ldap.conf
ldap_init: HOME env is /var/lib/keystone
ldap_init: trying /var/lib/keystone/ldaprc
ldap_init: trying /var/lib/keystone/.ldaprc
ldap_init: trying ldaprc
ldap_init: LDAPCONF env is NULL
ldap_create
ldap_url_parse_ext(ldap://10.0.0.23)
ldap_sasl_bind
ldap_send_initial_request
ldap_new_connection 1 1 0
ldap_int_open_connection
ldap_connect_to_host: TCP 10.0.0.23:389
ldap_new_socket: 18
ldap_prepare_socket: 18
ldap_connect_to_host: Trying 10.0.0.23:389
ldap_pvt_connect: fd: 18 tm: -1 async: 0
attempting to connect:
connect success
ldap_open_defconn: successful
ldap_send_server_request
ldap_result ld 0x7f0e31c9b150 msgid 1
wait4msg ld 0x7f0e31c9b150 msgid 1 (infinite timeout)
wait4msg continue ld 0x7f0e31c9b150 msgid 1 all 1
** ld 0x7f0e31c9b150 Connections:
* host: 10.0.0.23  port: 389  (default)
  refcnt: 2  status: Connected
  last used: Thu Jun  1 12:11:40 2017

** ld 0x7f0e31c9b150 Outstanding Requests:
 * msgid 1,  origid 1, status InProgress
   outstanding referrals 0, parent count 0
  ld 0x7f0e31c9b150 request count 1 (abandoned 0)
** ld 0x7f0e31c9b150 Response Queue:
   Empty
  ld 0x7f0e31c9b150 response count 0
ldap_chkResponseList ld 0x7f0e31c9b150 msgid 1 all 1
ldap_chkResponseList returns ld 0x7f0e31c9b150 NULL
ldap_int_select
read1msg: ld 0x7f0e31c9b150 msgid 1 all 1
read1msg: ld 0x7f0e31c9b150 msgid 1 message type bind
read1msg: ld 0x7f0e31c9b150 0 new referrals
read1msg:  mark request completed, ld 0x7f0e31c9b150 msgid 1
request done: ld 0x7f0e31c9b150 msgid 1
res_errno: 0, res_error: <>, res_matched: <>
ldap_free_request (origid 1, msgid 1)
ldap_parse_result
ldap_msgfree
ldap_search_ext
put_filter: "(&(sn=admin)(objectClass=organizationalUnit)(cn=*))"
put_filter: AND
put_filter_list "(sn=admin)(objectClass=organizationalUnit)(cn=*)"
put_filter: "(sn=admin)"
put_filter: simple
put_simple_filter: "sn=admin"
put_filter: "(objectClass=organizationalUnit)"
put_filter: simple
put_simple_filter: "objectClass=organizationalUnit"
put_filter: "(cn=*)"
put_filter: simple
put_simple_filter: "cn=*"
ldap_build_search_req ATTRS: cn userPassword enabled sn mail description
ldap_send_initial_request
ldap_send_server_request
ldap_result ld 0x7f0e31c9b150 msgid 2
wait4msg ld 0x7f0e31c9b150 msgid 2 (infinite timeout)
wait4msg continue ld 0x7f0e31c9b150 msgid 2 all 1
** ld 0x7f0e31c9b150 Connections:
* host: 10.0.0.23  port: 389  (default)
  refcnt: 2  status: Connected
  last used: Thu Jun  1 12:11:40 2017

** ld 0x7f0e31c9b150 Outstanding Requests:
 * msgid 2,  origid 2, status InProgress
   outstanding referrals 0, parent count 0
  ld 0x7f0e31c9b150 request count 1 (abandoned 0)
** ld 0x7f0e31c9b150 Response Queue:
   Empty
  ld 0x7f0e31c9b150 response count 0
ldap_chkResponseList ld 0x7f0e31c9b150 msgid 2 all 1
ldap_chkResponseList returns ld 0x7f0e31c9b150 NULL
ldap_int_select
read1msg: ld 0x7f0e31c9b150 msgid 2 all 1
read1msg: ld 0x7f0e31c9b150 msgid 2 message type search-result
read1msg: ld 0x7f0e31c9b150 0 new referrals
read1msg:  mark request completed, ld 0x7f0e31c9b150 msgid 2
request done: ld 0x7f0e31c9b150 msgid 2
res_errno: 0, res_error: <>, res_matched: <>
ldap_free_request (origid 2, msgid 2)
ldap_parse_result
ldap_msgfree
2017-06-01 12:11:40.512893 2017-06-01 12:11:40.512 5767 WARNING keystone.auth.plugins.core [req-07b3f423-d9fd-419a-836c-2d59fb53ac9d - - - - -] Could not find user: admin
2017-06-01 12:11:40.513608 2017-06-01 12:11:40.513 5767 WARNING keystone.common.wsgi [req-07b3f423-d9fd-419a-836c-2d59fb53ac9d - - - - -] Authorization failed. Could not find user: admin (Disable insecure_debug mode to suppress these det$

My keystone.ldap.conf like below

[identity]
driver = keystone.identity.backends.ldap.Identity
[assignment]
driver = keystone.assignment.backends.sql.Assignment
[ldap]
url = ldap://10.0.0.23
suffix = dc=openstack,dc=org
user = cn=admin,dc=openstack,dc=org
password = toor
user_tree_dn = ou=Users,dc=openstack,dc=org
user_objectclass = organizationalUnit
group_tree_dn = ou=Groups,dc=openstack,dc=org
group_objectclass = organizationalUnit
use_dumb_member = True
dumb_member = keystone_ldap
page_size = 0
alias_dereferencing = always
query_scope = sub

EDIT: Ldap structure

# openstack.org
dn: dc=openstack,dc=org
objectClass: top
objectClass: dcObject
objectClass: organization
o: openstack
dc: openstack

# admin, openstack.org
dn: cn=admin,dc=openstack,dc=org
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: admin
description: LDAP administrator

# Groups, openstack.org
dn: ou=Groups,dc=openstack,dc=org
objectClass: top
objectClass: organizationalUnit
ou: groups

# Users, openstack.org
dn: ou=Users,dc=openstack,dc=org
objectClass: top
objectClass: organizationalUnit
ou: users

EDIT:
Inside keystone.conf I did not add any sn property but ldap always searching sn=admin as filter.

filter="(&(sn=admin)(objectClass=inetOrgPerson)(cn=*))"

Also I added ldap admin as user field of keystone.conf . Ldap searches this admin user inside user_tree but admin is not included user_tree. If someone knows working mechanism of keystone ldap, then problem could be easily solved.

Body:
According to the below source code keystone adds filter

filter="(&(sn=admin)(objectClass=inetOrgPerson)(cn=*))"

if you do not specify user_name_attribute. Make

user_name_attribute=cn

https://github.com/openstack/keystone/blob/master/keystone/conf/ldap.py


来源: stackexchange

问:
not need to use Viewstate to retain state in asp.net?
I saw some code using Viewstate to retain state between user requests, below is the code to use a button to increment the number in a textbox input:

```<code>public partial class WebForm1 : System.Web.UI.Page
{
    int ClicksCount = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "0";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if(ViewState["Clicks"] != null)
        {
            ClicksCount = (int)ViewState["Clicks"] + 1;
        }
        TextBox1.Text = ClicksCount.ToString(); ;
        ViewState["Clicks"] = ClicksCount;
    }
}
</code>```

But I don't need to use Viewstate to achieve the same goal, and it is much more simple, here is my code:

```<code>public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TextBox1.Text = "0";
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int i = Int32.Parse(TextBox1.Text);
            i++;
            TextBox1.Text = i.ToString();
        }
    }
</code>```

so what's wrong with my code

答: There is nothing wrong with your code: the contents of the ASP.NET controls (as is the TextBox1 in your example) are already integrated in the ViewState automatically, and hence there is no need to manually enter them. You would use directly the ViewState to store anything that is not part of your design components (for instance an int variable that you want to increase each time).

ContentLicense: CC BY-SA 3.0

Body:
I saw some code using Viewstate to retain state between user requests, below is the code to use a button to increment the number in a textbox input:

public partial class WebForm1 : System.Web.UI.Page
{
    int ClicksCount = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = "0";
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        if(ViewState["Clicks"] != null)
        {
            ClicksCount = (int)ViewState["Clicks"] + 1;
        }
        TextBox1.Text = ClicksCount.ToString(); ;
        ViewState["Clicks"] = ClicksCount;
    }
}

But I don't need to use Viewstate to achieve the same goal, and it is much more simple, here is my code:

public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TextBox1.Text = "0";
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            int i = Int32.Parse(TextBox1.Text);
            i++;
            TextBox1.Text = i.ToString();
        }
    }

so what's wrong with my code


问:
How to implement vanity URLs in a legacy Flask app?
I'm facing a problem where I need to redirect or replace existing URLs in a legacy Flask app to a more "vanity" URL scheme.

For instance:

www.example.org/camp -> really points to https://example.org/connect/rally_camps/register

While I managed to make this work using nginx config (this is using the typical uwsgi + reverse proxy nginx config to be serverd):

```<code>location /camp {
       rewrite ^/.* https://example.org/connect/rally_camps/register permanent;
}
</code>```

When I hit the vanity URL I'm redirected to the non-vanity URL (long one). This obviously looks ugly...I'm not sure if there is a way to tell nginx to redirect but keep the same URL or this is something that requires some Flask work...301 redirects when user hits vanity URL to long URL maybe? But I think this will change URL again...any ideas?

Thanks!

答:
Assuming you don't need to capture whatever comes after /camp/, this nginx configuration should do it:

```<code>location /camp {
       rewrite ^/.* /connect/rally_camps/register ;
}
</code>```

From the nginx docs for rewrite:

If a replacement string starts with “http://”, “https://”, or “$scheme”, the processing stops and the redirect is returned to a client.

In other words, if you don't want a redirect, the replacement string cannot start with any of these prefixes.

The permanent flag also yields a redirect, so you can't use that either.

Body:
I'm facing a problem where I need to redirect or replace existing URLs in a legacy Flask app to a more "vanity" URL scheme.

For instance:

www.example.org/camp -> really points to https://example.org/connect/rally_camps/register

While I managed to make this work using nginx config (this is using the typical uwsgi + reverse proxy nginx config to be serverd):

location /camp {
       rewrite ^/.* https://example.org/connect/rally_camps/register permanent;
}

When I hit the vanity URL I'm redirected to the non-vanity URL (long one). This obviously looks ugly...I'm not sure if there is a way to tell nginx to redirect but keep the same URL or this is something that requires some Flask work...301 redirects when user hits vanity URL to long URL maybe? But I think this will change URL again...any ideas?

Thanks!

Body:
Assuming you don't need to capture whatever comes after /camp/, this nginx configuration should do it:

location /camp {
       rewrite ^/.* /connect/rally_camps/register ;
}

From the nginx docs for rewrite:

If a replacement string starts with “http://”, “https://”, or “$scheme”, the processing stops and the redirect is returned to a client.

In other words, if you don't want a redirect, the replacement string cannot start with any of these prefixes.

The permanent flag also yields a redirect, so you can't use that either.


问:
My increment doesn't work (c)
So, I have this code, at end I have an increment for exit when it reaches 4 (4 times wrong value entered), but it doesn't work:

```<code>int main() {
  int nej;
  printf("1-Triangulo \n");
  printf("2-Division \n");
  printf("3-Menu \n");
  printf("4-Bosque \n");
  printf("0-Salir \n");
  scanf("%d", &nej);
  if (nej == 1) {
    // Ejercicio 1-Triangulo:

    triangulo();
  }

  if (nej == 2) {
    // Ejercicio 2-Division:

    division();
  }

  if (nej == 3) {
    menu();
  }

  if (nej == 4) {
    arboles();
  }

  if (nej == 0) {
    // Salida
    exit(1);
  }

  int nerr = 0;

  while (nej < 0 || nej > 4) {
    nerr++;
    // Contador de error
    if (nerr == 4) {
      exit(1);
    }
  }
}
</code>```

How to fix this?

答:
It have following errors:

Code should be in the while loop

Variable nerr should be declared and initialize outside the while loop

Variable nerr should control the while loop

Note: It is Ok to use multiple if. But use of switch is much convenient and advisable.

Corrected code is as following:

```<code> int main() {
   int nej;
   int nerr = 0;
   while (nerr < 4) {
   printf("1-Triangulo \n");
   printf("2-Division \n");
   printf("3-Menu \n");
   printf("4-Bosque \n");
   printf("0-Salir \n");
   scanf("%d", &nej);

   switch(nej){
   case 1:// Ejercicio 1-Triangulo:
     triangulo();
   break;
   case 2:// Ejercicio 2-Division:
     division();
   break;
   case 3:
     menu();
   break;
   case 4:
     arboles();
   break;
   case 0:// Salida
     exit(1);
   break;
   default:
     nerr++;
   }
     // Reset 'nerr' if any valid vaue is entered by user
     if ((nej >= 0) && (nej <= 4)) {
       nerr = 0;
     }
   }
 }
</code>```

Title: My increment doesn't work (c)

Body:
So, I have this code, at end I have an increment for exit when it reaches 4 (4 times wrong value entered), but it doesn't work:

int main() {
  int nej;
  printf("1-Triangulo \n");
  printf("2-Division \n");
  printf("3-Menu \n");
  printf("4-Bosque \n");
  printf("0-Salir \n");
  scanf("%d", &nej);
  if (nej == 1) {
    // Ejercicio 1-Triangulo:

    triangulo();
  }

  if (nej == 2) {
    // Ejercicio 2-Division:

    division();
  }

  if (nej == 3) {
    menu();
  }

  if (nej == 4) {
    arboles();
  }

  if (nej == 0) {
    // Salida
    exit(1);
  }

  int nerr = 0;

  while (nej < 0 || nej > 4) {
    nerr++;
    // Contador de error
    if (nerr == 4) {
      exit(1);
    }
  }
}

How to fix this?

Body:
It have following errors:

Code should be in the while loop

Variable nerr should be declared and initialize outside the while loop

Variable nerr should control the while loop

Note: It is Ok to use multiple if. But use of switch is much convenient and advisable.

Corrected code is as following:

 int main() {
   int nej;
   int nerr = 0;
   while (nerr < 4) {
   printf("1-Triangulo \n");
   printf("2-Division \n");
   printf("3-Menu \n");
   printf("4-Bosque \n");
   printf("0-Salir \n");
   scanf("%d", &nej);

   switch(nej){
   case 1:// Ejercicio 1-Triangulo:
     triangulo();
   break;
   case 2:// Ejercicio 2-Division:
     division();
   break;
   case 3:
     menu();
   break;
   case 4:
     arboles();
   break;
   case 0:// Salida
     exit(1);
   break;
   default:
     nerr++;
   }
     // Reset 'nerr' if any valid vaue is entered by user
     if ((nej >= 0) && (nej <= 4)) {
       nerr = 0;
     }
   }
 }


问:
Need Help regarding backup css
I need your help.

My website css has been crashed due to suddenly power supply off and next while I saw css, CSS was cleaned totally.
Anyone suggest me How can I get them again?

Thanks in advance.

答:
CSS Style sheets are usually just files alongside the other content. It's hard to believe the site is there, but they are missing.

Check whether the paths are all in order. Try to physically locate the style sheet files first.

ContentLicense: CC BY-SA 2.5

Title: Need Help regarding backup css


问:
Install Sonatype Nexus 2 as a service
I'd like to know how to install Sonatype Nexus 2 as a service on GNU/Linux in order to get it configured properly and started automatically at startup.</p>

答:
For Nexus 2 documentation is at

https://books.sonatype.com/nexus-book/reference/install-sect-service.html

for Nexus 3 it is at

https://books.sonatype.com/nexus-book/reference3/install.html#service-linux

The recommendations differ. One example is instead of copying nexus start script, use sym link

```<code>sudo ln -s $NEXUS_HOME/bin/nexus /etc/init.d/nexus
</code>```

Title: Install Sonatype Nexus 2 as a service

Body:
For Nexus 2 documentation is at

https://books.sonatype.com/nexus-book/reference/install-sect-service.html

for Nexus 3 it is at

https://books.sonatype.com/nexus-book/reference3/install.html#service-linux

The recommendations differ. One example is instead of copying nexus start script, use sym link

sudo ln -s $NEXUS_HOME/bin/nexus /etc/init.d/nexus


问:
Generate chained setters
I want to create a big Java object with 20 fileds, most of IDE's provide a generate function, wich allows me to generate getters and setters for all the fiels of my object.

The thing is, I am a big fan of method chaining and I am using it on all my objects, but I have to add return this at the end of each setters, which is not very handy.

Is it possible to generate setters with a special plugin form an IDE ?

答:
You can try lombok

lombok.accessors.chain = [true | false] (default: false)

If set to true, generated setters will return this (instead of void). An explicitly configured chain parameter of an @Accessors annotation takes precedence over this setting.

Is this what you want ?
https://projectlombok.org/features/GetterSetter.html

```<code>@Accessors(chain = true)
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor(access=AccessLevel.PRIVATE)

public class LombokTest {
    private String test;

    public static void main(String []args) {
        LombokTest a = new LombokTest();
        System.out.println(a.setTest("amber").getTest());
    }
}
</code>```

Title: Generate chained setters

Body:
You can try lombok

lombok.accessors.chain = [true | false] (default: false)

If set to true, generated setters will return this (instead of void). An explicitly configured chain parameter of an @Accessors annotation takes precedence over this setting.

Is this what you want ?
https://projectlombok.org/features/GetterSetter.html

@Accessors(chain = true)
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor(access=AccessLevel.PRIVATE)

public class LombokTest {
    private String test;

    public static void main(String []args) {
        LombokTest a = new LombokTest();
        System.out.println(a.setTest("amber").getTest());
    }
}


问:
Setting large json file to Firebase with specific key for each item
Keen for your advice on the best approach. I have a large json file that I want to set to firebase that currently has array of items like below:

```<code>{
"features": [
    {
        "properties": {
            "key": "2345345",
            "data1": "data",
            "data2": "data",
            "data3": "data"
        }
    },
    {
        "properties": {
            "key": "3455647",
            "data1": "data",
            "data2": "data",
            "data3": "data"
        }
    }
]
}
</code>```

However, firebase will auto generate a key for each object. I would like to be able to set the key myself, using the key in the properties so it would look like this:

```<code>{
"features": {
   "2345345": {
        "properties": {
            "key": "2345345",
            "data1": "data",
            "data2": "data",
            "data3": "data"
        }
    },
    "3455647": {
        "properties": {
            "key": "3455647",
            "data1": "data",
            "data2": "data",
            "data3": "data"
        }
    }
}
}
</code>```

It is for an Angular 2 web project using angularfire2.

What would be the best way to achieve this? I don't have control over the way the data is generated.

答:
Loop through the array and change it to an object.

```<code>let obj = {features: [...]};

var new_features = {};
for(var i=0; i<obj.features.length; i++) {
    var key = ... // <- create your own key here
    new_features[key] = obj.features[0];
}
obj.features = new_features;
const items = db.object('/features');
items.set(obj);
</code>```

OR set each object separately (involves more calls)

```<code>for(var i=0; i<obj.features.length; i++) {
    var key = ... // <- create your own key here
    const items = db.object('/features/' + key);
    items.set(obj.features[0]);
}
</code>```

Body:
Keen for your advice on the best approach. I have a large json file that I want to set to firebase that currently has array of items like below:

{
"features": [
    {
        "properties": {
            "key": "2345345",
            "data1": "data",
            "data2": "data",
            "data3": "data"
        }
    },
    {
        "properties": {
            "key": "3455647",
            "data1": "data",
            "data2": "data",
            "data3": "data"
        }
    }
]
}

However, firebase will auto generate a key for each object. I would like to be able to set the key myself, using the key in the properties so it would look like this:

{
"features": {
   "2345345": {
        "properties": {
            "key": "2345345",
            "data1": "data",
            "data2": "data",
            "data3": "data"
        }
    },
    "3455647": {
        "properties": {
            "key": "3455647",
            "data1": "data",
            "data2": "data",
            "data3": "data"
        }
    }
}
}

It is for an Angular 2 web project using angularfire2.

What would be the best way to achieve this? I don't have control over the way the data is generated.

Body:
Loop through the array and change it to an object.

let obj = {features: [...]};

var new_features = {};
for(var i=0; i<obj.features.length; i++) {
    var key = ... // <- create your own key here
    new_features[key] = obj.features[0];
}
obj.features = new_features;
const items = db.object('/features');
items.set(obj);

OR set each object separately (involves more calls)

for(var i=0; i<obj.features.length; i++) {
    var key = ... // <- create your own key here
    const items = db.object('/features/' + key);
    items.set(obj.features[0]);
}


问:
Android new Intent with back button
In my Android App I use an empty activity with one button. If I push the button I call a new activity with an intent. But on the new activity the back button (top left) to jump back to the last page is missing. Isn't there already a activity template from android studio or a spezial intent call to do this? Or what is the best way to do this?

This is the function which is called on the button press

```<code>void scanClicked(View v){
    Intent intent = new Intent(this, ServiceActivity.class);
    startActivity(intent);
}
</code>```

The ServiceActivity is just an Empty Activity

```<code>    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/SplashTheme"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NavigationActivity"
        android:label="@string/title_activity_navigation"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ServiceActivity"
        android:label="@string/annualServiceTitle">
    </activity>
</code>```

答:
This is based on your app theme defining in styles.xml file.

If you are using DarkActionBar theme as you said, you just need to add android:parentActivityName="fronius.com.serviceapp_frontend.NavigationActivity"
 in your manifest file.

But if you are using NoActionBar theme to use toolbar in your activities (as mentioned in Material Design) you have to add this line of code to visible up navigation button in your activity in addition to specify parentActivityName:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

 Also you can change the up navigation button icon by this line of code:
               getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_back);

Title: Android new Intent with back button

Body:
In my Android App I use an empty activity with one button. If I push the button I call a new activity with an intent. But on the new activity the back button (top left) to jump back to the last page is missing. Isn't there already a activity template from android studio or a spezial intent call to do this? Or what is the best way to do this?

This is the function which is called on the button press

void scanClicked(View v){
    Intent intent = new Intent(this, ServiceActivity.class);
    startActivity(intent);
}

The ServiceActivity is just an Empty Activity

    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:theme="@style/SplashTheme"
        android:windowSoftInputMode="adjustPan">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".NavigationActivity"
        android:label="@string/title_activity_navigation"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ServiceActivity"
        android:label="@string/annualServiceTitle">
    </activity>


问:
How to properly clone a jsPlumb draggable
I am using the latest community edition of jsPlumb.  I am trying to enable drag-n-drop of items from a toolbox into a jsPlumb diagram.

```<code>jsPlumb.draggable('decision', {
  clone: true,
  grid:[10,10]
});
</code>```

I can start draggin but when I drop the element into the jsPlumb Container I get the following error

jsPlumb function failed : TypeError: Cannot read property 'el' of undefined

What am I doing wrong?

答:
You can use this:</p>

```<code>jsPlumb.draggable(clone, { containment:'decision'});
</code>```

Body:
I am using the latest community edition of jsPlumb.  I am trying to enable drag-n-drop of items from a toolbox into a jsPlumb diagram.

jsPlumb.draggable('decision', {
  clone: true,
  grid:[10,10]
});

I can start draggin but when I drop the element into the jsPlumb Container I get the following error

jsPlumb function failed : TypeError: Cannot read property 'el' of undefined

What am I doing wrong?

Body:
You can use this:

jsPlumb.draggable(clone, { containment:'decision'});


问:
WPF - Access the parent Control from inside a Style Setter ControlTemplate
When making controls non-amendable we display them as a TextBox to keep a consistent style. The problem is that a ComboBox can have any type of data so binding the Text property of the ControlTemplate TextBox is not as simple as using SelectedItem.

```<code><Style TargetType="{x:Type ComboBox}">
        <Style.Triggers>
            <Trigger Property="IsReadOnly" Value="True">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type ComboBox}}, Path=????, Converter={StaticResource ResourceKey=ComboToTextConverter}, UpdateSourceTrigger=PropertyChanged}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</code>```

The idea I have is to use a Converter and send the whole ComboBox so it can be handled by the Converter code. Is there anyway to do this?

Any other suggestions are welcome!

答:
you need to use the SelectedValue and SelectedValuePath properties:

```<code><Style TargetType="ComboBox" x:Key="cStyle">
<Style.Triggers>
  <Trigger Property="IsReadOnly" Value="True">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ComboBox">
          <TextBox Text="{Binding RelativeSource=
                   {RelativeSource TemplatedParent},
                   Path=SelectedValue}" />
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Trigger>
</Style.Triggers>
</code>```

and heres your ComboBox

```<code><ComboBox Name="cbox" ItemsSource="{Binding}"
        Style="{StaticResource cStyle}"
        SelectedValuePath="SomeText"
        DisplayMemberPath="SomeText" />
</code>```

now when you set the IsReadOnly property to true on the ComboBox, it turns into a TextBox with the selected value as its text.

Body:
When making controls non-amendable we display them as a TextBox to keep a consistent style. The problem is that a ComboBox can have any type of data so binding the Text property of the ControlTemplate TextBox is not as simple as using SelectedItem.

    </Style>

The idea I have is to use a Converter and send the whole ComboBox so it can be handled by the Converter code. Is there anyway to do this?

Any other suggestions are welcome!

Body:
you need to use the SelectedValue and SelectedValuePath properties:

<Style TargetType="ComboBox" x:Key="cStyle">
<Style.Triggers>
  <Trigger Property="IsReadOnly" Value="True">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ComboBox">
          <TextBox Text="{Binding RelativeSource=
                   {RelativeSource TemplatedParent},
                   Path=SelectedValue}" />
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Trigger>
</Style.Triggers>

and heres your ComboBox

<ComboBox Name="cbox" ItemsSource="{Binding}"
        Style="{StaticResource cStyle}"
        SelectedValuePath="SomeText"
        DisplayMemberPath="SomeText" />

now when you set the IsReadOnly property to true on the ComboBox, it turns into a TextBox with the selected value as its text.


问:
Get The First Event From More Than One Generator
I have three generators. Each one yields results/events in chronological order.

What I want to be able to do is figure out which of the three generators has the next (chronological) event.
One way that I though of is to have a list of one event from each generator, and which generator it came from. Then, sort the list, take the first event, and add the next event from the corresponding generator to my list.

Is there a better/more efficient/standard way of dealing with this problem?

答:
Since you did not give a concrete example I can only provide some ideas/pseudocode for you. The idea is to hold at most n items from n iterators in memory since each iterator yields chronologically sorted objects. Also inserting into/getting from a PriorityQueue will be faster than sorting a list over and over again.

```<code>from Queue import PriorityQueue

def yield_chronologically(iterators):
    'iterators: list of iterator objects'
    PQ = PriorityQueue()

    # put first n items
    for i, it in enumerate(iterators):
        try:
            nxt = next(it)
            # this is where you have to determine the priority
            # with a function get_chronological_key you have yet to write
            chronological_key = get_chronological_key(nxt)
            PQ.put(chronological_key, (i, nxt))
        except StopIteration:
            pass

    # yield items and insert next item from iterator that was taken from
    # into the PQ
    while not PQ.empty():
        _, (i, nxt) = PQ.get()
        yield nxt
        try:
            nxt = next(iterators[i])
            chronological_key = get_chronological_key(nxt)
            PQ.put(chronological_key, (i, nxt))
        except StopIteration:
            pass
</code>```

Body:
Since you did not give a concrete example I can only provide some ideas/pseudocode for you. The idea is to hold at most n items from n iterators in memory since each iterator yields chronologically sorted objects. Also inserting into/getting from a PriorityQueue will be faster than sorting a list over and over again.

from Queue import PriorityQueue

def yield_chronologically(iterators):
    'iterators: list of iterator objects'
    PQ = PriorityQueue()

    # put first n items
    for i, it in enumerate(iterators):
        try:
            nxt = next(it)
            # this is where you have to determine the priority
            # with a function get_chronological_key you have yet to write
            chronological_key = get_chronological_key(nxt)
            PQ.put(chronological_key, (i, nxt))
        except StopIteration:
            pass

    # yield items and insert next item from iterator that was taken from
    # into the PQ
    while not PQ.empty():
        _, (i, nxt) = PQ.get()
        yield nxt
        try:
            nxt = next(iterators[i])
            chronological_key = get_chronological_key(nxt)
            PQ.put(chronological_key, (i, nxt))
        except StopIteration:
            pass


问:
How to post value from one php page to another using ajax
I am trying to post one value which I got using Jquery, so I have to pass that value to php page using ajax. but when I did this I got Undefined index data error.

Here is my code:

```<code>$("#requirementtable tbody tr").on("click", function(){
                        desc =  $(this).closest("tr").find("td:nth-child(4)").text().trim();
$.ajax({
        type:"POST",
        url:"get_diagnosis.php",
        data: desc,
        success: function (data, textStatus, jqXHR)
        {
            alert(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert("some error occured->" + jqXHR.responseJSON);
        }
    })
  })
</code>```

this is my php code:

```<code><?php
    $data = $_POST['data'];
    echo $data;
?>
</code>```

答:
Replace the followings:

```<code>desc =  $(this).closest("tr").find("td:nth-child(4)").text().trim();
//        remove ^^^^^^^^^^ since you're currently in tr click
desc =  $(this).find("td:nth-child(4)").text().trim();
</code>```

And replace to:

```<code>data: desc,
</code>```

With:

```<code>data: {data:desc}, //to pass data as object as you don't have serialized data
</code>```

And inside your php code, you can get data using $_POST['data'].

Body:
I am trying to post one value which I got using Jquery, so I have to pass that value to php page using ajax. but when I did this I got Undefined index data error.

Here is my code:

$("#requirementtable tbody tr").on("click", function(){
                        desc =  $(this).closest("tr").find("td:nth-child(4)").text().trim();
$.ajax({
        type:"POST",
        url:"get_diagnosis.php",
        data: desc,
        success: function (data, textStatus, jqXHR)
        {
            alert(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert("some error occured->" + jqXHR.responseJSON);
        }
    })
  })

this is my php code:

<?php
    $data = $_POST['data'];
    echo $data;
?>

Body:
Replace the followings:

desc =  $(this).closest("tr").find("td:nth-child(4)").text().trim();
//        remove ^^^^^^^^^^ since you're currently in tr click
desc =  $(this).find("td:nth-child(4)").text().trim();

And replace to:

data: desc,

With:

data: {data:desc}, //to pass data as object as you don't have serialized data

And inside your php code, you can get data using $_POST['data'].


问:
DRF: Serializer validation while submitting a POST request to detail route
DRF newbie here. I have the following model:

```<code>class User(models.Model):

    first_name = models.CharField(max_length=30, null=True, blank=True)
    last_name = models.CharField(max_length=30, null=True, blank=True)

    email = models.EmailField(max_length=254, null=False, blank=False, unique=True)
    password = models.CharField(max_length=128, null=False, blank=False)
</code>```

I've managed to implement POST /users/ successfully. I'm able to validate password and email fields in the request body against pre-defined constraints.(e.g. password cannot be entirely numeric) For this purpose, I override field validators such as validate_password and validate_email.

Now I'm trying to implement an endpoint POST /users/pk/password/ through which users will be able to update their password resource. To achieve this I've used detail_route. Below you can find the corresponding implementation:

```<code># Custom method to update the password resource of a given user.
@detail_route(methods=['post'])
def password(self, request, pk=None):

    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        # returns error
    else:

        password = request.data.get('password',None)
        new_password = request.data.get('new_password',None)

        if password and new_password:

            if check_password(password,user.password):

                # Use Django built-in to hash password.
                password_hash =  make_password(new_password)
                user.password = password_hash
                user.save()

                serializer_data = UserSerializer(user).data

                return Response(serializer_data)

            else:
                # return error reponse
        else:
            # return error response
</code>```

By using this approach, I'm able to update the password field of a user but validate_password is not effective anymore when POST /users/pk/password/ is called so that users can update their password with an entirely numeric one.

I'm aware of the fact that I can try to implement validate_password inside the detail route implementation, but it does not feel like the best way to go.

My question is what is the best way to do this without duplicating code and without moving validation logic into views.py?

PS: I cannot use nor extend Django User model for various reasons.

Thanks!

答:
This the problem, you are getting the data straight off the raw post, when you are supposed to be using the serializer

```<code>    password = request.data.get('password',None)
    new_password = request.data.get('new_password',None)
</code>```

Now assuming your serializer with the validation code is called MySerializer, the above lines need to be replaced with something like

```<code>   serial = MySerializer(data=request.data)
   if serial.is_valid():
       password = serial.validated_data['password']
       new_password = serial.validated_data['new_password']
</code>```

Now your validation code will be executed.

Body:
DRF newbie here. I have the following model:

class User(models.Model):

    first_name = models.CharField(max_length=30, null=True, blank=True)
    last_name = models.CharField(max_length=30, null=True, blank=True)

    email = models.EmailField(max_length=254, null=False, blank=False, unique=True)
    password = models.CharField(max_length=128, null=False, blank=False)

I've managed to implement POST /users/ successfully. I'm able to validate password and email fields in the request body against pre-defined constraints.(e.g. password cannot be entirely numeric) For this purpose, I override field validators such as validate_password and validate_email.

Now I'm trying to implement an endpoint POST /users/pk/password/ through which users will be able to update their password resource. To achieve this I've used detail_route. Below you can find the corresponding implementation:

# Custom method to update the password resource of a given user.
@detail_route(methods=['post'])
def password(self, request, pk=None):

    try:
        user = User.objects.get(pk=pk)
    except User.DoesNotExist:
        # returns error
    else:

        password = request.data.get('password',None)
        new_password = request.data.get('new_password',None)

        if password and new_password:

            if check_password(password,user.password):

                # Use Django built-in to hash password.
                password_hash =  make_password(new_password)
                user.password = password_hash
                user.save()

                serializer_data = UserSerializer(user).data

                return Response(serializer_data)

            else:
                # return error reponse
        else:
            # return error response

By using this approach, I'm able to update the password field of a user but validate_password is not effective anymore when POST /users/pk/password/ is called so that users can update their password with an entirely numeric one.

I'm aware of the fact that I can try to implement validate_password inside the detail route implementation, but it does not feel like the best way to go.

My question is what is the best way to do this without duplicating code and without moving validation logic into views.py?

PS: I cannot use nor extend Django User model for various reasons.

Thanks!

Body:
This the problem, you are getting the data straight off the raw post, when you are supposed to be using the serializer

    password = request.data.get('password',None)
    new_password = request.data.get('new_password',None)

Now assuming your serializer with the validation code is called MySerializer, the above lines need to be replaced with something like

   serial = MySerializer(data=request.data)
   if serial.is_valid():
       password = serial.validated_data['password']
       new_password = serial.validated_data['new_password']

Now your validation code will be executed.


问:
MySQL selecting yesterday's date
How can I display and count the values whose dates are yesterday?
I used time() to insert date in the database. Example:

```<code>URL: google.com youtube.com google.com youtube.com test.com youtube.com
DateVisited: 1313668492 1313668540 1313668571 13154314
</code>```

I want do display how many URLs that have multiple existed in the table and also how many of that URL have been visited yesterday. Example result:

```<code>LINK       | timesExisted | timesVisitedYesterday
Google.com |       2      | 2
youtube.com|       3      | 3
</code>```

I already have the idea on getting yesterday's date, but I don't have an idea on counting how many times a URL has existed for yesterday and counting how many times a URL has existed in the table.

答:
You can use:

```<code>SELECT SUBDATE(NOW(), 1);
</code>```

or

```<code>SELECT SUBDATE(NOW(), INTERVAL 1 DAY);
</code>```

or

```<code>SELECT NOW() - INTERVAL 1 DAY;
</code>```

or

```<code>SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);
</code>```

Title: MySQL selecting yesterday's date

Body:
How can I display and count the values whose dates are yesterday?
I used time() to insert date in the database. Example:

URL: google.com youtube.com google.com youtube.com test.com youtube.com
DateVisited: 1313668492 1313668540 1313668571 13154314

I want do display how many URLs that have multiple existed in the table and also how many of that URL have been visited yesterday. Example result:

LINK       | timesExisted | timesVisitedYesterday
Google.com |       2      | 2
youtube.com|       3      | 3

I already have the idea on getting yesterday's date, but I don't have an idea on counting how many times a URL has existed for yesterday and counting how many times a URL has existed in the table.

Body:
You can use:

SELECT SUBDATE(NOW(), 1);

or

SELECT SUBDATE(NOW(), INTERVAL 1 DAY);

or

SELECT NOW() - INTERVAL 1 DAY;

or

SELECT DATE_SUB(NOW(), INTERVAL 1 DAY);

ContentLicense: CC BY-SA 4.0


问:
R: circlize chord diagram with images as labels?
Is it possible to place images where the labels of a circlize chordDiagram would be?

For example, I have manually placed SVG outlines of the continents against the labels. I was wondering if there is a programmatic way to achieve this.

Here is a starter example to which I hope to be able to add image labels. Note that there is an example on the circlize site that appears to do what I want:

but I cannot combine that with this example:

```<code>mat = matrix(sample(100, 25), 5)
rownames(mat) = letters[1:5]
colnames(mat) = letters[1:5]

library(circlize)
chordDiagram(mat, directional = TRUE, transparency = 0.5)
</code>```

答:
In your example, you need to create one empty track at the most outside of the circle and later go back to this empty track to add raster images.

In following example, preAllocateTracks argument is used to define how many empty tracks should be put. For more explanation of this argument, please refer to: http://zuguang.de/circlize_book/book/advanced-usage-of-chorddiagram.html#organization-of-tracks

```<code>mat = matrix(sample(100, 25), 5)
rownames(mat) = letters[1:5]
colnames(mat) = letters[1:5]

library(circlize)

library(png)
tmp = tempfile()
download.file("https://www.google.de/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png", tmp)
image = as.raster(readPNG(tmp))
ratio = ncol(image)/nrow(image)

chordDiagram(mat, directional = TRUE, transparency = 0.5,
    preAllocateTracks = 1)

circos.track(track.index = 1, panel.fun = function(x, y) {
    xcenter = get.cell.meta.data("xcenter")
    ycenter = get.cell.meta.data("ycenter")

    pos = circlize:::polar2Cartesian(circlize(xcenter, ycenter))

    rasterImage(image,
        xleft = pos[1, 1] - 0.05*ratio,
        ybottom = pos[1, 2] - 0.05,
        xright = pos[1, 1] + 0.05*ratio,
        ytop = pos[1, 2]+ 0.05)
}, bg.border = NA)
</code>```

It is also possible but not easy to rotate the images to let them face the center of the circle, because rasterImage() has a angle argument which allows rotating the image but the rotation is relative to the left bottom corner of the image while not the center of the image.

EDIT: I have added a new function circos.raster() in the package (version >= 0.4.1) which makes adding raster images easier.

Body:
Is it possible to place images where the labels of a circlize chordDiagram would be?

For example, I have manually placed SVG outlines of the continents against the labels. I was wondering if there is a programmatic way to achieve this.

Here is a starter example to which I hope to be able to add image labels. Note that there is an example on the circlize site that appears to do what I want:

but I cannot combine that with this example:

mat = matrix(sample(100, 25), 5)
rownames(mat) = letters[1:5]
colnames(mat) = letters[1:5]

library(circlize)
chordDiagram(mat, directional = TRUE, transparency = 0.5)

Body:
In your example, you need to create one empty track at the most outside of the circle and later go back to this empty track to add raster images.

In following example, preAllocateTracks argument is used to define how many empty tracks should be put. For more explanation of this argument, please refer to: http://zuguang.de/circlize_book/book/advanced-usage-of-chorddiagram.html#organization-of-tracks

mat = matrix(sample(100, 25), 5)
rownames(mat) = letters[1:5]
colnames(mat) = letters[1:5]

library(circlize)

library(png)
tmp = tempfile()
download.file("https://www.google.de/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png", tmp)
image = as.raster(readPNG(tmp))
ratio = ncol(image)/nrow(image)

chordDiagram(mat, directional = TRUE, transparency = 0.5,
    preAllocateTracks = 1)

circos.track(track.index = 1, panel.fun = function(x, y) {
    xcenter = get.cell.meta.data("xcenter")
    ycenter = get.cell.meta.data("ycenter")

    pos = circlize:::polar2Cartesian(circlize(xcenter, ycenter))

    rasterImage(image,
        xleft = pos[1, 1] - 0.05*ratio,
        ybottom = pos[1, 2] - 0.05,
        xright = pos[1, 1] + 0.05*ratio,
        ytop = pos[1, 2]+ 0.05)
}, bg.border = NA)

It is also possible but not easy to rotate the images to let them face the center of the circle, because rasterImage() has a angle argument which allows rotating the image but the rotation is relative to the left bottom corner of the image while not the center of the image.

EDIT: I have added a new function circos.raster() in the package (version >= 0.4.1) which makes adding raster images easier.


问:
Dataframe titles on to_csv
I have a dataframe of the following structure which I have simplified for the sake of this question, I am reading the dataframe from a csv file.

```<code>  A        B    C     D    E
  LOCATION DATE DATE  1    1
  LOCATION DATE DATE  1    1
  LOCATION DATE DATE  1    1
  LOCATION DATE DATE  1    1
</code>```

I read in this csv from the file temp.dat using the following:

```<code>dfinal = pd.read_csv("temp.dat", header=0)
</code>```

Then the following is done

```<code>os.remove("temp.dat")
dfinal = dfinal.sort_values(by="B", ascending=True)
f = open(t, "w")
f.write(stuff)
f.write(stuff)
dfinal.to_csv(t, index=False)
f.close()
</code>```

In the above code the temp file is deleted, the dataframe is sorted by ascending date and then a new file whose name is assigned to t is opened. Then two lines
of metadata are written and the dataframe is written to the file and finally closed, however writing the dataframe as above produces errors on the column names like so.

As my file stands currently:

```<code>stuff
stuff
21,342,231,0,2 #Column names are being replaced here with unknown numbers
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
</code>```

The column names are not printing correctly as the first line after the 2 "stuff" lines should be the header that is read from the csv temp.dat but the writing of the f.write statements are messing up the columns.

My desired output would be:

```<code>stuff
stuff
A        B    C     D    E
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
</code>```

How would I go about achieving this?

答:
I think you need mode='a' what means python write mode append in to_csv:

```<code>print (dfinal)
          A      B     C  D  E
0  LOCATION  DATE1  DATE  1  1
1  LOCATION  DATE5  DATE  1  1
2  LOCATION   DATE  DATE  1  1
3  LOCATION   DATE  DATE  1  1

t = "temp.dat"
stuff = 'stuff\n'
dfinal = dfinal.sort_values(by="B", ascending=True)

#write metadata
with open(t, "w") as f:
    f.write(stuff)
    f.write(stuff)
#append df to existing file filled by metadata
dfinal.to_csv(t, index=False, mode='a')

#omit first 2 metadata rows
df = pd.read_csv(t, header=2)
print (df)
          A      B     C  D  E
0  LOCATION   DATE  DATE  1  1
1  LOCATION   DATE  DATE  1  1
2  LOCATION  DATE1  DATE  1  1
3  LOCATION  DATE5  DATE  1  1
</code>```

Title: Dataframe titles on to_csv

Body:
I have a dataframe of the following structure which I have simplified for the sake of this question, I am reading the dataframe from a csv file.

  A        B    C     D    E
  LOCATION DATE DATE  1    1
  LOCATION DATE DATE  1    1
  LOCATION DATE DATE  1    1
  LOCATION DATE DATE  1    1

I read in this csv from the file temp.dat using the following:

dfinal = pd.read_csv("temp.dat", header=0)

Then the following is done

os.remove("temp.dat")
dfinal = dfinal.sort_values(by="B", ascending=True)
f = open(t, "w")
f.write(stuff)
f.write(stuff)
dfinal.to_csv(t, index=False)
f.close()

In the above code the temp file is deleted, the dataframe is sorted by ascending date and then a new file whose name is assigned to t is opened. Then two lines
of metadata are written and the dataframe is written to the file and finally closed, however writing the dataframe as above produces errors on the column names like so.

As my file stands currently:

stuff
stuff
21,342,231,0,2 #Column names are being replaced here with unknown numbers
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1

The column names are not printing correctly as the first line after the 2 "stuff" lines should be the header that is read from the csv temp.dat but the writing of the f.write statements are messing up the columns.

My desired output would be:

stuff
stuff
A        B    C     D    E
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1
LOCATION DATE DATE  1    1

How would I go about achieving this?

Body:
I think you need mode='a' what means python write mode append in to_csv:

print (dfinal)
          A      B     C  D  E
0  LOCATION  DATE1  DATE  1  1
1  LOCATION  DATE5  DATE  1  1
2  LOCATION   DATE  DATE  1  1
3  LOCATION   DATE  DATE  1  1

t = "temp.dat"
stuff = 'stuff\n'
dfinal = dfinal.sort_values(by="B", ascending=True)

#write metadata
with open(t, "w") as f:
    f.write(stuff)
    f.write(stuff)
#append df to existing file filled by metadata
dfinal.to_csv(t, index=False, mode='a')

#omit first 2 metadata rows
df = pd.read_csv(t, header=2)
print (df)
          A      B     C  D  E
0  LOCATION   DATE  DATE  1  1
1  LOCATION   DATE  DATE  1  1
2  LOCATION  DATE1  DATE  1  1
3  LOCATION  DATE5  DATE  1  1


问:
PreferenceActivity with multiple PreferenceScreens without Headers
I would like to do a normal PreferenceActivity (in the old style, without headers), but with fragments and without using addPreferencesFromResource(id) (because deprecation).

Right now I achieved this by putting this in my onCreate:

```<code>getFragmentManager().beginTransaction().replace(android.R.id.content, new PreferencesFragment()).commit();
</code>```

And my PreferencesFragment looks something like this:

```<code>public static class PreferencesFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}
</code>```

Obviously I also implemented the isValidFragment method:

```<code>@Override
protected boolean isValidFragment(String fragmentName) {
    return PreferencesFragment.class.getName().equals(fragmentName)
            || InnerFragment.class.getName().equals(fragmentName);
}
</code>```

And it's working just fine. However, there is a problem when having PreferenceScreen's inside my preferences.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <!--  ...  -->
    <PreferenceScreen android:fragment="net.chaozspike.batterynotifier.SettingsActivity$InnerFragment"
        android:summary="@string/settings_activity_prefs_display_night_mode_sum"
        android:title="@string/settings_activity_prefs_display_night_mode" />
    <!--  ...  -->
</PreferenceScreen>
</code>```

I have the following problem: the new preference screen shows on top of the normal one, and I know it's probably because I replaced the default R.id.content. Screenshot:

However I want to fix this problem without using deprecated stuff or headers. Is that possible to achieve?

答:
Simply use PreferenceActivity.EXTRA_SHOW_FRAGMENT and PreferenceActivity.EXTRA_NO_HEADERS to show only one fragment and skip the headers:

```<code>//Note #1: ExtendedPreferenceActivity extends PreferenceActivity
//Note #2: ExtendedPreferenceFragment extends PreferenceFragment and is
//declared as an inner static class in ExtendedPreferenceActivity
Intent intent = new Intent(context, ExtendedPreferenceActivity.class );
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, ExtendedPreferenceActivity.ExtendedPreferenceFragment.class.getName() );
intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true );
startActivity(intent);
</code>```

Body:
I would like to do a normal PreferenceActivity (in the old style, without headers), but with fragments and without using addPreferencesFromResource(id) (because deprecation).

Right now I achieved this by putting this in my onCreate:

getFragmentManager().beginTransaction().replace(android.R.id.content, new PreferencesFragment()).commit();

And my PreferencesFragment looks something like this:

public static class PreferencesFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

Obviously I also implemented the isValidFragment method:

@Override
protected boolean isValidFragment(String fragmentName) {
    return PreferencesFragment.class.getName().equals(fragmentName)
            || InnerFragment.class.getName().equals(fragmentName);
}

And it's working just fine. However, there is a problem when having PreferenceScreen's inside my preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceScreen android:fragment="net.chaozspike.batterynotifier.SettingsActivity$InnerFragment"
        android:summary="@string/settings_activity_prefs_display_night_mode_sum"
        android:title="@string/settings_activity_prefs_display_night_mode" />

</PreferenceScreen>

I have the following problem: the new preference screen shows on top of the normal one, and I know it's probably because I replaced the default R.id.content. Screenshot:

However I want to fix this problem without using deprecated stuff or headers. Is that possible to achieve?

Body:
Simply use PreferenceActivity.EXTRA_SHOW_FRAGMENT and PreferenceActivity.EXTRA_NO_HEADERS to show only one fragment and skip the headers:

//Note #1: ExtendedPreferenceActivity extends PreferenceActivity
//Note #2: ExtendedPreferenceFragment extends PreferenceFragment and is
//declared as an inner static class in ExtendedPreferenceActivity
Intent intent = new Intent(context, ExtendedPreferenceActivity.class );
intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, ExtendedPreferenceActivity.ExtendedPreferenceFragment.class.getName() );
intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true );
startActivity(intent);


问:
java parsing a string like "0:ADD(10)"
i am having a string array like this {"0:ADD(10)","1:ADD(20)"} how can i parse this and get the value '10','20' from this string ,

Scenario is : i am trying to write a client and server app using Apache Mina server , when i sent message between client and server i am getting response as "0:ADD(10)"

答:
```<code>    String[] split = "{\"0:ADD(10)\",\"1:ADD(20)\"}".split( "," );
    for ( String e : split ) {
        String arg = e.substring( e.indexOf( '(' )+1, e.indexOf( ')') );
         System.out.println( arg );
     }
</code>```

Title: java parsing a string like "0:ADD(10)"


问:
QAbstractTableModel strange rowCount
I have an abstractTable model with a very odd problem.

The rowCount method;

```<code>int ordersModel::rowCount(const QModelIndex &) const
{
    int i = oData->count();
    qDebug() << "rowc=" << i;

    return 711;
  //  return   oData->count();

}
</code>```

Works when I hard code the value (711 or something lower) but if I
use return i; or return oData->count(); the table displays nothing. (qDebug() reports that the data has 711 entries.

The headers appear correctly. I'm in Qt 5.4.1, Windows 7.

Stumped!

答:
Try </p>

```<code>int MyModel::rowCount(const QModelIndex &parent) const {

  if ( parent.isValid() )
      return 0;

  return m_entryList.size();
}
</code>```

Title: QAbstractTableModel strange rowCount

Body:
I have an abstractTable model with a very odd problem.

The rowCount method;

int ordersModel::rowCount(const QModelIndex &) const
{
    int i = oData->count();
    qDebug() << "rowc=" <count();

}

Works when I hard code the value (711 or something lower) but if I
use return i; or return oData->count(); the table displays nothing. (qDebug() reports that the data has 711 entries.

The headers appear correctly. I'm in Qt 5.4.1, Windows 7.

Stumped!

Body:
Try

int MyModel::rowCount(const QModelIndex &parent) const {

  if ( parent.isValid() )
      return 0;

  return m_entryList.size();
}


问:
Make pycharm use the real ipython console
In pycharm, the ipython console does not seem to be a real ipython console.

In pycharm ipython console:

```<code>In[1]: ?sorted
{'text/plain': 'Signature: sorted(iterable, key=None, reverse=False)\nDocstring:\nReturn a ne
</code>```

In a real ipython console:

```<code>In [5]: ?sorted
Signature: sorted(iterable, key=None, reverse=False)
Docstring:
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
Type:      builtin_function_or_method
</code>```

I saw some other differences: does not load ipython profile, different behavior when using shortcut to get back previous commands

Is there anyway to have a real ipython console in pycharm? And that this console is still compatible with the shortcuts to run the selected code in the console.

答:
Could it be, that you're using different virtual environments/python versions in PyCharm and locally? That could perfectly explain differences in the outputs.

Can you run this code in both and compare the output:

```<code>import IPython; IPython.version_info
</code>```

EDIT

Confirmed, PyCharm converts the output of the ipython even if the versions are the same.

Body:
In pycharm, the ipython console does not seem to be a real ipython console.

In pycharm ipython console:

In[1]: ?sorted
{'text/plain': 'Signature: sorted(iterable, key=None, reverse=False)\nDocstring:\nReturn a ne

In a real ipython console:

In [5]: ?sorted
Signature: sorted(iterable, key=None, reverse=False)
Docstring:
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
Type:      builtin_function_or_method

I saw some other differences: does not load ipython profile, different behavior when using shortcut to get back previous commands

Is there anyway to have a real ipython console in pycharm? And that this console is still compatible with the shortcuts to run the selected code in the console.

Body:
Could it be, that you're using different virtual environments/python versions in PyCharm and locally? That could perfectly explain differences in the outputs.

Can you run this code in both and compare the output:

import IPython; IPython.version_info

EDIT

Confirmed, PyCharm converts the output of the ipython even if the versions are the same.


问:
Alert function not working in coffeescript
I found about CoffeeScript in a blog and decided to give it a try ,my first project/code with it was this

```<code>alert "Hello CoffeeScript!"
</code>```

It doesn't work and gives this reply

```<code>ReferenceError: alert is not defined
</code>```

is there anything i am doing wrong?

答: window.alert is a method defined by the DOM (in browsers), not by Javascript. If the environment you're running this in doesn't have a global alert method defined, then you can't call it.

Body:
I found about CoffeeScript in a blog and decided to give it a try ,my first project/code with it was this

alert "Hello CoffeeScript!"

It doesn't work and gives this reply

ReferenceError: alert is not defined

is there anything i am doing wrong?


问:
Cross-origin ajax not working
I am having a problem while using cross-origin ajax.

I know it's a common question but did not get any solution for it yet.

```<code>$.ajax({
  type: "GET",
  url: url,
  data: {id:id},
  dataType: "jsonp",
  crossDomain: true,
  contentType: "application/jsonp; charset=utf-8",
  async: false,
  success: fnsuccesscallbackk,
  error: function(xhr, error){
    alert(error);
  },
  jsonpCallback: fnsuccesscallback
});

function fnsuccesscallback(data){
  alert(data)
}
</code>```

…but getting undefined response in callback function.

Is there anything wrong what I am doing.

答:
After a lots of RND finally i got the solution of this.</p>

```<code>Ajax function:
$.ajax({
        type:"GET",
        url:'https://www.url.com/welcome/test_js',
        data:{name:'xyz'},
        crossDomain:true,
        dataType: "jsonp",
        jsonp: 'fnsuccesscallback',
         success: function(data) {
              alert(data.name)
        }
});

In the Php function:
function test_js() {
    echo $_GET['fnsuccesscallback'] . "(" . json_encode($_GET) . ")";
}
</code>```

Title: Cross-origin ajax not working

Body:
I am having a problem while using cross-origin ajax.

I know it's a common question but did not get any solution for it yet.

$.ajax({
  type: "GET",
  url: url,
  data: {id:id},
  dataType: "jsonp",
  crossDomain: true,
  contentType: "application/jsonp; charset=utf-8",
  async: false,
  success: fnsuccesscallbackk,
  error: function(xhr, error){
    alert(error);
  },
  jsonpCallback: fnsuccesscallback
});

function fnsuccesscallback(data){
  alert(data)
}

…but getting undefined response in callback function.

Is there anything wrong what I am doing.

Body:
After a lots of RND finally i got the solution of this.

Ajax function:
$.ajax({
        type:"GET",
        url:'https://www.url.com/welcome/test_js',
        data:{name:'xyz'},
        crossDomain:true,
        dataType: "jsonp",
        jsonp: 'fnsuccesscallback',
         success: function(data) {
              alert(data.name)
        }
});

In the Php function:
function test_js() {
    echo $_GET['fnsuccesscallback'] . "(" . json_encode($_GET) . ")";
}


问:
Set text in the centre of AppBar
I this is my xml:

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_height="57dp"
        android:layout_width="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Ranger"
            android:id="@+id/logoSign"/>
    </android.support.design.widget.AppBarLayout>
</RelativeLayout>
</code>```

I want to do the TextView in the centre of the AppBar. But I get this:

Thanks for your help. :)

答:
```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_height="57dp"
    android:layout_width="match_parent">
    <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Ranger"
            android:id="@+id/logoSign"/>
    </LinearLayout>
</android.support.design.widget.AppBarLayout>
</code>```

Title: Set text in the centre of AppBar

Body:
I this is my xml:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_height="57dp"
        android:layout_width="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Ranger"
            android:id="@+id/logoSign"/>
    </android.support.design.widget.AppBarLayout>
</RelativeLayout>

I want to do the TextView in the centre of the AppBar. But I get this:

Thanks for your help. :)


问:
TSQL Code formatter - SQL Server 2005/2008
Is there a free code formatter available for TSQL - SQL Server 2005/2008. I found few most of which asks to copy paste code online in an applet. I am looking for a desktop version. Tried toad for sql server but formatting is not supported in freeware.
If anyone has any work-around please share it. </p>

答:
SQLISE has a formating function, you can set a number of formatting options. It is free. It is a codeplex project based on PowerShell.

Drawback it removes all comments
link text


问:
NodeJS Dynamic Service Loader & Runner
Context:

I'm trying to build a few slack hooks / notification services for a channel I'm active on, being the cheap-skate finance savvy person that I am, I'd like to make use of a free service as such (trail Heroku accounts, or similar products), thus I'd like to be able to run multiple services on a single instance.

I've created a generic runner, that should be based on a config and be able to pick up some node modules and supply them the config settings.

I'm using the following node_modules:

"auto-loader": "^0.2.0",
      "node-cron": "^1.2.0",
      "read-yaml": "^1.1.0"

config.yml

```<code>foo:
  cron: 1 * * * *
  url: http://www.foo.com
  team:
    -
      slackId: bar
      bnetId: 1
      eloId: 1
    -
      slackId: baz
      bnetId: 2
      eloId: 2
</code>```

app.js

```<code>const autoLoader = require('auto-loader');
const readYaml = require('read-yaml');
const cron = require('node-cron');

const services = autoLoader.load(__dirname +'/services')

readYaml('config.yml', function(err, conf) {

    if (err) throw err;

    Object.keys(conf).forEach(function (key) {

        console.log('Creating CRON for ' + key);

        if(cron.validate(conf[key].cron)) {

            console.log(conf[key].cron, '-> is valid cron');

            // the cron task below does not seem to fire ever
            cron.schedule(conf[key].cron, function(){
                services[key](conf[key]);
            });

        } else {
            console.log('Cron invalid for::' + key)
        }

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

service/foo.js

```<code>module.exports = function (config) {
    console.log('foo entered!!');
    console.log(config)
}
</code>```

Question:

What am I missing? If I remove the cron schedule, my services get hit, thus my assumptions are as follows...

Either I'm missing something conceptually about how long running process are meant to work in NodeJS (as this is my first), or I'm missing a super (not obvious) to me bug.

How do you create a long running task/process in NodeJS with separate scheduled code sections / tasks?

答:
The code itself works as expected. The issue appears to be with the configuration of the cron.

cron: 1 * * * * will run at 1 minute past the hour.

```<code>cron: "*/1 * * * *"      # would run it every minute
cron: "*/5 * * * *"      # would run it every 5 minutes
cron: "*/10 * * * * *"   # would run every 10 seconds
</code>```

Title: NodeJS Dynamic Service Loader & Runner

Body:
Context:

I'm trying to build a few slack hooks / notification services for a channel I'm active on, being the cheap-skate finance savvy person that I am, I'd like to make use of a free service as such (trail Heroku accounts, or similar products), thus I'd like to be able to run multiple services on a single instance.

I've created a generic runner, that should be based on a config and be able to pick up some node modules and supply them the config settings.

I'm using the following node_modules:

"auto-loader": "^0.2.0",
      "node-cron": "^1.2.0",
      "read-yaml": "^1.1.0"

config.yml

foo:
  cron: 1 * * * *
  url: http://www.foo.com
  team:
    -
      slackId: bar
      bnetId: 1
      eloId: 1
    -
      slackId: baz
      bnetId: 2
      eloId: 2

app.js

const autoLoader = require('auto-loader');
const readYaml = require('read-yaml');
const cron = require('node-cron');

const services = autoLoader.load(__dirname +'/services')

readYaml('config.yml', function(err, conf) {

    if (err) throw err;

    Object.keys(conf).forEach(function (key) {

        console.log('Creating CRON for ' + key);

        if(cron.validate(conf[key].cron)) {

            console.log(conf[key].cron, '-> is valid cron');

            // the cron task below does not seem to fire ever
            cron.schedule(conf[key].cron, function(){
                services[key](conf[key]);
            });

        } else {
            console.log('Cron invalid for::' + key)
        }

    });
});

service/foo.js

module.exports = function (config) {
    console.log('foo entered!!');
    console.log(config)
}

Question:

What am I missing? If I remove the cron schedule, my services get hit, thus my assumptions are as follows...

Either I'm missing something conceptually about how long running process are meant to work in NodeJS (as this is my first), or I'm missing a super (not obvious) to me bug.

How do you create a long running task/process in NodeJS with separate scheduled code sections / tasks?

Body:
The code itself works as expected. The issue appears to be with the configuration of the cron.

cron: 1 * * * * will run at 1 minute past the hour.

cron: "*/1 * * * *"      # would run it every minute
cron: "*/5 * * * *"      # would run it every 5 minutes
cron: "*/10 * * * * *"   # would run every 10 seconds


问:
AWS S3 - Calculate File Hash with Lambda
Is it possible to use a lambda function for every PUT request to a S3 bucket to calculate the file hash? And yes, I know, that S3 uses etags.</p>

答:
You can add a trigger for your lambda function.

Configure triggers -> Choose S3 -> Event type -> Object Created PUT

You will get notification for every PUT request on bucket. You can access it using lambda handler and perform hash operation in that handler function.


问:
XAML - Binding Group Header In Group Header Style
Not trying to post a duplicate of this thread:
WPF - Binding to current item from within group header style

I got the binding working.  I'm stil unclear why it works.    This part of the XAML sets up the group item and binds the Texbox to the text.  What I don't understand is the Binding to the 'Name' property.  What is 'Name' a property of? The group header?  Until I found the linked thread I was trying to bind to a property on the items in the data grid.

```<code> <ControlTemplate TargetType="{x:Type GroupItem}">
      <Expander IsExpanded="True"
                Background="#FF112255"
                BorderBrush="#FF002255"
                Foreground="#FFEEEEEE"
                BorderThickness="1,1,1,5">
         <Expander.Header>
           <StackPanel Orientation="Horizontal">
              <TextBlock FontWeight="Bold"
                         Text="SVC Node: "/>
                 <TextBlock FontWeight="Bold"
                            Text="{Binding Name}"/>
             </StackPanel>
           </Expander.Header>
         <Expander.Content>
        <ItemsPresenter />
       </Expander.Content>
      </Expander>
  </ControlTemplate>
</code>```

答:
Name refers to the property of the System.Windows.Data.CollectionViewGroup object that gets created by WPF and being set as the DataContext of a GroupItem.

This property returns the value of the property that you group the source collection by. So if you for example group a source collection of Person objects by a property called Sex, the Name property of the CollectionViewGroup would return something like "Male" or "Female". This Name property is not a property of your custom model class.

The CollectionViewGroup class also has a an Items property that returns the collection of objects, for example all Person objects where the Sex property returns "Male", that belongs to the specific group.

Hope that makes sense.

Body:
Not trying to post a duplicate of this thread:
WPF - Binding to current item from within group header style

I got the binding working.  I'm stil unclear why it works.    This part of the XAML sets up the group item and binds the Texbox to the text.  What I don't understand is the Binding to the 'Name' property.  What is 'Name' a property of? The group header?  Until I found the linked thread I was trying to bind to a property on the items in the data grid.

 <ControlTemplate TargetType="{x:Type GroupItem}">
      <Expander IsExpanded="True"
                Background="#FF112255"
                BorderBrush="#FF002255"
                Foreground="#FFEEEEEE"
                BorderThickness="1,1,1,5">
         <Expander.Header>
           <StackPanel Orientation="Horizontal">
              <TextBlock FontWeight="Bold"
                         Text="SVC Node: "/>
                 <TextBlock FontWeight="Bold"
                            Text="{Binding Name}"/>
             </StackPanel>
           </Expander.Header>
         <Expander.Content>
        <ItemsPresenter />
       </Expander.Content>
      </Expander>
  </ControlTemplate>


问:
How to get rid of the tabs referencing deleted SQL queries? (on startup)
Content as per title. Will be updated if title won't be clear enough.

Restart of the tool didn't help. Closing the tabs doesn't help either.

I wonder if there is anything that can be done.

答:
It might have something to do with your IDE saving your workspace in the past and now being unable to overwrite it.

Check Tools > Preferences > Environment and see if (de)activating any of the following options and then restarting SQL Developer has any effect:

Save Everything On Exit: toggle* it, close every tab and restart.

Automatically Reload Externally Modified Files: deactivate it, close every tab and restart.

Check Externally Modified Files On Start: deactivate it, close every tab and restart.

Local History > Enable Local History: deactivate it, close every tab and restart.

* By toggle I mean: if it's off, turn it on; if it's on, turn it off.

The exact name of the settings may vary. You can have a look at SQL Developer Preferences doc for further explanation of each option.


问:
Inconsitent TypeScript behavior with union and object type
Let's have a following snippet:

```<code>interface A {
  isEmpty(x: any[] | string | object): boolean;
  isEmptyObject(x: object): boolean;
}

const a: A = <A>{};

a.isEmptyObject({});
a.isEmptyObject({a: 1});

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});
</code>```

When I try to compile it, it crashes with this:

```<code>a.ts(14,12): error TS2345: Argument of type '{ a: number; }' is not assignable to parameter of type 'string | object | any[]'.
  Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.
</code>```

How is this possible, when the union type (string | object | any[]) contains type object for which it works (the isEmptyObject call with {a: 1} is fine)?

Main question: Is this a TypeScript bug, or how one should write that input may be an array of any value or string or object (but not any primitive, I don't want any or Object)?

Tested with TypeScript 2.3.4.

答:
Typescript is failing the compilation on the following condition:

Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.

Basically { a: 1 } is not convertible to type object.

You could do it this way:

```<code>interface A {
    isEmpty(x: any[] | string | { [index: string]: any }): boolean;
    isEmptyObject(x: { [index: string]: any }): boolean;
}
</code>```

EDIT: after another look at the docs it is possibly explained by:

Union types can be a bit tricky here, but it just takes a bit of intuition to get used to. If a value has the type A | B, we only know for certain that it has members that both A and B have. In this example, Bird has a member named fly. We can’t be sure whether a variable typed as Bird | Fish has a fly method. If the variable is really a Fish at runtime, then calling pet.fly() will fail.

Body:
Let's have a following snippet:

interface A {
  isEmpty(x: any[] | string | object): boolean;
  isEmptyObject(x: object): boolean;
}

const a: A = {};

a.isEmptyObject({});
a.isEmptyObject({a: 1});

a.isEmpty([]);
a.isEmpty('');
a.isEmpty({});
a.isEmpty({a: 1});

When I try to compile it, it crashes with this:

a.ts(14,12): error TS2345: Argument of type '{ a: number; }' is not assignable to parameter of type 'string | object | any[]'.
  Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.

How is this possible, when the union type (string | object | any[]) contains type object for which it works (the isEmptyObject call with {a: 1} is fine)?

Main question: Is this a TypeScript bug, or how one should write that input may be an array of any value or string or object (but not any primitive, I don't want any or Object)?

Tested with TypeScript 2.3.4.

Body:
Typescript is failing the compilation on the following condition:

Object literal may only specify known properties, and 'a' does not exist in type 'string | object | any[]'.

Basically { a: 1 } is not convertible to type object.

You could do it this way:

interface A {
    isEmpty(x: any[] | string | { [index: string]: any }): boolean;
    isEmptyObject(x: { [index: string]: any }): boolean;
}

EDIT: after another look at the docs it is possibly explained by:

Union types can be a bit tricky here, but it just takes a bit of intuition to get used to. If a value has the type A | B, we only know for certain that it has members that both A and B have. In this example, Bird has a member named fly. We can’t be sure whether a variable typed as Bird | Fish has a fly method. If the variable is really a Fish at runtime, then calling pet.fly() will fail.


问:
Reactjs, typescript unable to set initial state inside component
I'm very new to React. I have a component that renders fine, when I try to initialise the state, it says It cannot find the name, as I have not declared it yet, so how do I initialise it properly? I'm using:

"react": "^15.5.4",
      "react-dom": "^15.5.4",

The component errors here on the line below:

```<code>export class Profile extends React.Component<{}, state> {

constructor(props){
    super(props);
    this.state = [{name: 'baz'}, {name: 'shaz'}];
}

public render() {
    return (
        <section>
         <section>
             <h3>profile 1</h3>
             <div>baz</div>
         </section>
            <section>
                <h3>profile 2</h3>
                <div>shaz</div>
            </section>
        </section>
        )

}

 ReactDOM.render(
   >> this is where I call <Profile />,
    document.getElementById('app'),
)
</code>```

Edit

So I managed to solve the issue with everyones help:

```<code>interface State {
    name: string;
}

export class Profile extends React.Component<{}, State> {
    public state: State;

    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (
            <section>
             <section>
                 <h3>profile 1</h3>
                 <div>baz</div>
             </section>
                <section>
                    <h3>profile 2</h3>
                    <div>{this.state.name}</div>
                </section>
            </section>
        )

    }
}
</code>```

答:
this.state is just an object. In this scenario you can run a loop on this.state object to get the value of each name, or if you want you can set all the name under another parent object, for example: let say you want to store names under users key. That would be,

```<code>constructor(props){
  super(props);
  this.state = {
    users: [
      {name: 'baz'}, {name: 'shaz'}
    ]
  };
}
</code>```

Now you should loop on this.state.users to get the name values.

Example,

```<code>// Loop using es6 map
componentWillMount() {
  this.state.users.map( user => {
    console.log( user.name )
  } )
}
</code>```

Body:
I'm very new to React. I have a component that renders fine, when I try to initialise the state, it says It cannot find the name, as I have not declared it yet, so how do I initialise it properly? I'm using:

"react": "^15.5.4",
      "react-dom": "^15.5.4",

The component errors here on the line below:

export class Profile extends React.Component<{}, state> {

constructor(props){
    super(props);
    this.state = [{name: 'baz'}, {name: 'shaz'}];
}

public render() {
    return (

profile 1

baz

profile 2

shaz

        )

}

 ReactDOM.render(
   >> this is where I call <Profile />,
    document.getElementById('app'),
)

Edit

So I managed to solve the issue with everyones help:

interface State {
    name: string;
}

export class Profile extends React.Component<{}, State> {
    public state: State;

    constructor(props){
        super(props);
            this.state = {
               name: 'baz111'
            };
    }

    public render() {
        return (

profile 1

baz

profile 2

{this.state.name}

        )

    }
}

Body:
this.state is just an object. In this scenario you can run a loop on this.state object to get the value of each name, or if you want you can set all the name under another parent object, for example: let say you want to store names under users key. That would be,

constructor(props){
  super(props);
  this.state = {
    users: [
      {name: 'baz'}, {name: 'shaz'}
    ]
  };
}

Now you should loop on this.state.users to get the name values.

Example,

// Loop using es6 map
componentWillMount() {
  this.state.users.map( user => {
    console.log( user.name )
  } )
}


问:
getting null pass String from fragment to the activiy using bundle
Well this will sound silly but I am using bundle to store my Data within, and trying to pass this bundle from the fragment to the hosting activity, and testing the data using a toast, but the toast is empty! I cant find the reason why this is happening since i made sure to fill the data correctly
My code in the fragment is:

```<code> @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_parent_register, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        setUpViews();
        setRecyclerAdapter();
    }

    private void setUpViews() {
        fullNameEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_fullName);
        emailEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_email);
        passwordEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_password);
        fullName = fullNameEditText.getText().toString();
        email= emailEditText.getText().toString();
        password = passwordEditText.getText().toString();
        Bundle parentData = new Bundle();
        parentData.putString(KEY_PARENT_FULL_NAME,fullName);
        parentData.putString(KEY_PARENT_EMAIL,email);
        parentData.putString(KEY_PARENT_PASSWORD,password);

        Intent intent = getActivity().getIntent();
        intent.putExtras(parentData);
</code>```

in the activity is :

```<code>  registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DataHolder.getInstance().getAccountType() == 0) {
                    Intent intent = new Intent(RegisterActivity.this, TeacherLocationActivity.class);
                    startActivity(intent);
                } else {
                /*    Intent intent = new Intent(RegisterActivity.this, StudentLocationActivity.class);
                    startActivity(intent);*/
                    Bundle parentData = getIntent().getExtras();
                    if (parentData != null)
                    {
                        Toast.makeText(RegisterActivity.this, parentData.getString(KEY_PARENT_FULL_NAME)+parentData.getString(KEY_PARENT_EMAIL)+parentData.getString(KEY_PARENT_PASSWORD), Toast.LENGTH_SHORT).show();
                    }
                    else if (parentData == null)
                    {
                        Toast.makeText(RegisterActivity.this, "Bundle is empty", Toast.LENGTH_SHORT).show();                    }
                }
            }
        });
</code>```

答:
To pass data from fragment to activity, you should use OnFragmentInteractionListener. Go to Android studio, add new fragment to see how is it implemented. It's very easy.

Read here: https://developer.android.com/training/basics/fragments/communicating.html

Body:
Well this will sound silly but I am using bundle to store my Data within, and trying to pass this bundle from the fragment to the hosting activity, and testing the data using a toast, but the toast is empty! I cant find the reason why this is happening since i made sure to fill the data correctly
My code in the fragment is:

 @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_parent_register, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        setUpViews();
        setRecyclerAdapter();
    }

    private void setUpViews() {
        fullNameEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_fullName);
        emailEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_email);
        passwordEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_password);
        fullName = fullNameEditText.getText().toString();
        email= emailEditText.getText().toString();
        password = passwordEditText.getText().toString();
        Bundle parentData = new Bundle();
        parentData.putString(KEY_PARENT_FULL_NAME,fullName);
        parentData.putString(KEY_PARENT_EMAIL,email);
        parentData.putString(KEY_PARENT_PASSWORD,password);

        Intent intent = getActivity().getIntent();
        intent.putExtras(parentData);

in the activity is :

  registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DataHolder.getInstance().getAccountType() == 0) {
                    Intent intent = new Intent(RegisterActivity.this, TeacherLocationActivity.class);
                    startActivity(intent);
                } else {
                /*    Intent intent = new Intent(RegisterActivity.this, StudentLocationActivity.class);
                    startActivity(intent);*/
                    Bundle parentData = getIntent().getExtras();
                    if (parentData != null)
                    {
                        Toast.makeText(RegisterActivity.this, parentData.getString(KEY_PARENT_FULL_NAME)+parentData.getString(KEY_PARENT_EMAIL)+parentData.getString(KEY_PARENT_PASSWORD), Toast.LENGTH_SHORT).show();
                    }
                    else if (parentData == null)
                    {
                        Toast.makeText(RegisterActivity.this, "Bundle is empty", Toast.LENGTH_SHORT).show();                    }
                }
            }
        });


问:
RestController with GET + POST on same method?
I'd like to create a single method and configure both GET + POST on it, using spring-mvc:

```<code>@RestController
public class MyServlet {
    @RequestMapping(value = "test", method = {RequestMethod.GET, RequestMethod.POST})
    public void test(@Valid MyReq req) {
          //MyReq contains some params
    }
}
</code>```

Problem: with the code above, any POST request leads to an empty MyReq object.

If I change the method signature to @RequestBody @Valid MyReq req, then the post works, but the GET request fails.

So isn't is possible to just use get and post together on the same method, if a bean is used as input parameters?

答:
The best solution to your problem seems to be something like this:

```<code>@RestController
public class MyServlet {
    @RequestMapping(value = "test", method = {RequestMethod.GET})
    public void testGet(@Valid @RequestParam("foo") String foo) {
          doStuff(foo)
    }
    @RequestMapping(value = "test", method = {RequestMethod.POST})
    public void testPost(@Valid @RequestBody MyReq req) {
          doStuff(req.getFoo());
    }
}
</code>```

You can process the request data in different ways depending on how you receive it and call the same method to do the business logic.

Body:
I'd like to create a single method and configure both GET + POST on it, using spring-mvc:

@RestController
public class MyServlet {
    @RequestMapping(value = "test", method = {RequestMethod.GET, RequestMethod.POST})
    public void test(@Valid MyReq req) {
          //MyReq contains some params
    }
}

Problem: with the code above, any POST request leads to an empty MyReq object.

If I change the method signature to @RequestBody @Valid MyReq req, then the post works, but the GET request fails.

So isn't is possible to just use get and post together on the same method, if a bean is used as input parameters?

Body:
The best solution to your problem seems to be something like this:

@RestController
public class MyServlet {
    @RequestMapping(value = "test", method = {RequestMethod.GET})
    public void testGet(@Valid @RequestParam("foo") String foo) {
          doStuff(foo)
    }
    @RequestMapping(value = "test", method = {RequestMethod.POST})
    public void testPost(@Valid @RequestBody MyReq req) {
          doStuff(req.getFoo());
    }
}

You can process the request data in different ways depending on how you receive it and call the same method to do the business logic.