来源: stackexchange

问:
Incorrect endpoint firing using Route attribute
I have the following methods in my UserController. The first two, Register and VerifyUser work fine.

However - I can't get login to be called. No matter what combination of URLs I try - the Register method fires.

```<code>[RoutePrefix("api/user")]
public class UserController : ApiController
{
    [Route("Register")]
    [HttpPost]
    public HttpResponseMessage Register([FromBody]RegisterUserModel model)
    {
        ....
    }

    [HttpGet]
    [Route("{email}/{verifyId}")]
    public HttpResponseMessage VerifyUser(string email, string verifyId)
    {
        ....
    }

    [Route("Login")] //Not being fired - Register being fired
    [HttpPost]
    public HttpResponseMessage Login([FromBody]RegisterUserModel userMod)
    {
        ....
    }
}
</code>```

Am I missing something obvious?

答:
What is happening is that you most likely have the default convention based route only

```<code>// Convention-based routing.
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</code>```

which would map to register first and not bother to check Login.

calling api/user/Login would map to the api/{controller}/{id} convention route with Login being mapped to the id placeholder. The route table to use the HTTP verb POST to find the first action that could handle a post with the provided body. It would find register first and map to that action.

Check to make sure attribute routing is enabled in WebApiConfig ie

```<code>// Attribute routing.
config.MapHttpAttributeRoutes();

// Convention-based routing.
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</code>```

The comments in the following shows the Url that maps to the actions.

```<code>[RoutePrefix("api/user")]
public class UserController : ApiController {

    //Matches POST api/user/register
    [Route("Register")]
    [HttpPost]
    public IHttpActionResult Register([FromBody]RegisterUserModel model) {
        //....
    }

    //Matches GET api/user/some_email/some_id
    [HttpGet]
    [Route("{email}/{verifyId}")]
    public IHttpActionResult VerifyUser(string email, string verifyId) {
        //....
    }

    //Matches POST api/user/login
    [Route("Login")]
    [HttpPost]
    public IHttpActionResult Login([FromBody]RegisterUserModel userMod) {
        //....
    }
}
</code>```

Reference Attribute Routing in ASP.NET Web API 2

ContentLicense: CC BY-SA 3.0

Body:
I have the following methods in my UserController. The first two, Register and VerifyUser work fine.

However - I can't get login to be called. No matter what combination of URLs I try - the Register method fires.

[RoutePrefix("api/user")]
public class UserController : ApiController
{
    [Route("Register")]
    [HttpPost]
    public HttpResponseMessage Register([FromBody]RegisterUserModel model)
    {
        ....
    }

    [HttpGet]
    [Route("{email}/{verifyId}")]
    public HttpResponseMessage VerifyUser(string email, string verifyId)
    {
        ....
    }

    [Route("Login")] //Not being fired - Register being fired
    [HttpPost]
    public HttpResponseMessage Login([FromBody]RegisterUserModel userMod)
    {
        ....
    }
}

Am I missing something obvious?

Body:
What is happening is that you most likely have the default convention based route only

// Convention-based routing.
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

which would map to register first and not bother to check Login.

calling api/user/Login would map to the api/{controller}/{id} convention route with Login being mapped to the id placeholder. The route table to use the HTTP verb POST to find the first action that could handle a post with the provided body. It would find register first and map to that action.

Check to make sure attribute routing is enabled in WebApiConfig ie

// Attribute routing.
config.MapHttpAttributeRoutes();

// Convention-based routing.
config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

The comments in the following shows the Url that maps to the actions.

[RoutePrefix("api/user")]
public class UserController : ApiController {

    //Matches POST api/user/register
    [Route("Register")]
    [HttpPost]
    public IHttpActionResult Register([FromBody]RegisterUserModel model) {
        //....
    }

    //Matches GET api/user/some_email/some_id
    [HttpGet]
    [Route("{email}/{verifyId}")]
    public IHttpActionResult VerifyUser(string email, string verifyId) {
        //....
    }

    //Matches POST api/user/login
    [Route("Login")]
    [HttpPost]
    public IHttpActionResult Login([FromBody]RegisterUserModel userMod) {
        //....
    }
}

Reference Attribute Routing in ASP.NET Web API 2


问:
Docusign API Get Limits in sandbox
Does DocuSign enforce its limits on Get requests per EnvelopeID in the sandbox?

I have reviewed their publications regarding the 1 Get request per EnvelopeID every 15 minutes and 1000 API requests per hour, however in the sandbox, it appears that I am able to get a valid response when intentionally violating these limits for testing when using the same EnvelopeID and endpoint.  Are these restrictions enforced only in the production environment? I posed the question to Docusign, but they didn't answer and referred me here.  Any insight would be appreciated.

答:
In Demo environment limit is more than 1000, for my Sandbox account I can see the limit is 100000. You can always check the Header in the any API call response, it will have below values:

```<code>X-RateLimit-Limit →100000
X-RateLimit-Remaining →99998
X-RateLimit-Reset →1512680400
</code>```

X-RateLimit-Limit tells your API call limit

X-RateLimit-Remaining tells how many are remaining in this hour

X-RateLimit-Reset tells the time when rate limit counter will be
rest

Title: Docusign API Get Limits in sandbox

Body:
In Demo environment limit is more than 1000, for my Sandbox account I can see the limit is 100000. You can always check the Header in the any API call response, it will have below values:

X-RateLimit-Limit →100000
X-RateLimit-Remaining →99998
X-RateLimit-Reset →1512680400

X-RateLimit-Limit tells your API call limit

X-RateLimit-Remaining tells how many are remaining in this hour

X-RateLimit-Reset tells the time when rate limit counter will be
rest


问:
Unity 2017 and HTC Vive
According to the documentation of Unity, I should use Axis1D.SecondaryIndexTrigger to be able to detect if the user pushes the joystick's trigger identified by the number 7 (on the image of the HTC Vive and in the table describing the inputs, both are displayed in the above link).

However, when I type if(Input.GetAxis(Axis1D.SecondaryIndexTrigger)), the compiler says :

error CS0103: The name `Axis1D' does not exist in the current context

Axis1D seems to be necessarily imported or somewhat to be usable.
How could I do this ?

答:
For Htc Vive you need to import following SteamVR Plugin from the unity assetstore

For step by step visit  getting started guide here for setting up Htc vive

Title: Unity 2017 and HTC Vive


问:
Redirection url:port to the same url:different-port
I spent 5 days looking for both Google and here a solution but there must be something that escapes me or I do not understand and therefore I do not.

I will explain it in detail. I want to redirect all the requests of a url:port to the same url but with another port sameurl:port. Example: example.com:9717 to example.com:15617

I have tried various methods in .htaccess and with proxypass in the vhost without success.

Currently the requests are directed to:

myexample.com:9713/key-private/data

And I want to redirect all the traffic to a new port:

myexample.com:15617/key-private/data

The problem is that I can redirect the port with htaccess or proxypass but it does not redirect the private-key data, so when it receives the requests in the new port it gives an error indicating that the private-key does not exist or is not correct. I guess that's because the redirect does not send it, or it does not do it correctly. The private key is essential since without it the user can not access.

Could someone please tell me the solution or put me on the right path?

Examples that I have used:

```<code>NameVirtualHost IP:15617
<VirtualHost IP:15617>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/data
    ProxyRequests off
    ProxyPass / http://IP:9713/
    ProxyPassReverse / http://IP:9713/
</VirtualHost>

RewriteCond %{HTTP_HOST} ^example.com:9713$ [NC]
RewriteCond %{SERVER_PORT} ^9713$
RewriteRule ^(.*)$ http://example.com:15617/$1 [L,R=302]

RewriteCond %{REQUEST_URI} ^\/$
RewriteRule .* http://example.com:15617/ [R=301,L]

RewriteCond %{HTTP_HOST} ^example.com:9713$ [NC]
RewriteCond %{SERVER_PORT} ^9713$
RewriteRule ^(.*)$ http://example.com:15617/$1 [L,R=302]

RewriteCond ${SERVER_PORT} 9713/$1
RewriteRule ^(.*)$ http://example.com:15617/$1 [QSA,L]
</code>```

I have tried more options but I do not add them for not making the question too long. I know something escapes me, but I can not understand or find what it is.

Thank you very much and excuse my English, it is quite poor.

答:
On port 9713, you want that virtual host to redirect to port 15617, right? So something like this:

```<code><VirtualHost *:9713>
  ServerName example.com
  ServerAlias www.example.com
  RedirectMatch /(.*) http://www.example.com:15617/$1
</VirtualHost>
</code>```

Body:
I spent 5 days looking for both Google and here a solution but there must be something that escapes me or I do not understand and therefore I do not.

I will explain it in detail. I want to redirect all the requests of a url:port to the same url but with another port sameurl:port. Example: example.com:9717 to example.com:15617

I have tried various methods in .htaccess and with proxypass in the vhost without success.

Currently the requests are directed to:

myexample.com:9713/key-private/data

And I want to redirect all the traffic to a new port:

myexample.com:15617/key-private/data

The problem is that I can redirect the port with htaccess or proxypass but it does not redirect the private-key data, so when it receives the requests in the new port it gives an error indicating that the private-key does not exist or is not correct. I guess that's because the redirect does not send it, or it does not do it correctly. The private key is essential since without it the user can not access.

Could someone please tell me the solution or put me on the right path?

Examples that I have used:

NameVirtualHost IP:15617
<VirtualHost IP:15617>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/data
    ProxyRequests off
    ProxyPass / http://IP:9713/
    ProxyPassReverse / http://IP:9713/
</VirtualHost>

RewriteCond %{HTTP_HOST} ^example.com:9713$ [NC]
RewriteCond %{SERVER_PORT} ^9713$
RewriteRule ^(.*)$ http://example.com:15617/$1 [L,R=302]

RewriteCond %{REQUEST_URI} ^\/$
RewriteRule .* http://example.com:15617/ [R=301,L]

RewriteCond %{HTTP_HOST} ^example.com:9713$ [NC]
RewriteCond %{SERVER_PORT} ^9713$
RewriteRule ^(.*)$ http://example.com:15617/$1 [L,R=302]

RewriteCond ${SERVER_PORT} 9713/$1
RewriteRule ^(.*)$ http://example.com:15617/$1 [QSA,L]

I have tried more options but I do not add them for not making the question too long. I know something escapes me, but I can not understand or find what it is.

Thank you very much and excuse my English, it is quite poor.

Body:
On port 9713, you want that virtual host to redirect to port 15617, right? So something like this:

<VirtualHost *:9713>
  ServerName example.com
  ServerAlias www.example.com
  RedirectMatch /(.*) http://www.example.com:15617/$1
</VirtualHost>


问:
Angular 4 canDeactivate fails if back button is hit twice in a row
I am attempting to implement a back button guard in Angular 4 for the first time. I am trying to use a service and canDeactivate.

I'm using the following service (code I found on the web, not my original code):

```<code>import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

export interface CanComponentDeactivate {
    canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {

    canDeactivate(component: CanComponentDeactivate) {
        return component.canDeactivate ? component.canDeactivate() : true;
    }

}
</code>```

Then in my routing module, I have the following path that uses canDeactivate:

```<code>{ path: 'contacts/:id/edit', canActivate: [AuthGuard], component: ContactEditComponent, data: { title: 'Edit Contact' }, canDeactivate: [CanDeactivateGuard] }
</code>```

Finally, in the component where I want back button routing protection, I have the following method:

```<code>canDeactivate() {
  if (this.editMode) {
    return window.confirm('Discard changes?');
  }
  return true;
}
</code>```

I was expecting that each time I attempted to hit the back button I would receive a pop-up with the 'Discard changes?' message.

What's happening is if I hit the back button, the pop-up alert occurs as expected. If I select 'cancel' the app won't navigate to the previous component. But, if I hit the back button a subsequent time, the app navigates back two components (in other words, to the 'page' before the 'page' before the 'page' I'm viewing).

Just for testing purposes I tried replacing if (this.editMode) with if (true) just to confirm that the state wasn't getting lost. There was no change in behavior.

答:
This seems to be a known Angular bug that has been fixed and is awaiting conflict resolution before it's merged into the Angular GitHub master branch.

https://github.com/angular/angular/pull/18135

Body:
I am attempting to implement a back button guard in Angular 4 for the first time. I am trying to use a service and canDeactivate.

I'm using the following service (code I found on the web, not my original code):

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs/Observable';

export interface CanComponentDeactivate {
    canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {

    canDeactivate(component: CanComponentDeactivate) {
        return component.canDeactivate ? component.canDeactivate() : true;
    }

}

Then in my routing module, I have the following path that uses canDeactivate:

{ path: 'contacts/:id/edit', canActivate: [AuthGuard], component: ContactEditComponent, data: { title: 'Edit Contact' }, canDeactivate: [CanDeactivateGuard] }

Finally, in the component where I want back button routing protection, I have the following method:

canDeactivate() {
  if (this.editMode) {
    return window.confirm('Discard changes?');
  }
  return true;
}

I was expecting that each time I attempted to hit the back button I would receive a pop-up with the 'Discard changes?' message.

What's happening is if I hit the back button, the pop-up alert occurs as expected. If I select 'cancel' the app won't navigate to the previous component. But, if I hit the back button a subsequent time, the app navigates back two components (in other words, to the 'page' before the 'page' before the 'page' I'm viewing).

Just for testing purposes I tried replacing if (this.editMode) with if (true) just to confirm that the state wasn't getting lost. There was no change in behavior.


问:
Download Neo4j server version 2.0.4
I could not find the Neo4j server version 2.0.4. The older releases that I could find are listed here https://neo4j.com/download/other-releases/. But the oldest release is 2.3.11. Does anyone know where I can find older versions?</p>

答:
You should try using the newest release available in the 2.x family at https://neo4j.com/download/other-releases/

There is not even a TAG for 2.0.4 in the source repository on github.
https://github.com/neo4j/neo4j

Title: Download Neo4j server version 2.0.4


问:
Must Java be installed to run a Java application?
when you write an app in java, people need to have this java installed to use it right?

Sorry if this is a dumb question.

答: There are also executable installers which may bundle Java or download it during the installation. You may also use "Java Web Start".</p>

ContentLicense: CC BY-SA 2.5


问:
Django - ValueError: too many values to unpack (expected 2)
I try to use make a droplist from model.

```<code>USER_TYPE = {
'admin': "Admin",
'patient': "Patient",
'helper': "Helper",
'therapist': "Therapist",
}

class User(AbstractBaseUser):
    user_type = models.CharField(max_length=10, choices=USER_TYPE, default="patient")
</code>```

However, I get this error:

ValueError: too many values to unpack (expected 2)

Thanks in advance!

答:
All you need is tuples instead of dictionary. Like :

YEAR_IN_SCHOOL_CHOICES = (
    ('FR', 'Freshman'),
    ('SO', 'Sophomore'),
    ('JR', 'Junior'),
    ('SR', 'Senior'),
)

Body:
I try to use make a droplist from model.

USER_TYPE = {
'admin': "Admin",
'patient': "Patient",
'helper': "Helper",
'therapist': "Therapist",
}

class User(AbstractBaseUser):
    user_type = models.CharField(max_length=10, choices=USER_TYPE, default="patient")

However, I get this error:

ValueError: too many values to unpack (expected 2)

Thanks in advance!


问:
Propagating Calling Context GCC Preprocessor Macro Values to Target Function
Let's say I have

```<code>foo () {
  bar ();
}
</code>```

where foo lies in f.c and bar lies in b.c, i.e. b.h is included in f.c. I would like to modify bar to print that it was called from any function foo that invokes it, like so:

```<code>bar () {
  printf ("Called from line %d in file %s",?,?);
  /* Run as usual */
}
</code>```

I want to obtain these two pieces of information from the predefined GCC preprocessor macros __LINE__ and __FILE__. However, these obviously evaluate to the line of printf in b.c and the path to b.c respectively, if simply plugged into the printf.

Can I somehow propagate the values of __LINE__ and __FILE__ from the calling context to the printf in bar, so "Called from line x in file foo.c" is printed instead?

I attempted to rename bar to bar2 and then define a delegator function in the header file b.h:

```<code>bar () {
  printf ("Called from line %d in file %s",__LINE__,__FILE__);
  bar2 ();
}
</code>```

The idea was that the #include directive would copy the header code into the source file f.c and then substitute the path to f.c and line number respectively. However, this gave me a duplicate definition error across the different translation units.

Next, I tried to add the static modifier to the header definition of bar2 to allow multiple definitions. I can then compile without errors and run the program, but still only bar.h is printed.

Where am I going wrong? I'm sure there is a more elegant way to do this.

Questions:

Why not just use a debugger like GDB? This is kernel code.

Why not do caller-side debugging? Large code base.

EDIT:

Why does this not work?

```<code>#ifdef DEBUG_PALLOC
#define palloc_get_page(FLAGS) (palloc_get_page_debug (FLAGS,  __FILE__,__LINE__))
#else
void *palloc_get_page (enum palloc_flags);
#endif
</code>```

答:
you could create a delegate, but not a function in the .h as __FILE__ and __LINE__ would be in the .h (and the static modifier doesn't help here), but with a macro which will expand at the proper location with the correct file & line info.

```<code>#define bar2() bar(__FILE__,__LINE__)
</code>```

and bar should accept file & line parameters:

```<code>void bar(const char *file, int line)
{
   printf ("Called from line %d in file %s",line,file);
}
</code>```

The gdb method is more complex. That could work with:

a gdb script that prints the current breakpoint location / traceback and continues,

a collaborating bar function that triggers a breakpoint (On intel/Windows: with the Breakpoint function or asm("int $3") directive, if a flag/env. var is set telling that the debugger is enabled, but if bar is called often, this could slow down the program a lot)

Note: if you want to make it activable or not, this is becoming more complex, but by setting a command line -DDEBUG flag you could make the following print the lines or not:

file bar.h:

```<code>#pragma once
#ifdef DEBUG

#define bar2() bar(__FILE__,__LINE__)
void bar(const char *file, int line);

#else
void bar2();
#endif
</code>```

file bar.c

```<code>#include "bar.h"
#include <stdio.h>

#ifdef DEBUG
void bar(const char *file, int line)
#else
void bar2()
#endif

{
#ifdef DEBUG
   printf ("Called from line %d in file %s\n",line,file);
#endif
   printf("NOP\n");
}
</code>```

call bar2 from your main program. If DEBUG is set, bar2 is a macro that calls bar. If DEBUG isn't set, bar2 is directly your function.

Note that doing that for all your functions is tedious, unless you use a script to generate those patterns.

Body:
Let's say I have

foo () {
  bar ();
}

where foo lies in f.c and bar lies in b.c, i.e. b.h is included in f.c. I would like to modify bar to print that it was called from any function foo that invokes it, like so:

bar () {
  printf ("Called from line %d in file %s",?,?);
  /* Run as usual */
}

I want to obtain these two pieces of information from the predefined GCC preprocessor macros __LINE__ and __FILE__. However, these obviously evaluate to the line of printf in b.c and the path to b.c respectively, if simply plugged into the printf.

Can I somehow propagate the values of __LINE__ and __FILE__ from the calling context to the printf in bar, so "Called from line x in file foo.c" is printed instead?

I attempted to rename bar to bar2 and then define a delegator function in the header file b.h:

bar () {
  printf ("Called from line %d in file %s",__LINE__,__FILE__);
  bar2 ();
}

The idea was that the #include directive would copy the header code into the source file f.c and then substitute the path to f.c and line number respectively. However, this gave me a duplicate definition error across the different translation units.

Next, I tried to add the static modifier to the header definition of bar2 to allow multiple definitions. I can then compile without errors and run the program, but still only bar.h is printed.

Where am I going wrong? I'm sure there is a more elegant way to do this.

Questions:

Why not just use a debugger like GDB? This is kernel code.

Why not do caller-side debugging? Large code base.

EDIT:

Why does this not work?

#ifdef DEBUG_PALLOC
#define palloc_get_page(FLAGS) (palloc_get_page_debug (FLAGS,  __FILE__,__LINE__))
#else
void *palloc_get_page (enum palloc_flags);
#endif

Body:
you could create a delegate, but not a function in the .h as __FILE__ and __LINE__ would be in the .h (and the static modifier doesn't help here), but with a macro which will expand at the proper location with the correct file & line info.

#define bar2() bar(__FILE__,__LINE__)

and bar should accept file & line parameters:

void bar(const char *file, int line)
{
   printf ("Called from line %d in file %s",line,file);
}

The gdb method is more complex. That could work with:

a gdb script that prints the current breakpoint location / traceback and continues,

a collaborating bar function that triggers a breakpoint (On intel/Windows: with the Breakpoint function or asm("int $3") directive, if a flag/env. var is set telling that the debugger is enabled, but if bar is called often, this could slow down the program a lot)

Note: if you want to make it activable or not, this is becoming more complex, but by setting a command line -DDEBUG flag you could make the following print the lines or not:

file bar.h:

#pragma once
#ifdef DEBUG

#define bar2() bar(__FILE__,__LINE__)
void bar(const char *file, int line);

#else
void bar2();
#endif

file bar.c

#include "bar.h"
#include <stdio.h>

#ifdef DEBUG
void bar(const char *file, int line)
#else
void bar2()
#endif

{
#ifdef DEBUG
   printf ("Called from line %d in file %s\n",line,file);
#endif
   printf("NOP\n");
}

call bar2 from your main program. If DEBUG is set, bar2 is a macro that calls bar. If DEBUG isn't set, bar2 is directly your function.

Note that doing that for all your functions is tedious, unless you use a script to generate those patterns.


问:
How can I build a better SPARQL query, to get only the data I want from DBpedia? (was: "How to get rid of multiple rows with DBPEDIA SPARQL")

I run from SPARQL Explorer at DBpedia. I wish to get each President only once, but as some of them have multiple entries for birthplace it gives multiple rows.

```<code>SELECT DISTINCT ?person ?birthPlace  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.
      ?person dbo:birthPlace ?birthPlace .

       OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
       OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .

FILTER ( regex(?birthPlace,   "_")  OR
         regex(?birthPlace, ";_")
       ) .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100
</code>```

I would like to have only the STATE where they are born.

```<code>:Abraham_Lincoln [http] :Hodgenville,_Kentucky [http]   -   -
:Barack_Obama [http]    :Kapiolani_Medical_Center_for_Women_and_Children [http] -   -
:Bill_Clinton [http]    :Hope,_Arkansas [http]  -   -
:Dwight_D._Eisenhower [http]    :Denison,_Texas [http]  -   -
:George_W._Bush [http]  :New_Haven,_Connecticut [http]  -   -
:George_Washington [http]   :Westmoreland_County,_Virginia [http]   -   -
:George_Washington [http]   :British_America [http] -   -
:George_Washington [http]   :George_Washington_Birthplace_National_Monument [http]  -   -
:James_A._Garfield [http]   :Orange,_Ohio [http]    -   -
:James_A._Garfield [http]   :Moreland_Hills,_Ohio [http]    -   -
:Jimmy_Carter [http]    :Plains,_Georgia
</code>```

答:
Focusing on

I would like to have only the STATE where they are born

rather than on

How to get rid of multiple rows with DBPEDIA SPARQL

this could be a solution:

```<code>SELECT DISTINCT ?person ?birthState  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.

       OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
       OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .
       OPTIONAL {?person dbo:birthPlace/dbp:subdivisionType/dbp:territory ?birthState } .

FILTER ( regex(?birthState,   "_")  OR
         regex(?birthState, ";_")
       ) .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100
</code>```

Body:
I run from SPARQL Explorer at DBpedia. I wish to get each President only once, but as some of them have multiple entries for birthplace it gives multiple rows.

SELECT DISTINCT ?person ?birthPlace  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.
      ?person dbo:birthPlace ?birthPlace .

       OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
       OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .

FILTER ( regex(?birthPlace,   "_")  OR
         regex(?birthPlace, ";_")
       ) .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100

I would like to have only the STATE where they are born.

:Abraham_Lincoln [http] :Hodgenville,_Kentucky [http]   -   -
:Barack_Obama [http]    :Kapiolani_Medical_Center_for_Women_and_Children [http] -   -
:Bill_Clinton [http]    :Hope,_Arkansas [http]  -   -
:Dwight_D._Eisenhower [http]    :Denison,_Texas [http]  -   -
:George_W._Bush [http]  :New_Haven,_Connecticut [http]  -   -
:George_Washington [http]   :Westmoreland_County,_Virginia [http]   -   -
:George_Washington [http]   :British_America [http] -   -
:George_Washington [http]   :George_Washington_Birthplace_National_Monument [http]  -   -
:James_A._Garfield [http]   :Orange,_Ohio [http]    -   -
:James_A._Garfield [http]   :Moreland_Hills,_Ohio [http]    -   -
:Jimmy_Carter [http]    :Plains,_Georgia

Body:
Focusing on

I would like to have only the STATE where they are born

rather than on

How to get rid of multiple rows with DBPEDIA SPARQL

this could be a solution:

SELECT DISTINCT ?person ?birthState  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.

       OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
       OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .
       OPTIONAL {?person dbo:birthPlace/dbp:subdivisionType/dbp:territory ?birthState } .

FILTER ( regex(?birthState,   "_")  OR
         regex(?birthState, ";_")
       ) .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100


问:
C# - Declaration of class variables
How can I create a new instance of Boeing737 and use it later in the program. For example I want to be able to create 5 Boeings, do I have to define them like

```<code>Boeing737 boeing1 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

Boeing737 boeing2 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
</code>```

and so on...
Or is there easier way?
Other question, to WHAT can I assign all the properties of boeing1 for example?

Here is my current code:

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Insert the type of boeing that u are using");
        Boeing737 boeing = new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
        Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);
        Console.ReadKey();

    }
}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}
</code>```

}

答:
What about using C# Arrays.

namespace ConsoleApps_examples
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Insert the type of boeing that u are using");

```<code>        //string sname = Console.ReadLine();
        //int ifuel = int.Parse(Console.ReadLine());

        Console.WriteLine(" here are 5 different type of boeing:");

        string sname = "";
        int ifuel = 0;

        int i;
        int[] fuellist = new int[5] { 99, 98, 92, 97, 95 };
        var nameslist = new string[5]  { "XXA1", "XXA2", "XXA3","XXA4","XXA5"};

        //var arr3 = new string[] { "one", "two", "three" };

        for (i = 0; i < 5; i++)
        {
            ifuel = fuellist[i];
            sname = nameslist[i];
            Boeing737 boeing = new Boeing737(name: "Boeing737" + sname, fuel: ifuel, tons: 0);
            Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);

        }

        //Boeing737 boeing = new Boeing737(name: "Boeing737" + sname, fuel: ifuel, tons: 0);
        Console.ReadKey();

    }

}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}
</code>```

}

this is the output:
List of 5 types of Boeing planes:

Title: C# - Declaration of class variables

Body:
How can I create a new instance of Boeing737 and use it later in the program. For example I want to be able to create 5 Boeings, do I have to define them like

Boeing737 boeing1 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

Boeing737 boeing2 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

and so on...
Or is there easier way?
Other question, to WHAT can I assign all the properties of boeing1 for example?

Here is my current code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Insert the type of boeing that u are using");
        Boeing737 boeing = new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
        Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);
        Console.ReadKey();

    }
}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}

}

Body:
What about using C# Arrays.

namespace ConsoleApps_examples
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Insert the type of boeing that u are using");

        //string sname = Console.ReadLine();
        //int ifuel = int.Parse(Console.ReadLine());

        Console.WriteLine(" here are 5 different type of boeing:");

        string sname = "";
        int ifuel = 0;

        int i;
        int[] fuellist = new int[5] { 99, 98, 92, 97, 95 };
        var nameslist = new string[5]  { "XXA1", "XXA2", "XXA3","XXA4","XXA5"};

        //var arr3 = new string[] { "one", "two", "three" };

        for (i = 0; i < 5; i++)
        {
            ifuel = fuellist[i];
            sname = nameslist[i];
            Boeing737 boeing = new Boeing737(name: "Boeing737" + sname, fuel: ifuel, tons: 0);
            Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);

        }

        //Boeing737 boeing = new Boeing737(name: "Boeing737" + sname, fuel: ifuel, tons: 0);
        Console.ReadKey();

    }

}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}

}

this is the output:
List of 5 types of Boeing planes:


问:
Transform a "multiple line" - function into a "one line" - function
I try to transform a function that consists of multiple lines into a function that only consists of one line.

The multiple-line function looks like this:

```<code>text =  “Here is a tiny example.”

def add_text_to_list(text):
             new_list = []
             split_text = text.splitlines() #split words in text and change type from “str” to “list”
             for line in split_text:
                 cleared_line = line.strip() #each line of split_text is getting stripped
                 if cleared_line:
                     new_list.append(cleared_line)
             return new_list
</code>```

I 100% understand how this function works and what it does, yet I have trouble implementing this into a valid “oneliner”. I also know that I need to come up with a list comprehension. What I'm trying to do is this (in chronological order):

```<code>1. split words of text with text.splitlines()
2. strip lines of text.splitlines with line.strip()
3. return modified text after both of these steps
</code>```

The best I came up with:

```<code>def one_line_version(text):
  return [line.strip() for line in text.splitlines()] #step 1 is missing
</code>```

I appreciate any kind of help.

Edit: Thanks @Tenfrow!

答:
You forgot about if in the list comprehension

```<code>def add_text_to_list(text):
    return [line.strip() for line in text.splitlines() if line.strip()]
</code>```

Body:
I try to transform a function that consists of multiple lines into a function that only consists of one line.

The multiple-line function looks like this:

text =  “Here is a tiny example.”

def add_text_to_list(text):
             new_list = []
             split_text = text.splitlines() #split words in text and change type from “str” to “list”
             for line in split_text:
                 cleared_line = line.strip() #each line of split_text is getting stripped
                 if cleared_line:
                     new_list.append(cleared_line)
             return new_list

I 100% understand how this function works and what it does, yet I have trouble implementing this into a valid “oneliner”. I also know that I need to come up with a list comprehension. What I'm trying to do is this (in chronological order):

1. split words of text with text.splitlines()
2. strip lines of text.splitlines with line.strip()
3. return modified text after both of these steps

The best I came up with:

def one_line_version(text):
  return [line.strip() for line in text.splitlines()] #step 1 is missing

I appreciate any kind of help.

Edit: Thanks @Tenfrow!

Body:
You forgot about if in the list comprehension

def add_text_to_list(text):
    return [line.strip() for line in text.splitlines() if line.strip()]


问:
CSS - First-letter selection not working with ID
My CSS :first-letter selector works with all p elements, but with a span that has an id #fletter it won't work...

```<code>#fletter span:first-letter {
    font-weight: 600;
font-size: 25px;
}
</code>```

```<code><span id="fletter">
</code>```

The selector works fine with my p elements, though.

```<code>p:first-letter {
font-weight: 600;
font-size: 25px;
}
</code>```

```<code><p>Lorem Ipsum</p>
</code>```

答:
I might be missing something but you are lacking the requires 2 colons.
This works perfectly fine for me in Chrome etc:</p>

```<code>#<idname>::first-letter{
    color: green;
    font-size: 100px;
}
</code>```

Body:
My CSS :first-letter selector works with all p elements, but with a span that has an id #fletter it won't work...

#fletter span:first-letter {
    font-weight: 600;
font-size: 25px;
}

The selector works fine with my p elements, though.

p:first-letter {
font-weight: 600;
font-size: 25px;
}

Lorem Ipsum

Body:
I might be missing something but you are lacking the requires 2 colons.
This works perfectly fine for me in Chrome etc:

#<idname>::first-letter{
    color: green;
    font-size: 100px;
}


问:
Jenkins pipeline agent with label or node call slave node?
Someone ask about how to create an agent and it create a slave node (here), and I don't know if it's true or no :

agent {
  label 'my-defined-label'
}
```

<p>and</p>

<pre class="lang-groovy prettyprint-override"><code>agent {
  node {
    label 'my-defined-label'
    customWorkspace '/some/other/path'
  }
}
</code>```

So 'my-defined-label' is just slave name?

Thanks for the answers

答:
It can match an exact node name, a label, any other supported label expression. For example, java8 && linux, (docker || java) && !windows , and corp-agent-node-01-name are all valid label syntax.

The documentation is clear about how the built in syntax works:

Allocates an executor on a node (typically a slave) and runs further code in the context of a workspace on that slave.

label - Computer name, label name, or any other label expression like linux && 64bit to restrict where this step builds. May be left blank, in which case any available executor is taken.

Valid Operators

The following operators are supported, in the order of precedence.

(expr) - parenthesis

!expr - negation

expr&&expr - and

expr||expr - or

a -> b - "implies" operator. Equivalent to !a|b. For example, windows->x64 could be thought of as "if run on a Windows slave, that slave must be 64bit." *It still allows Jenkins to run this build on linux.

a <-> b - "if and only if" operator. Equivalent to a&&b || !a&&!b. For example, windows<->sfbay could be thought of as "if run on a Windows slave, that slave must be in the SF bay area, but if not on Windows, it must not be in the bay area."

All operators are left-associative (i.e., a->b->c <-> (a->b)->c ) An expression can contain whitespace for better readability, and it'll be ignored.

Label names or slave names can be quoted if they contain unsafe characters. For example, "jenkins-solaris (Solaris)" || "Windows 2008"

Body:
Someone ask about how to create an agent and it create a slave node (here), and I don't know if it's true or no :

agent {
  label 'my-defined-label'
}

and

agent {
  node {
    label 'my-defined-label'
    customWorkspace '/some/other/path'
  }
}

So 'my-defined-label' is just slave name?

Thanks for the answers


问:
How to copy artifact .jar and export classpath or it can be added to JAVA_HOME/lib/ext
I'm trying to install https://github.com/awslabs/kinesis-kafka-connector and one of the steps after building a jar is:

```<code>Copy artifact amazon-kinesis-kafka-connector-0.0.X.jar and export classpath or it can be added to JAVA_HOME/lib/ext
</code>```

I can't find the ext folder in my JAVA_HOME/lib:

```<code>$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home

$ ls /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib

ant-javafx.jar  dt.jar      javafx-mx.jar   missioncontrol
packager.jar    tools.jar
ct.sym      ir.idl      jconsole.jar    orb.idl     sa-jdi.jar  visualvm
</code>```

Should I be creating an ext folder here and then copying the jar to it or is there any other way to do this? Also, I use intelliJ as my IDE. Thank you!

答:
You just need to add this jar to classpath.

Here is already answer for Idea:
add jar to Idea classpath of your project

But i recommend you to start using dependency management tools, for ex. maven or gradle. :)

Body:
I'm trying to install https://github.com/awslabs/kinesis-kafka-connector and one of the steps after building a jar is:

Copy artifact amazon-kinesis-kafka-connector-0.0.X.jar and export classpath or it can be added to JAVA_HOME/lib/ext

I can't find the ext folder in my JAVA_HOME/lib:

$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home

$ ls /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/lib

ant-javafx.jar  dt.jar      javafx-mx.jar   missioncontrol
packager.jar    tools.jar
ct.sym      ir.idl      jconsole.jar    orb.idl     sa-jdi.jar  visualvm

Should I be creating an ext folder here and then copying the jar to it or is there any other way to do this? Also, I use intelliJ as my IDE. Thank you!


问:
How to format my time display to show daylight savings label?
my time is showing like this

moment(date).tz(TimeZone).format('h:mm a z')

1:02 p.m. EST

what I would like it for it to say

1:02 p.m. EDT

how can i change it to daylight savings time

答:
Whenever it comes to issues such as date or time, if you want to get a tailored result it helps to refactor code to a sort of date class.  Fortunately, dateJS a javascript library that deals with date and time could help you out.

In reference to displaying daylight savings time, this example gives you what you want.

getTimezoneAbbreviation

```<code>Date.getTimezoneAbbreviation ( Number timezoneOffset, Boolean isDayLightSavingsTime ) : String

Returns a culture-specific timezone abbreviation based on a given offset and a boolean indicating whether daylight savings time is in effect.

Parameters
{Number timezoneOffset} The year.
{Boolean isDayLightSavingsTime} Whether the date instance is observing Daylight Saving Time (Summer Time)
Return Value
{String} The timezone abbreviation

Example
var today = Date.today(); Date.getTimezoneAbbreviation(today.getTimezoneOffset, today.isDayLightSavingsTime()); // "UTC", "GMT", "EST", "PDT", etc.
</code>```

Body:
Whenever it comes to issues such as date or time, if you want to get a tailored result it helps to refactor code to a sort of date class.  Fortunately, dateJS a javascript library that deals with date and time could help you out.

In reference to displaying daylight savings time, this example gives you what you want.

getTimezoneAbbreviation

Date.getTimezoneAbbreviation ( Number timezoneOffset, Boolean isDayLightSavingsTime ) : String

Returns a culture-specific timezone abbreviation based on a given offset and a boolean indicating whether daylight savings time is in effect.

Parameters
{Number timezoneOffset} The year.
{Boolean isDayLightSavingsTime} Whether the date instance is observing Daylight Saving Time (Summer Time)
Return Value
{String} The timezone abbreviation

Example
var today = Date.today(); Date.getTimezoneAbbreviation(today.getTimezoneOffset, today.isDayLightSavingsTime()); // "UTC", "GMT", "EST", "PDT", etc.


问:
Java equivalent of Perl's hash
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

```<code>$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}
</code>```

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

答:
First of all, your specific example ($hash{AREA_CODE}->{PHONE}->{STREET_ADDR}), with hard-coded strings as hash keys, is not really a useful data structure in Java as Michael Carman pointed out - it should be stored as a class with attributes (and to be honest it's a bad data structure in concept - data like this is more likely to be an array of phones, not hash of phones).

Second, assuming you actually meant $hash{$AREA_CODE}->{$PHONE}->{$STREET_ADDR}, it looks like everyone's Java code so far was NOT implementing a generic equivalent code - the code all assumed that the Java hash is newly initialized for storing example OR fully populated for retrieval example (in other words, as leonbloy's answer noted, is missing autovivification feature).

The correct code mimiquing autovivification is:

```<code>// This method will ensure that hash-of-hash-of-hashes structure exists of a given set of 3 keys.
public HashMap<String, HashMap<String, HashMap<String, Object>>>
 autovivification_3rd_level (
           HashMap<String, HashMap<String, HashMap<String, Object>>> hash
         , String AREA_CODE, String PHONE, String STREET_ADDR) {
    if (hash == null) {
        hash = new HashMap<String, HashMap<String, HashMap<String, Object>>>();
    }
    if (!hash.contains(AREA_CODE) || hash.get(AREA_CODE) == null) {
        hash.put(new HashMap<String, HashMap<String, Object>>());
    }
    HashMap<String, HashMap<String, Object>> AREA_CODE_hash
         = (HashMap<String, HashMap<String, Object>>) hash.get(AREA_CODE);
    if (!AREA_CODE_hash.contains(PHONE) || AREA_CODE_hash.get(PHONE) == null) {
        AREA_CODE_hash.put(new HashMap<String, Object>());
    }
    return hash;
}

////////////////////////////////////////////////////////////////////////////////////

// Equivalent to Perl's "$hash{$AREA_CODE}->{$PHONE}->{$STREET_ADDR} = value;"
public Object put_3d_level_hash(
          HashMap<String, HashMap<String, HashMap<String, Object>>> hash
        , String AREA_CODE, String PHONE, String STREET_ADDR,
        , Object value) {
    hash = autovivification_3rd_level(hash, AREA_CODE, PHONE, STREET_ADDR);
    return hash.get(AREA_CODE).get(PHONE).put(STREET_ADDR, value);
}
put_3d_level_hash(hash, AREA_CODE, PHONE, STREET_ADDR, obj);

////////////////////////////////////////////////////////////////////////////////////

// Equivalent to Perl's "$var = $hash{$AREA_CODE}->{$PHONE}->{$STREET_ADDR}"
public Object get_3d_level_hash(HashMap<String, HashMap<String, HashMap<String, Object>>> hash
                       , String AREA_CODE, String PHONE, String STREET_ADDR) {
    hash = autovivification_3rd_level(hash, AREA_CODE, PHONE, STREET_ADDR);
    return hash.get(AREA_CODE).get(PHONE).get(STREET_ADDR);
}
Object obj = get_3d_level_hash(hash, AREA_CODE, PHONE, STREET_ADDR);
</code>```

Title: Java equivalent of Perl's hash

Body:
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

Body:
First of all, your specific example ($hash{AREA_CODE}->{PHONE}->{STREET_ADDR}), with hard-coded strings as hash keys, is not really a useful data structure in Java as Michael Carman pointed out - it should be stored as a class with attributes (and to be honest it's a bad data structure in concept - data like this is more likely to be an array of phones, not hash of phones).

Second, assuming you actually meant $hash{$AREA_CODE}->{$PHONE}->{$STREET_ADDR}, it looks like everyone's Java code so far was NOT implementing a generic equivalent code - the code all assumed that the Java hash is newly initialized for storing example OR fully populated for retrieval example (in other words, as leonbloy's answer noted, is missing autovivification feature).

The correct code mimiquing autovivification is:

// This method will ensure that hash-of-hash-of-hashes structure exists of a given set of 3 keys.
public HashMap<String, HashMap<String, HashMap<String, Object>>>
 autovivification_3rd_level (
           HashMap<String, HashMap<String, HashMap<String, Object>>> hash
         , String AREA_CODE, String PHONE, String STREET_ADDR) {
    if (hash == null) {
        hash = new HashMap<String, HashMap<String, HashMap<String, Object>>>();
    }
    if (!hash.contains(AREA_CODE) || hash.get(AREA_CODE) == null) {
        hash.put(new HashMap<String, HashMap<String, Object>>());
    }
    HashMap<String, HashMap<String, Object>> AREA_CODE_hash
         = (HashMap<String, HashMap<String, Object>>) hash.get(AREA_CODE);
    if (!AREA_CODE_hash.contains(PHONE) || AREA_CODE_hash.get(PHONE) == null) {
        AREA_CODE_hash.put(new HashMap<String, Object>());
    }
    return hash;
}

////////////////////////////////////////////////////////////////////////////////////

// Equivalent to Perl's "$hash{$AREA_CODE}->{$PHONE}->{$STREET_ADDR} = value;"
public Object put_3d_level_hash(
          HashMap<String, HashMap<String, HashMap<String, Object>>> hash
        , String AREA_CODE, String PHONE, String STREET_ADDR,
        , Object value) {
    hash = autovivification_3rd_level(hash, AREA_CODE, PHONE, STREET_ADDR);
    return hash.get(AREA_CODE).get(PHONE).put(STREET_ADDR, value);
}
put_3d_level_hash(hash, AREA_CODE, PHONE, STREET_ADDR, obj);

////////////////////////////////////////////////////////////////////////////////////

// Equivalent to Perl's "$var = $hash{$AREA_CODE}->{$PHONE}->{$STREET_ADDR}"
public Object get_3d_level_hash(HashMap<String, HashMap<String, HashMap<String, Object>>> hash
                       , String AREA_CODE, String PHONE, String STREET_ADDR) {
    hash = autovivification_3rd_level(hash, AREA_CODE, PHONE, STREET_ADDR);
    return hash.get(AREA_CODE).get(PHONE).get(STREET_ADDR);
}
Object obj = get_3d_level_hash(hash, AREA_CODE, PHONE, STREET_ADDR);


问:
How to divide larger number by smaller
I am trying to divide the larger number in this problem by the smaller number and print the answer in a quotient form. I have done the code to where it will print the correct answer, but I am wondering how to divide the larger by smaller number. Do I use an if statement?</p>

```<code>case 1:
    int number1;
    int number2;

    System.out.println("Please enter your first number");
    number1 = s.nextInt();

    System.out.println("Please enter your second number");
    number2 = s.nextInt();

    int quotient = number1 / number2;
    int remainder = number1 % number2;

    if(number1 > number2 || number2 > number1) {
        System.out.println("Quotient = " + quotient + "r" + remainder);
    }

    break;
</code>```

答:
maybe something like that:

```<code>int smallerNumber;
int biggerNumber;

System.out.println("Please enter your first number");
smallerNumber = s.nextInt();

int temp;
System.out.println("Please enter your second number");
temp =  s.nextInt();

smallerNumber=Math.min(temp,smallerNumber);
biggerNumber=Math.max(temp,smallerNumber);
</code>```

Or using array and then sort it:

```<code>List<Integer> arr= new ArrayList<>(2);

System.out.println("Please enter your first number");
arr.add( s.nextInt());

System.out.println("Please enter your second number");
arr.add( s.nextInt());

Collections.sort(arr);

//now arr.get(0) is smaller and arr.get(1) is bigger
</code>```

Title: How to divide larger number by smaller

Body:
I am trying to divide the larger number in this problem by the smaller number and print the answer in a quotient form. I have done the code to where it will print the correct answer, but I am wondering how to divide the larger by smaller number. Do I use an if statement?

case 1:
    int number1;
    int number2;

    System.out.println("Please enter your first number");
    number1 = s.nextInt();

    System.out.println("Please enter your second number");
    number2 = s.nextInt();

    int quotient = number1 / number2;
    int remainder = number1 % number2;

    if(number1 > number2 || number2 > number1) {
        System.out.println("Quotient = " + quotient + "r" + remainder);
    }

    break;

Body:
maybe something like that:

int smallerNumber;
int biggerNumber;

System.out.println("Please enter your first number");
smallerNumber = s.nextInt();

int temp;
System.out.println("Please enter your second number");
temp =  s.nextInt();

smallerNumber=Math.min(temp,smallerNumber);
biggerNumber=Math.max(temp,smallerNumber);

Or using array and then sort it:

List<Integer> arr= new ArrayList<>(2);

System.out.println("Please enter your first number");
arr.add( s.nextInt());

System.out.println("Please enter your second number");
arr.add( s.nextInt());

Collections.sort(arr);

//now arr.get(0) is smaller and arr.get(1) is bigger


问:
Rasterization of contours in filled contour plot
I have a filled contour plot, which I wish to save as an .svg or .pdf file. The following is a simplified example. I want to rasterize the contour plot itself (the colorful part!), while keeping everything else (all axes, labels etc.) as vector graphics.

```<code>import numpy as np
import matplotlib.pylab as plt

x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, 2*np.pi, 100)
xi, yi = np.meshgrid(x, y)
zi = np.cos(xi)**2 + np.sin(yi)**2

plt.figure()
plt.contourf(xi, yi, zi, rasterized=True)
plt.savefig('fig.svg', dpi=100)
</code>```

However, when I inspect fig.svg or open it for editing in Inkscape (I am able to ungroup the filled contour into vector shapes) it is clear that rasterization has not worked!

That's fine for such a simple plot, but if my plot has a higher number of contour levels (below) the vector image will need many many curves and the filesize would be much bigger.

```<code>plt.close()
plt.figure()
plt.contourf(xi, yi, zi, 100, rasterized=True)
plt.savefig('fig.svg', dpi=100)
</code>```

Can someone please suggest a solution and explain why this rasterized=True flag has not done what I require?

答:
I just found this is a duplicate of this question.

Using rasterized=True as argument to contour or contourf should show a

```UserWarning: The following kwargs were not used by contour: 'rasterized'```

In order to rasterize a contour plot, you need to rasterize its individual parts, i.e.

```<code>cs = plt.contour(...)
for c in cs.collections:
    c.set_rasterized(True)
</code>```

The example from the question would hence look like

```<code>import numpy as np
import matplotlib.pylab as plt

x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, 2*np.pi, 100)
xi, yi = np.meshgrid(x, y)
zi = np.cos(xi)**2 + np.sin(yi)**2

plt.figure()
cs = plt.contourf(xi, yi, zi)

for c in cs.collections:
    c.set_rasterized(True)

plt.savefig('fig.svg', dpi=100)
</code>```

Body:
I have a filled contour plot, which I wish to save as an .svg or .pdf file. The following is a simplified example. I want to rasterize the contour plot itself (the colorful part!), while keeping everything else (all axes, labels etc.) as vector graphics.

import numpy as np
import matplotlib.pylab as plt

x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, 2*np.pi, 100)
xi, yi = np.meshgrid(x, y)
zi = np.cos(xi)**2 + np.sin(yi)**2

plt.figure()
plt.contourf(xi, yi, zi, rasterized=True)
plt.savefig('fig.svg', dpi=100)

However, when I inspect fig.svg or open it for editing in Inkscape (I am able to ungroup the filled contour into vector shapes) it is clear that rasterization has not worked!

That's fine for such a simple plot, but if my plot has a higher number of contour levels (below) the vector image will need many many curves and the filesize would be much bigger.

plt.close()
plt.figure()
plt.contourf(xi, yi, zi, 100, rasterized=True)
plt.savefig('fig.svg', dpi=100)

Can someone please suggest a solution and explain why this rasterized=True flag has not done what I require?

Body:
I just found this is a duplicate of this question.

Using rasterized=True as argument to contour or contourf should show a

UserWarning: The following kwargs were not used by contour: 'rasterized'

In order to rasterize a contour plot, you need to rasterize its individual parts, i.e.

cs = plt.contour(...)
for c in cs.collections:
    c.set_rasterized(True)

The example from the question would hence look like

import numpy as np
import matplotlib.pylab as plt

x = np.linspace(0, 2*np.pi, 100)
y = np.linspace(0, 2*np.pi, 100)
xi, yi = np.meshgrid(x, y)
zi = np.cos(xi)**2 + np.sin(yi)**2

plt.figure()
cs = plt.contourf(xi, yi, zi)

for c in cs.collections:
    c.set_rasterized(True)

plt.savefig('fig.svg', dpi=100)


问:
How to get the last index from a String in a for loop
I am trying to make a program which checks if input String is palindrome. I finally managed to do it converting it to char array first, but I couldn't figure out how to access the last index from the String in for loop.

```<code>import java.util.Scanner;

public class Task8 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        boolean isPalindrome = true;

        System.out.println("Please, enter string!");
        String str = sc.nextLine();
        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            if(chars[i]!= chars[chars.length-i-1]){
                isPalindrome = false;
                break;
            }
        }
        if(isPalindrome){
            System.out.println("It is palindrome!");
        }
        if(!isPalindrome){
            System.out.println("It isnt a palindrome!");
        }
    }
}
</code>```

This is the final result it it looks like it is working, but eclipse returns errors if I try something like:

```<code>for(int i = 0; i < str.length(); i++){
        if(str.charAt(i)!= str.charAt(str.length(-1-i)){
            isPalindrome = false;
            break;
        }
    }
</code>```

It is working if i put -1-i outside the the braces (str.charAt(i)!= str.charAt(str.length()-1-i)), but why on the first index it lets me put i in the braces and for the last index I can't use i and -1 inside braces ?

答:
The length() method doesn't take any parameters.
It's the charAt(...) method that takes an index parameter.

And btw it's enough to go until the middle of the input string.

```<code>for (int i = 0; i < str.length() / 2; i++) {
    if (str.charAt(i) != str.charAt(str.length() -i - 1)) {
        isPalindrome = false;
        break;
    }
}
</code>```

Body:
I am trying to make a program which checks if input String is palindrome. I finally managed to do it converting it to char array first, but I couldn't figure out how to access the last index from the String in for loop.

import java.util.Scanner;

public class Task8 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        boolean isPalindrome = true;

        System.out.println("Please, enter string!");
        String str = sc.nextLine();
        char[] chars = str.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            if(chars[i]!= chars[chars.length-i-1]){
                isPalindrome = false;
                break;
            }
        }
        if(isPalindrome){
            System.out.println("It is palindrome!");
        }
        if(!isPalindrome){
            System.out.println("It isnt a palindrome!");
        }
    }
}

This is the final result it it looks like it is working, but eclipse returns errors if I try something like:

for(int i = 0; i < str.length(); i++){
        if(str.charAt(i)!= str.charAt(str.length(-1-i)){
            isPalindrome = false;
            break;
        }
    }

It is working if i put -1-i outside the the braces (str.charAt(i)!= str.charAt(str.length()-1-i)), but why on the first index it lets me put i in the braces and for the last index I can't use i and -1 inside braces ?

Body:
The length() method doesn't take any parameters.
It's the charAt(...) method that takes an index parameter.

And btw it's enough to go until the middle of the input string.

for (int i = 0; i < str.length() / 2; i++) {
    if (str.charAt(i) != str.charAt(str.length() -i - 1)) {
        isPalindrome = false;
        break;
    }
}


问:
Recursive function returning bool
I can't understand the following recursive function returning a  bool.

```<code> bool p(int a[], int inf, int sup) {
    if(sup==inf)
        if(a[inf]>0)
            return true;
        else
            return false;
    int m=(inf+sup)/2;
    bool left=p(a,inf,m);
    bool right=p(a,m+1,sup);
    return left && right;
}
</code>```

It should return true if all the elements in (inf, sup) are positive or else false, but I can't see how the elements that are not at the two extrema of the array are considered, since the condition that is tested is that a[inf]>0 and inf is not changed during recursion for left, while it gets values only in the right part of the array for right.

So basically, since it is different from easier recursions (like the factorial or Fibonacci) I can't understand how recursion works here: I tried to start from the base case and go on to the second step but it is unclear how to proceed.

Can anyone suggest me how to follow the recursion in this case to understand how this function returns true iff all the elements in (inf, sup) are positive?

答:
If the collection has one element, return the answer for that element.  No recusion is needed to further simplify the problem.

If the collection has more than one element, split the collection in half and recurse on each half.

Every element in the collection will eventually be considered as a one-element collection.

Title: Recursive function returning bool

Body:
I can't understand the following recursive function returning a  bool.

 bool p(int a[], int inf, int sup) {
    if(sup==inf)
        if(a[inf]>0)
            return true;
        else
            return false;
    int m=(inf+sup)/2;
    bool left=p(a,inf,m);
    bool right=p(a,m+1,sup);
    return left && right;
}

It should return true if all the elements in (inf, sup) are positive or else false, but I can't see how the elements that are not at the two extrema of the array are considered, since the condition that is tested is that a[inf]>0 and inf is not changed during recursion for left, while it gets values only in the right part of the array for right.

So basically, since it is different from easier recursions (like the factorial or Fibonacci) I can't understand how recursion works here: I tried to start from the base case and go on to the second step but it is unclear how to proceed.

Can anyone suggest me how to follow the recursion in this case to understand how this function returns true iff all the elements in (inf, sup) are positive?


问:
How to get ImageView scale to fill the layout as much as the width permits
What I want is for the ImageView to scale with the same ratio to fill the layout without being cropped. Since the width is going to match first, effectively, this means scaling until the width is maximized.

My code is:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    ImageView img = findViewById(R.id.displayImg);
    img.setImageBitmap(bmp); // bmp is a public static Bitmap set by another class
    img.setRotation(90);
    img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
</code>```

My layout is:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/displayImg" />

</android.support.constraint.ConstraintLayout>
</code>```

As per Android ImageView ScaleType: A Visual Guide CENTER_INSIDE should

Scale the image uniformly (maintain the image’s aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

The black image is what I'm currently, and I've drawn what I believe I should be seeing instead (as you can tell, I'm the modern-day Michelangelo).

答:
wrap_content if the reason why.... change that to fill_parent or match_parent.

Take a look at this:
https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

CENTER_INSIDE Scale the image uniformly (maintain the image's aspect
  ratio) so that both dimensions (width and height) of the image will be
  equal to or less than the corresponding dimension of the view (minus
  padding).

If the ratio of your image is off, it wont stretch.

Java

```<code>imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
</code>```

XML

```<code>android:scaleType="fitCenter"
</code>```

side note: fillXY might be better.

ContentLicense: CC BY-SA 4.0

Body:
What I want is for the ImageView to scale with the same ratio to fill the layout without being cropped. Since the width is going to match first, effectively, this means scaling until the width is maximized.

My code is:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    ImageView img = findViewById(R.id.displayImg);
    img.setImageBitmap(bmp); // bmp is a public static Bitmap set by another class
    img.setRotation(90);
    img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}

My layout is:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/displayImg" />

</android.support.constraint.ConstraintLayout>

As per Android ImageView ScaleType: A Visual Guide CENTER_INSIDE should

Scale the image uniformly (maintain the image’s aspect ratio) so that both dimensions (width and height) of the image will be equal to or less than the corresponding dimension of the view (minus padding).

The black image is what I'm currently, and I've drawn what I believe I should be seeing instead (as you can tell, I'm the modern-day Michelangelo).

Body:
wrap_content if the reason why.... change that to fill_parent or match_parent.

Take a look at this:
https://developer.android.com/reference/android/widget/ImageView.ScaleType.html

CENTER_INSIDE Scale the image uniformly (maintain the image's aspect
  ratio) so that both dimensions (width and height) of the image will be
  equal to or less than the corresponding dimension of the view (minus
  padding).

If the ratio of your image is off, it wont stretch.

Java

imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

XML

android:scaleType="fitCenter"

side note: fillXY might be better.


问:
AWS - is there a way to receive events asynchronously without the lambda
I have a general AWS question. I have started using AWS sdk, but looks like if I want to receive events asynchronously from AWS(ex: cloudwatch events), lambda functions is the only way. I want to write a simple application that registers a callback to AWS for events, but i couldn't find a way to do that till now, since i don't want to use lambda, i have been polling from my application. Please, let me know if polling is the only option or if there is a better way to resolve it without polling.</p>

答:
With cloudwatch events, you can set rules and trigger a number of different targets, including SQS queues which you can poll from your EC2 Instances.

Lambda is certainly a popular endpoint, but based on the docs, there are other targets you can send the events to


问:
How to use wildcard with dnsmasq in ubuntu 16.04
04
I am trying to config wildcard in the host file

```<code>127.0.0.1 *.example.com
</code>```

so i installed dnsmasq
I have tried

```<code>echo address=/example/127.0.0.1/ | sudo tee -a /etc/NetworkManager/dnsmasq.d/local
echo address=/.example/127.0.0.1/ | sudo tee -a /etc/NetworkManager/dnsmasq.d/local
sudo /etc/init.d/dnsmasq restart
sudo service network-manager restart
</code>```

followed answers of:

Wildcard Virtual Hosts Ubuntu

But nothing has worked so far.

答:
what you can do is

```<code>sudo echo 'address=/example.com/127.0.0.1'  >> /etc/dnsmasq.conf
</code>```

is equivalent to

```<code>*.example.com
</code>```

or

```<code>*.*.*.example.com
</code>```

and restart the dnsmasq service

```<code>sudo /etc/init.d/dnsmasq restart
</code>```

I think this will do the trick.

Body:
04
I am trying to config wildcard in the host file

127.0.0.1 *.example.com

so i installed dnsmasq
I have tried

echo address=/example/127.0.0.1/ | sudo tee -a /etc/NetworkManager/dnsmasq.d/local
echo address=/.example/127.0.0.1/ | sudo tee -a /etc/NetworkManager/dnsmasq.d/local
sudo /etc/init.d/dnsmasq restart
sudo service network-manager restart

followed answers of:

Wildcard Virtual Hosts Ubuntu

But nothing has worked so far.

Body:
what you can do is

sudo echo 'address=/example.com/127.0.0.1'  >> /etc/dnsmasq.conf

is equivalent to

*.example.com

or

*.*.*.example.com

and restart the dnsmasq service

sudo /etc/init.d/dnsmasq restart

I think this will do the trick.


问:
Permission error when I install keras package in Program Files
I need to instal keras package i have anaconda3 and python 2.7.13 and windows 10 OS
where i execut this line

```<code> pip install keras
</code>```

give me this error :

```<code> (C:\Program Files\Anaconda) C:\Users\User-47>pip install keras
    Collecting keras
    Using cached Keras-2.1.2-py2.py3-none-any.whl
    Requirement already satisfied: scipy>=0.14 in c:\program
    files\anaconda\lib\site-packages (from keras)
Requirement already satisfied: numpy>=1.9.1 in c:\program files\anaconda\lib\site-packages (from keras)
Requirement already satisfied: pyyaml in c:\program files\anaconda\lib\site-packages (from keras)
Requirement already satisfied: six>=1.9.0 in c:\program files\anaconda\lib\site-packages (from keras)
Installing collected packages: keras
Exception:
Traceback (most recent call last):
  File "C:\Program Files\Anaconda\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Program Files\Anaconda\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "C:\Program Files\Anaconda\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "C:\Program Files\Anaconda\lib\site-packages\pip\req\req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "C:\Program Files\Anaconda\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "C:\Program Files\Anaconda\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "C:\Program Files\Anaconda\lib\site-packages\pip\wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "C:\Program Files\Anaconda\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "C:\Program Files\Anaconda\lib\os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [WinError 5] Accès refusé: 'C:\\Program Files\\Anaconda\\Lib\\site-packages\\keras'
</code>```

答:
The answer is in the exception: PermissionError: [WinError 5] Accès refusé: 'C:\\Program Files\\Anaconda\\Lib\\site-packages\\keras'.  Installing files in C:\Program Files requires an administrator account, not a user account.  Whoever installed Anaconda on the machine either used an admin account or gave an admin password in a UserAccessControl (UAC) box.  I am slightly surprised that you did not see such a box, but I guess it depends on the Windows version and settings.

People who install Anaconda just for their user account have to put it or let it be put somewhere else.

Body:
I need to instal keras package i have anaconda3 and python 2.7.13 and windows 10 OS
where i execut this line

 pip install keras

give me this error :

 (C:\Program Files\Anaconda) C:\Users\User-47>pip install keras
    Collecting keras
    Using cached Keras-2.1.2-py2.py3-none-any.whl
    Requirement already satisfied: scipy>=0.14 in c:\program
    files\anaconda\lib\site-packages (from keras)
Requirement already satisfied: numpy>=1.9.1 in c:\program files\anaconda\lib\site-packages (from keras)
Requirement already satisfied: pyyaml in c:\program files\anaconda\lib\site-packages (from keras)
Requirement already satisfied: six>=1.9.0 in c:\program files\anaconda\lib\site-packages (from keras)
Installing collected packages: keras
Exception:
Traceback (most recent call last):
  File "C:\Program Files\Anaconda\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "C:\Program Files\Anaconda\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "C:\Program Files\Anaconda\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "C:\Program Files\Anaconda\lib\site-packages\pip\req\req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "C:\Program Files\Anaconda\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "C:\Program Files\Anaconda\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "C:\Program Files\Anaconda\lib\site-packages\pip\wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "C:\Program Files\Anaconda\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "C:\Program Files\Anaconda\lib\os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [WinError 5] Accès refusé: 'C:\\Program Files\\Anaconda\\Lib\\site-packages\\keras'


答: str.length(-1-i) is not a correct syntax, str.length() API doesn't accept any arguments and it's sole purpose is to give you the length of the given string.

Title: How to get the last index from a String in a for loop


问:
import matplotlib ImportError: DLL load failed: The specified procedure could not be found
I'm using the Anaconda Python distribution: Python 2.7 x64 with Windows 7 SP1 x64 Ultimate. Today after conda update --all importing matplotlib has broken:

```<code>ImportError                               Traceback (most recent call last)
<ipython-input-4-6f467123fe04> in <module>()
----> 1 import matplotlib.pyplot

C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\pyplot.py in <module>()
 27 from cycler import cycler
 28 import matplotlib
---> 29 import matplotlib.colorbar
 30 from matplotlib import style
 31 from matplotlib import _pylab_helpers, interactive

C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\colorbar.py in <module>()
 34 import matplotlib.collections as collections
 35 import matplotlib.colors as colors
---> 36 import matplotlib.contour as contour
 37 import matplotlib.cm as cm
 38 import matplotlib.gridspec as gridspec

C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\contour.py in <module>()
 19 import matplotlib.colors as colors
 20 import matplotlib.collections as mcoll
---> 21 import matplotlib.font_manager as font_manager
 22 import matplotlib.text as text
 23 import matplotlib.cbook as cbook

C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\font_manager.py in <module>()
 56
 57 import matplotlib
---> 58 from matplotlib import afm, cbook, ft2font, rcParams, get_cachedir
 59 from matplotlib.compat import subprocess
 60 from matplotlib.fontconfig_pattern import (

ImportError: DLL load failed: The specified procedure could not be found.
</code>```

Do you have any ideas how to roll back to stable version or what to downgrade?

conda install anaconda and conda update anaconda do not change any packages.
My current conda version is 4.3.30, matplotlib version is 2.1.0.

答:
I got the same error. In my case it was Microsoft CNTK was the culprit. I uninstalled it and issue resolved.
Platform : Windows 10 (64 Bit)
Anaconda : 5
Python : 2.x</p>

Body:
I'm using the Anaconda Python distribution: Python 2.7 x64 with Windows 7 SP1 x64 Ultimate. Today after conda update --all importing matplotlib has broken:

ImportError                               Traceback (most recent call last)
<ipython-input-4-6f467123fe04> in <module>()
----> 1 import matplotlib.pyplot

C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\pyplot.py in <module>()
 27 from cycler import cycler
 28 import matplotlib
---> 29 import matplotlib.colorbar
 30 from matplotlib import style
 31 from matplotlib import _pylab_helpers, interactive

C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\colorbar.py in <module>()
 34 import matplotlib.collections as collections
 35 import matplotlib.colors as colors
---> 36 import matplotlib.contour as contour
 37 import matplotlib.cm as cm
 38 import matplotlib.gridspec as gridspec

C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\contour.py in <module>()
 19 import matplotlib.colors as colors
 20 import matplotlib.collections as mcoll
---> 21 import matplotlib.font_manager as font_manager
 22 import matplotlib.text as text
 23 import matplotlib.cbook as cbook

C:\Users\felagund\Anaconda\lib\site-packages\matplotlib\font_manager.py in <module>()
 56
 57 import matplotlib
---> 58 from matplotlib import afm, cbook, ft2font, rcParams, get_cachedir
 59 from matplotlib.compat import subprocess
 60 from matplotlib.fontconfig_pattern import (

ImportError: DLL load failed: The specified procedure could not be found.

Do you have any ideas how to roll back to stable version or what to downgrade?

conda install anaconda and conda update anaconda do not change any packages.
My current conda version is 4.3.30, matplotlib version is 2.1.0.


问:
How to create a new column from existing column in IBM Data Refinery
I have 3 columns in my dataset and i want to add a new column based
on the value from one column.
For ex. I have Birthdate for a user and i want to create a new column with user's
age.

答: There are several ways to split, combine columns or create new ones from existing columns. Eg: If you have one column called birthdate, you can use the Split operation from the operations panel to create birthyear, birthmonth, birthdate columns. From the year column, you can use the Calculate operation to calculate the age. Hope this helps</p>


问:
Bash script being too resource intensive
I wrote a script in bash that basically takes a wordlist file and checks every line it contains against another list, and outputs the non-matching lines to "uniques.txt". I found though, that this is VERY resource intensive, and takes a lot of time. As i am not a computer scientist or engineer, i don't really know what is going on in the metal.. I heard "C" was a great language because of this issue... Heres a portion of the code:

```<code>if [[ "$1" =~ ^\-i(.*)+$ ]]; then
    echo "[*] Testing lines in \""$2"\" against \""$3"\"..."
    for string in $(cat "$2"); do
        if ! cat "$3" | grep -x "$string" &>/dev/null; then
            echo "$string" >> uniques.txt
        fi
    done
fi
</code>```

A sample use of this script would be: "$script" -i "$wordlist" "$wordlist_to check_against".
The contents of the files would be strings with no spaces in between, one per line, as in:

```<code>johnson
peter
newyork
amsterdam
</code>```

答:
The regex you match $1 against makes no sense. The first parameter should start with -i followed by anything (including an empty string) repeated at least once. It's identical to ^-i, i.e. it starts with -i.

"in \""$2"\" is strange. It prints $2 unquoted, i.e. it can show the name wrong if it contains whitespace (e.g. file a  b will be shown as a b).

in $(cat means the words are read from file one by one, i.e. if there is more than one word per line in $2, they will be matched separately.

You can use grep -f to read the patterns from a file and avoid the loops that cause the slowness:

```<code>#! /bin/bash
if [[ $1 =~ ^-i ]]; then
    echo "[*] Testing lines in \"$2\" against \"$3\"..."
    grep -vxf "$2" "$3"
fi
</code>```

Body:
I wrote a script in bash that basically takes a wordlist file and checks every line it contains against another list, and outputs the non-matching lines to "uniques.txt". I found though, that this is VERY resource intensive, and takes a lot of time. As i am not a computer scientist or engineer, i don't really know what is going on in the metal.. I heard "C" was a great language because of this issue... Heres a portion of the code:

if [[ "$1" =~ ^\-i(.*)+$ ]]; then
    echo "[*] Testing lines in \""$2"\" against \""$3"\"..."
    for string in $(cat "$2"); do
        if ! cat "$3" | grep -x "$string" &>/dev/null; then
            echo "$string" >> uniques.txt
        fi
    done
fi

A sample use of this script would be: "$script" -i "$wordlist" "$wordlist_to check_against".
The contents of the files would be strings with no spaces in between, one per line, as in:

johnson
peter
newyork
amsterdam

Body:
The regex you match $1 against makes no sense. The first parameter should start with -i followed by anything (including an empty string) repeated at least once. It's identical to ^-i, i.e. it starts with -i.

"in \""$2"\" is strange. It prints $2 unquoted, i.e. it can show the name wrong if it contains whitespace (e.g. file a  b will be shown as a b).

in $(cat means the words are read from file one by one, i.e. if there is more than one word per line in $2, they will be matched separately.

You can use grep -f to read the patterns from a file and avoid the loops that cause the slowness:

#! /bin/bash
if [[ $1 =~ ^-i ]]; then
    echo "[*] Testing lines in \"$2\" against \"$3\"..."
    grep -vxf "$2" "$3"
fi


问:
Class with template member variable and functions
I'm trying to create something like this:

```<code>// The code doesn't work, it should just be a pseudo to help understand what i'm trying to create
template <typename Variable>
class Address
{
    unsigned int A_Address;
    Variable A_Type;

    void Set(A_Type value)
    {
        *((A_Type*)A_Address) = value;
    }

    A_Type Get()
    {
        return *((A_Type*)A_Address);
    }
};

Address address_1 = new Address<float/*type*/>(0x00000000/*address in memory*/);
address_1.Set(30.0f);
float value_1 = address_1.Get();

Address address_2 = new Address<int/*type*/>(0x00000000/*address in memory*/);
address_2.Set(10);
int value_2 = address_2.Get();
</code>```

So i want to be able to define objects like Address obj_1, obj_2; and then Initialize them later with a type and an address. Then the Get() method should return it's current value in memory and the Set() method should set that value in memory. I couldn't figure out how to not do Address<float> obj_1; and instead using Address obj_1; and initializing it later. Hope you understood what i'm trying to do and could let me know if it's possible and if so maybe help me out or point me in the right direction.
Thanks in advance!

答:
I'm not really dealing with your address mangling but what you want can be done that way :

```<code>struct Address
{
Address(unsigned int addr)
: A_Address(addr)
{}

unsigned int A_Address;

template <typename T>
void Set(T value)
{
    *((T*)A_Address) = value;
}

template <typename T>
T Get()
{
    return *((T*)A_Address);
}
};
</code>```

And you can use it that way

```<code>Address address(0x00000000);  //won't work because of virtual addressing
address.Set<float>(10.0F);
std::cout << address.Get<float>();

address.Set<double>(99.0);
std::cout << address.Get<double>();
</code>```

Be careful when you handle addresses that way, very error-prone. Have a look over there:

Pass a hex address to a Pointer Variable

Body:
I'm trying to create something like this:

// The code doesn't work, it should just be a pseudo to help understand what i'm trying to create
template <typename Variable>
class Address
{
    unsigned int A_Address;
    Variable A_Type;

    void Set(A_Type value)
    {
        *((A_Type*)A_Address) = value;
    }

    A_Type Get()
    {
        return *((A_Type*)A_Address);
    }
};

Address address_1 = new Address<float/*type*/>(0x00000000/*address in memory*/);
address_1.Set(30.0f);
float value_1 = address_1.Get();

Address address_2 = new Address<int/*type*/>(0x00000000/*address in memory*/);
address_2.Set(10);
int value_2 = address_2.Get();

So i want to be able to define objects like Address obj_1, obj_2; and then Initialize them later with a type and an address. Then the Get() method should return it's current value in memory and the Set() method should set that value in memory. I couldn't figure out how to not do Address<float> obj_1; and instead using Address obj_1; and initializing it later. Hope you understood what i'm trying to do and could let me know if it's possible and if so maybe help me out or point me in the right direction.
Thanks in advance!

Body:
I'm not really dealing with your address mangling but what you want can be done that way :

struct Address
{
Address(unsigned int addr)
: A_Address(addr)
{}

unsigned int A_Address;

template <typename T>
void Set(T value)
{
    *((T*)A_Address) = value;
}

template <typename T>
T Get()
{
    return *((T*)A_Address);
}
};

And you can use it that way

Address address(0x00000000);  //won't work because of virtual addressing
address.Set<float>(10.0F);
std::cout << address.Get<float>();

address.Set<double>(99.0);
std::cout << address.Get<double>();

Be careful when you handle addresses that way, very error-prone. Have a look over there:

Pass a hex address to a Pointer Variable


问:
how can I quickly convert in python an xlsx file into a csv file?
I have a 140MB Excel file I need to analyze using pandas. The problem is that if I open this file as xlsx it takes python 5 minutes simply to read it. I tried to manually save this file as csv and then it takes Python about a second to open and read it! There are different 2012-2014 solutions that why Python 3 don't really work on my end.

Can somebody suggest how to convert very quickly file 'C:\master_file.xlsx' to 'C:\master_file.csv'?

答:
There is a project aiming to be very pythonic on dealing with data called "rows". It relies on "openpyxl" for xlsx, though. I don't know if this will be faster than Pandas, but anyway:

```<code>$ pip install rows openpyxl
</code>```

And:

```<code>import rows
data = rows.import_from_xlsx("my_file.xlsx")
rows.export_to_csv(data, open("my_file.csv", "wb"))
</code>```

Body:
There is a project aiming to be very pythonic on dealing with data called "rows". It relies on "openpyxl" for xlsx, though. I don't know if this will be faster than Pandas, but anyway:

$ pip install rows openpyxl

And:

import rows
data = rows.import_from_xlsx("my_file.xlsx")
rows.export_to_csv(data, open("my_file.csv", "wb"))


问:
delete doesn't free memory at the end of a function
I'm nearing my wits end with this. I have searched for hours for a solution to this, but I haven't found something that solves my problem.

So I want to code a neuronal network and I have written extensive code for it and which I have checked and debugged so far. I tried evolving my network over multiple generations but although it does execute it gives me a double free or corruption error. I have traced the error with valgrind to this function

```<code>bool mutate_a_neuron(Neuron* neuron, int numberofneurons, int numberofinputs){

    int num_e = 3*NUM_I+3;
    bool* element_already_mutated = new bool[num_e];  //line 91
    //bool element_already_mutated[15]; //Workaround :(
    for(int i =0; i<num_e; i++){
        element_already_mutated[i]=false;
    }

    int number_of_elements = (int) neuron->numberofelementstomutate;
    unsigned short will_it_be_mutated = rand() % USHRT_MAX ;

    if(  neuron->mutationrate > will_it_be_mutated ){

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

            int elementtomutate = rand() % num_e;   //choose random element
            if(element_already_mutated[elementtomutate]){//check if mutated
                i--;
                continue;
            }

            if( mutate_element(neuron, elementtomutate, numberofneurons, numberofinputs) ){//mutate stuff
                element_already_mutated[elementtomutate]=true;
            } else {
                printf("Something went wrong while mutating an element or takes_input was false\n"); //die if error
            }
        }

        return true;
    }

    delete [] element_already_mutated; //line 120

    return false;
}
</code>```

Valgrind gives me a mismatched free()/delete/delete[] error at where element_already_mutated gets initialized and free'd. The funky thing is, if I comment the dynamic allocation out and just initialize my "workaround" which is just a normal static array, I get no memory leaks and everything gets deallocated correctly. NUM_I is defined as 4 in the header as:

```<code>#define NUM_I 4
</code>```

Valgrind error:

```<code>==1887== 15,023,190 bytes in 1,001,546 blocks are definitely lost in loss record 1 of 1
==1887==    at 0x4C2C93F: operator new[](unsigned long) (vg_replace_malloc.c:423)
==1887==    by 0x10A461: mutate_a_neuron(Neuron*, int, int) (n.cpp:91)
==1887==    (here follow more functions, which call mutate_a_neuron)
</code>```

Can someone tell me what I'm doing wrong? I don't think I'm deallocating incorrectly but I have no idea where the error might be otherwise.

答:
You sometimes delete it, and sometimes don't. This is the primary reason this whole method of coding is strongly discouraged. Here is your code with some extra stuff removed so you can see it more clearly:

```<code>bool mutate_a_neuron(...){
    bool* element_already_mutated = new bool[num_e];

    if( condition ){
        // not deleted
        return true;
    }

    delete [] element_already_mutated;
    return false;
}
</code>```

edit: actually UnholySheep already mentioned this in the comments. I missed that.

Body:
I'm nearing my wits end with this. I have searched for hours for a solution to this, but I haven't found something that solves my problem.

So I want to code a neuronal network and I have written extensive code for it and which I have checked and debugged so far. I tried evolving my network over multiple generations but although it does execute it gives me a double free or corruption error. I have traced the error with valgrind to this function

bool mutate_a_neuron(Neuron* neuron, int numberofneurons, int numberofinputs){

    int num_e = 3*NUM_I+3;
    bool* element_already_mutated = new bool[num_e];  //line 91
    //bool element_already_mutated[15]; //Workaround :(
    for(int i =0; i<num_e; i++){
        element_already_mutated[i]=false;
    }

    int number_of_elements = (int) neuron->numberofelementstomutate;
    unsigned short will_it_be_mutated = rand() % USHRT_MAX ;

    if(  neuron->mutationrate > will_it_be_mutated ){

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

            int elementtomutate = rand() % num_e;   //choose random element
            if(element_already_mutated[elementtomutate]){//check if mutated
                i--;
                continue;
            }

            if( mutate_element(neuron, elementtomutate, numberofneurons, numberofinputs) ){//mutate stuff
                element_already_mutated[elementtomutate]=true;
            } else {
                printf("Something went wrong while mutating an element or takes_input was false\n"); //die if error
            }
        }

        return true;
    }

    delete [] element_already_mutated; //line 120

    return false;
}

Valgrind gives me a mismatched free()/delete/delete[] error at where element_already_mutated gets initialized and free'd. The funky thing is, if I comment the dynamic allocation out and just initialize my "workaround" which is just a normal static array, I get no memory leaks and everything gets deallocated correctly. NUM_I is defined as 4 in the header as:

#define NUM_I 4

Valgrind error:

==1887== 15,023,190 bytes in 1,001,546 blocks are definitely lost in loss record 1 of 1
==1887==    at 0x4C2C93F: operator new[](unsigned long) (vg_replace_malloc.c:423)
==1887==    by 0x10A461: mutate_a_neuron(Neuron*, int, int) (n.cpp:91)
==1887==    (here follow more functions, which call mutate_a_neuron)

Can someone tell me what I'm doing wrong? I don't think I'm deallocating incorrectly but I have no idea where the error might be otherwise.

Body:
You sometimes delete it, and sometimes don't. This is the primary reason this whole method of coding is strongly discouraged. Here is your code with some extra stuff removed so you can see it more clearly:

bool mutate_a_neuron(...){
    bool* element_already_mutated = new bool[num_e];

    if( condition ){
        // not deleted
        return true;
    }

    delete [] element_already_mutated;
    return false;
}

edit: actually UnholySheep already mentioned this in the comments. I missed that.


问:
Django - ValueError: too many values to unpack (expected 2)
I try to use make a droplist from model.

```<code>USER_TYPE = {
'admin': "Admin",
'patient': "Patient",
'helper': "Helper",
'therapist': "Therapist",
}

class User(AbstractBaseUser):
    user_type = models.CharField(max_length=10, choices=USER_TYPE, default="patient")
</code>```

However, I get this error:

ValueError: too many values to unpack (expected 2)

Thanks in advance!

答:
You are using a CharField, but if you want a dropdown, you should be using a ChoiceField

You are supplying USER_TYPE as a dictionary but

choices

Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. See the model field reference documentation on choices for more details. If the argument is a callable, it is evaluated each time the field’s form is initialized. Defaults to an empty list.
  https://docs.djangoproject.com/en/1.11/ref/forms/fields/#django.forms.ChoiceField.choices

So try something like:

```<code>USER_TYPE = [
('admin', "Admin"),
('patient', "Patient"),
(..., ...),
]
</code>```

Body:
I try to use make a droplist from model.

USER_TYPE = {
'admin': "Admin",
'patient': "Patient",
'helper': "Helper",
'therapist': "Therapist",
}

class User(AbstractBaseUser):
    user_type = models.CharField(max_length=10, choices=USER_TYPE, default="patient")

However, I get this error:

ValueError: too many values to unpack (expected 2)

Thanks in advance!

Body:
You are using a CharField, but if you want a dropdown, you should be using a ChoiceField

You are supplying USER_TYPE as a dictionary but

choices

Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable. This argument accepts the same formats as the choices argument to a model field. See the model field reference documentation on choices for more details. If the argument is a callable, it is evaluated each time the field’s form is initialized. Defaults to an empty list.
  https://docs.djangoproject.com/en/1.11/ref/forms/fields/#django.forms.ChoiceField.choices

So try something like:

USER_TYPE = [
('admin', "Admin"),
('patient', "Patient"),
(..., ...),
]


问:
Query for selecting records from a table but the using a list thats on another table
I Need run a query that selects all the Data for selected vendors (Key words) but selection list (Key words) is on another Table.

Currently I am using: - I use only the key words in place of "Vendor"
Like "Vendor A" Or Like "Vendor B" Or Like "Vendor C" Or Like "Vendor D" Or Like "Vendor E"

Currently I have to add new vendors to this Query to get the report but this query is growing big and I need give this to a staff who does not know anything about Access and I was wondering if I could create a table for these key words where just updating the table list (key words) will allow access to look for these key words in another table and pull the records.
Hope this explains what I need.

答:
Yes, you can.  Put put each criteria on a separate row of a new table.  Put both tables in the same query, with no joins.  Pull all of the fields from the source table, with a constraint that looks something like "instr(keyfield,criteria)>0", or "keyfield=criteria" if you expect an exact match.  You may get duplicates if the key matches more than one criteria - if so, you can use group by to get rid of them.

And you should still look at the reference that Rene suggested above.