问:
Adding basic HTTP auth to a WCF REST service
I have a WCF HTTP REST Service and I tie into it with an HTTP client in a different programming language who writes its own custom HTTP.
I would like to add WWW-Authenticate basic authentication support to my WCF service.

My methods look like this:

```<code>[WebInvoke(UriTemplate = "widgets", Method = "POST")]
public XElement CreateWidget(XElement e)
{
...
}
</code>```

Is it possible for me to somehow filter incoming HTTP requests so I can check for a valid Basic auth string before it hits each of the REST methods like CreateWidget above?
Note: My auth info is stord in my database.

Basically I want to check for this in the request headers:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== and then I can myself parse that string and validate the u/p in the database.

The web.config file is as follows:

```<code><?xml version="1.0"?>
<configuration>

  <connectionStrings>
    <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="10485760" />
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxReceivedMessageSize="1048576" maxBufferSize="1048576" />
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>

</configuration>
</code>```

答:
I was also interested in custom authentication in a REST HTTP WCF service and finally got it to work.

That being said my code will give you a way to get it working, but I recommend reading this guide which explains everything in more depth: http://wcfsecurityguide.codeplex.com/

First, change the system.web portion of your Web.Config to look like this:

```<code><system.web>
  <compilation debug="true" targetFramework="4.0" />
  <httpRuntime maxRequestLength="10485760" />
  <authentication mode="None"></authentication>
  <httpModules>
    <add name="BasicAuthenticationModule" type="YourNamespace.UserNameAuthenticator" />
  </httpModules>
</system.web>
</code>```

Then add another file to your project: UserNameAuthenticator.cs

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.ServiceModel.Activation;

namespace YourNamespace
{
    public class UserNameAuthenticator : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication application)
        {
            application.AuthenticateRequest += new EventHandler(this.OnAuthenticateRequest);
            application.AuthorizeRequest += new EventHandler(this.OnAuthorizationRequest);
            application.EndRequest += new EventHandler(this.OnEndRequest);
        }

        public bool CustomAuth(string username, string password)
        {
            //TODO: Implement your custom auth logic here
            return true;
        }

        public string[] GetCustomRoles(string username)
        {
            return new string[] { "read", "write" };
        }

        public void OnAuthorizationRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;
            //If you want to handle authorization differently from authentication
        }

        public void OnAuthenticateRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;
            //the Authorization header is checked if present
            string authHeader = app.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authHeader))
            {
                string authStr = app.Request.Headers["Authorization"];
                if (authStr == null || authStr.Length == 0)
                {
                    // No credentials; anonymous request
                    return;
                }
                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    //header not correct we do not authenticate
                    return;
                }

                authStr = authStr.Trim();
                string encodedCredentials = authStr.Substring(6);
                byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
                string s = new ASCIIEncoding().GetString(decodedBytes);
                string[] userPass = s.Split(new char[] { ':' });
                string username = userPass[0];
                string password = userPass[1];
                //the user is validated against the SqlMemberShipProvider
                //If it is validated then the roles are retrieved from the
                //role provider and a generic principal is created
                //the generic principal is assigned to the user context
                // of the application
                if (CustomAuth(username, password))
                {
                    string[] roles = GetCustomRoles(username);
                    app.Context.User = new GenericPrincipal(new
                    GenericIdentity(username, "Membership Provider"), roles);
                }
                else
                {
                    DenyAccess(app);
                    return;
                }
            }
            else
            {
                //the authorization header is not present
                //the status of response is set to 401 and it ended
                //the end request will check if it is 401 and add
                //the authentication header so the client knows
                //it needs to send credentials to authenticate
                app.Response.StatusCode = 401;
                app.Response.End();
            }
        }

        public void OnEndRequest(object source, EventArgs eventArgs)
        {
            if (HttpContext.Current.Response.StatusCode == 401)
            {
                //if the status is 401 the WWW-Authenticated is added to
                //the response so client knows it needs to send credentials
                HttpContext context = HttpContext.Current;
                context.Response.StatusCode = 401;
                context.Response.AddHeader("WWW-Authenticate", "Basic Realm");
            }
        }
        private void DenyAccess(HttpApplication app)
        {
            app.Response.StatusCode = 401;
            app.Response.StatusDescription = "Access Denied";
            // error not authenticated
            app.Response.Write("401 Access Denied");
            app.CompleteRequest();
        }
    } // End Class
} //End Namespace
</code>```

Body:
I have a WCF HTTP REST Service and I tie into it with an HTTP client in a different programming language who writes its own custom HTTP.
I would like to add WWW-Authenticate basic authentication support to my WCF service.

My methods look like this:

[WebInvoke(UriTemplate = "widgets", Method = "POST")]
public XElement CreateWidget(XElement e)
{
...
}

Is it possible for me to somehow filter incoming HTTP requests so I can check for a valid Basic auth string before it hits each of the REST methods like CreateWidget above?
Note: My auth info is stord in my database.

Basically I want to check for this in the request headers:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== and then I can myself parse that string and validate the u/p in the database.

The web.config file is as follows:

<?xml version="1.0"?>
<configuration>

  <connectionStrings>
    <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime maxRequestLength="10485760" />
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </modules>
  </system.webServer>

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxReceivedMessageSize="1048576" maxBufferSize="1048576" />
      </webHttpEndpoint>
    </standardEndpoints>
  </system.serviceModel>

</configuration>

Body:
I was also interested in custom authentication in a REST HTTP WCF service and finally got it to work.

That being said my code will give you a way to get it working, but I recommend reading this guide which explains everything in more depth: http://wcfsecurityguide.codeplex.com/

First, change the system.web portion of your Web.Config to look like this:

<system.web>
  <compilation debug="true" targetFramework="4.0" />
  <httpRuntime maxRequestLength="10485760" />
  <authentication mode="None"></authentication>
  <httpModules>
    <add name="BasicAuthenticationModule" type="YourNamespace.UserNameAuthenticator" />
  </httpModules>
</system.web>

Then add another file to your project: UserNameAuthenticator.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using System.ServiceModel.Activation;

namespace YourNamespace
{
    public class UserNameAuthenticator : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication application)
        {
            application.AuthenticateRequest += new EventHandler(this.OnAuthenticateRequest);
            application.AuthorizeRequest += new EventHandler(this.OnAuthorizationRequest);
            application.EndRequest += new EventHandler(this.OnEndRequest);
        }

        public bool CustomAuth(string username, string password)
        {
            //TODO: Implement your custom auth logic here
            return true;
        }

        public string[] GetCustomRoles(string username)
        {
            return new string[] { "read", "write" };
        }

        public void OnAuthorizationRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;
            //If you want to handle authorization differently from authentication
        }

        public void OnAuthenticateRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;
            //the Authorization header is checked if present
            string authHeader = app.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(authHeader))
            {
                string authStr = app.Request.Headers["Authorization"];
                if (authStr == null || authStr.Length == 0)
                {
                    // No credentials; anonymous request
                    return;
                }
                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    //header not correct we do not authenticate
                    return;
                }

                authStr = authStr.Trim();
                string encodedCredentials = authStr.Substring(6);
                byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
                string s = new ASCIIEncoding().GetString(decodedBytes);
                string[] userPass = s.Split(new char[] { ':' });
                string username = userPass[0];
                string password = userPass[1];
                //the user is validated against the SqlMemberShipProvider
                //If it is validated then the roles are retrieved from the
                //role provider and a generic principal is created
                //the generic principal is assigned to the user context
                // of the application
                if (CustomAuth(username, password))
                {
                    string[] roles = GetCustomRoles(username);
                    app.Context.User = new GenericPrincipal(new
                    GenericIdentity(username, "Membership Provider"), roles);
                }
                else
                {
                    DenyAccess(app);
                    return;
                }
            }
            else
            {
                //the authorization header is not present
                //the status of response is set to 401 and it ended
                //the end request will check if it is 401 and add
                //the authentication header so the client knows
                //it needs to send credentials to authenticate
                app.Response.StatusCode = 401;
                app.Response.End();
            }
        }

        public void OnEndRequest(object source, EventArgs eventArgs)
        {
            if (HttpContext.Current.Response.StatusCode == 401)
            {
                //if the status is 401 the WWW-Authenticated is added to
                //the response so client knows it needs to send credentials
                HttpContext context = HttpContext.Current;
                context.Response.StatusCode = 401;
                context.Response.AddHeader("WWW-Authenticate", "Basic Realm");
            }
        }
        private void DenyAccess(HttpApplication app)
        {
            app.Response.StatusCode = 401;
            app.Response.StatusDescription = "Access Denied";
            // error not authenticated
            app.Response.Write("401 Access Denied");
            app.CompleteRequest();
        }
    } // End Class
} //End Namespace


来源: stackexchange

问:
theme font doesn't apply to paragraph
Okay, so I am just a beginner in HTML and CSS. I tried to apply wordpress themes font to everything else on the site. The font is "Roboto Condensed", sans-serif; . I even created a custom menu which works perfectly with this font, but when I try to apply it to paragraphs, like product descriptions, it just doesn't work. I tried to edit the style.css file with

* {
font-family: "Roboto Condensed", sans-serif;
}

or

```<code>body {font-family: "Roboto Condensed", sans-serif;}
</code>```

Can some one please tell me maybe I am doing something wrong?

答: There is alright with syntax,The font that you choose maybe does not  exist, so you must try another font-family or visit google fonts and pick your font-family</p>

ContentLicense: CC BY-SA 3.0

Title: theme font doesn't apply to paragraph

Body:
Okay, so I am just a beginner in HTML and CSS. I tried to apply wordpress themes font to everything else on the site. The font is "Roboto Condensed", sans-serif; . I even created a custom menu which works perfectly with this font, but when I try to apply it to paragraphs, like product descriptions, it just doesn't work. I tried to edit the style.css file with

* {
font-family: "Roboto Condensed", sans-serif;
}

or

body {font-family: "Roboto Condensed", sans-serif;}

Can some one please tell me maybe I am doing something wrong?


问:
How to use SQL Joins and Selects to get results from a third table that matches the first two?
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

```<code>Select * from 3rdTable where City='' AND State='';
</code>```

Result from Join is like

```<code> - City | State
 - A    | B
 - C    | D
 - E    | F
</code>```

Example Result if only 1 row of the 3rd table matches

```<code> - C    |  D
</code>```

How can this be done?

答:
```<code>SELECT *
FROM   table3 t3
       INNER JOIN (SELECT city,
                          state
                   FROM   table1 T1
                          JOIN table2 t2
                            ON t1.id = t2.id) a1
               ON t3.city = a1.city
                  AND t3.state = a1.state
</code>```

Body:
I have a Join statement on two tables(Table 1 and 2), which returns the City and State. I have another table(Table 3) which contains columns like Name, City, State, Country. I want to fetch all the rows from Table 3 whose City and State Columns matches with the rows of the Join result.

Select * from 3rdTable where City='' AND State='';

Result from Join is like

 - City | State
 - A    | B
 - C    | D
 - E    | F

Example Result if only 1 row of the 3rd table matches

 - C    |  D

How can this be done?


问:
How do I search for an object in LDAP based on its dn, in python-ldap?
I am trying to use e.g. the search_s function to search for an object based on its full distinguished name, but am not finding this to be convenient. For example,

```<code>search_s('DC=example, DC=com', ldap.SCOPE_SUBTREE,
    '(CN=Somebody, OU=Department, DC=example, DC=com)')
</code>```

How do I just retrieve one object based on its full LDAP distinguished name?

答:
Use SCOPE_BASE and a wildcard filter to return only the dn given by the first argument (the filter still has to match that object!) For example,

```<code>import ldap
...
ldap_connection.search_s('CN=Somebody, OU=Department, DC=example, DC=com',
    ldap.SCOPE_BASE,
    '(objectClass=*)')
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use e.g. the search_s function to search for an object based on its full distinguished name, but am not finding this to be convenient. For example,

search_s('DC=example, DC=com', ldap.SCOPE_SUBTREE,
    '(CN=Somebody, OU=Department, DC=example, DC=com)')

How do I just retrieve one object based on its full LDAP distinguished name?

Body:
Use SCOPE_BASE and a wildcard filter to return only the dn given by the first argument (the filter still has to match that object!) For example,

import ldap
...
ldap_connection.search_s('CN=Somebody, OU=Department, DC=example, DC=com',
    ldap.SCOPE_BASE,
    '(objectClass=*)')


问:
C how to show all unused functions (including ones defined in h files)
Somewhat related to this, but it still doesn't quite answer my question

I have a C project, and i would like to enumerate all unreferenced functions (including non-static, so setting compiler option for werror=unused-function only partially works...) in order to identify and clean up the codebase.

One way I thought is to enumerate all the functions in the project, and then make a script to go through each and see if it is called via cscope... but I'm not sure how to get a list-form of all the functions in the first place. That link above has a solution that is failing for me.

Any other ideas are welcome.

答:
There are g++ compiler options to remove unused code or not, and you can use the difference in symbol tables to point to unused non-virtual methods.
Virtual methods are "used" by virtue of being linked into the vtable even if they are never called, so the only way to find those is via coverage tools or perhaps lint. Dynamically linked library methods are a different issue, as you should only have a limited number of published entrypoints that you need to check through. And anyway you have to decide if some other client would want those entrypoints.</p>


问:
Can I generate SQL scripts with ServiceStack OrmLite?
Is it possible to generate SQL scripts using OrmLite without executing it against a database?  I would like to load a list of DTOs from a live SqlServer database and output a script to DELETE and INSERT each record.

The provided mini profiler supports logging, but looks like it needs to wrap a real database connection.

答:
I use this to capture the statement and keep running the sentense.

```<code>    public class CustomOrmLiteExecFilter : OrmLiteExecFilter
{
    public override T Exec<T>(IDbConnection dbConn, Func<IDbCommand, T> filter)
    {
        var holdProvider = OrmLiteConfig.DialectProvider;
        var dbCmd = CreateCommand(dbConn);
        try
        {
            var ret = filter(dbCmd);

            var pureSQL = holdProvider.MergeParamsIntoSql(dbCmd.CommandText, dbCmd.Parameters.OfType<IDbDataParameter>());
            //log or save the SQL Statement

            return ret;
        }
        finally
        {
            if (OrmLiteConfig.DialectProvider != holdProvider)
                OrmLiteConfig.DialectProvider = holdProvider;
        }
    }
}
</code>```

and the usage:

```<code> OrmLiteConfig.ExecFilter = new CustomOrmLiteExecFilter();
</code>```

hope this can help you!

Body:
I use this to capture the statement and keep running the sentense.

    public class CustomOrmLiteExecFilter : OrmLiteExecFilter
{
    public override T Exec<T>(IDbConnection dbConn, Func<IDbCommand, T> filter)
    {
        var holdProvider = OrmLiteConfig.DialectProvider;
        var dbCmd = CreateCommand(dbConn);
        try
        {
            var ret = filter(dbCmd);

            var pureSQL = holdProvider.MergeParamsIntoSql(dbCmd.CommandText, dbCmd.Parameters.OfType<IDbDataParameter>());
            //log or save the SQL Statement

            return ret;
        }
        finally
        {
            if (OrmLiteConfig.DialectProvider != holdProvider)
                OrmLiteConfig.DialectProvider = holdProvider;
        }
    }
}

and the usage:

 OrmLiteConfig.ExecFilter = new CustomOrmLiteExecFilter();

hope this can help you!


问:
If jQuery form is valid show hidden div
I've been messing with some form validation with two identical forms. So far I have the default HTML validation on the form, but for some reason when I submit the form, it reload the form it doesn't show my message that it's been successful.

Here's what I have for the form:

HTML

```<code><div class="place-form">
   <div class="success-msg" style="display:none;">
    <p>Thanks for your submission! We will contact you shortly.</p>
  </div>
  <div class="form-wrap">
    <form id="place-form-item">
    <div class="form-row">
      <input id="fname" type="text" name="fname" placeholder="Your First Name" required />
    </div>
    <div class="form-row">
      <input id="lname" type="text" name="lname" placeholder="Your Last Name" required />
    </div>
    <div class="form-row">
      <input id="form-email" type="email" name="email" placeholder="Your Email" required />
    </div>
    <div class="btn-row">
      <button class="submit-btn">submit</button>
    </div>
      </form>
  </div>
</div>
</code>```

JS:

```<code>$(".submit-btn").click(function(e){
   var $this = $(this);
   if($this.find("#place-form-item").valid()) {
       $this.parents(".form-wrap").hide();
       $this.parents().next(".success-msg").show()
     e.preventDefault();
   }
});
</code>```

Not sure how to get it so that upon click, the form passed validation and then hides the one form and shows the success message. Unless I'm targeting something incorrectly.

答:
Well, first you know that the .valid() method is a JQuery plug-in, right? Without the plug-in, the code in the if statement will never be reached.

There is a pure JavaScript API for checking a form's validity against the HTML5 validity framework - .checkValidity().

Next, your .next() call isn't going to find the success message because it isn't the next element from your button.  Both that and your .find() calls can be replaced by using a higher level selector as context for a search.

Next, don't work with the submit button's click event. Work with the form's submit event.

Lastly, it's better to work with CSS classes than to dynamically create inline styles on an element.

$("#place-form-item").on("submit", function(e){
   var $this = $(this);
   if(this.checkValidity()) {
      e.preventDefault();
      $this.parents(".form-wrap").hide();
      $(".success-msg", ".place-form").removeClass("hidden")
   }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden { display:none; }</code>```

    Thanks for your submission! We will contact you shortly.

    <form id="place-form-item">

        <input id="fname" type="text" name="fname" placeholder="Your First Name" required>

        <input id="lname" type="text" name="lname" placeholder="Your Last Name" required>

        <input id="form-email" type="email" name="email" placeholder="Your Email" required>

        <button class="submit-btn">submit</button>

    </form>

```

Title: If jQuery form is valid show hidden div

Body:
I've been messing with some form validation with two identical forms. So far I have the default HTML validation on the form, but for some reason when I submit the form, it reload the form it doesn't show my message that it's been successful.

Here's what I have for the form:

HTML

Thanks for your submission! We will contact you shortly.

    <form id="place-form-item">

      <input id="fname" type="text" name="fname" placeholder="Your First Name" required />

      <input id="lname" type="text" name="lname" placeholder="Your Last Name" required />

      <input id="form-email" type="email" name="email" placeholder="Your Email" required />

      <button class="submit-btn">submit</button>

      </form>

JS:

$(".submit-btn").click(function(e){
   var $this = $(this);
   if($this.find("#place-form-item").valid()) {
       $this.parents(".form-wrap").hide();
       $this.parents().next(".success-msg").show()
     e.preventDefault();
   }
});

Not sure how to get it so that upon click, the form passed validation and then hides the one form and shows the success message. Unless I'm targeting something incorrectly.

Body:
Well, first you know that the .valid() method is a JQuery plug-in, right? Without the plug-in, the code in the if statement will never be reached.

There is a pure JavaScript API for checking a form's validity against the HTML5 validity framework - .checkValidity().

Next, your .next() call isn't going to find the success message because it isn't the next element from your button.  Both that and your .find() calls can be replaced by using a higher level selector as context for a search.

Next, don't work with the submit button's click event. Work with the form's submit event.

Lastly, it's better to work with CSS classes than to dynamically create inline styles on an element.

$("#place-form-item").on("submit", function(e){
   var $this = $(this);
   if(this.checkValidity()) {
      e.preventDefault();
      $this.parents(".form-wrap").hide();
      $(".success-msg", ".place-form").removeClass("hidden")
   }
});

.hidden { display:none; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="place-form">

  <div class="success-msg hidden">
    Thanks for your submission! We will contact you shortly.
  </div>

  <div class="form-wrap">

    <form id="place-form-item">
      <div class="form-row">
        <input id="fname" type="text" name="fname" placeholder="Your First Name" required>
      </div>
      <div class="form-row">
        <input id="lname" type="text" name="lname" placeholder="Your Last Name" required>
      </div>
      <div class="form-row">
        <input id="form-email" type="email" name="email" placeholder="Your Email" required>
      </div>
      <div class="btn-row">
        <button class="submit-btn">submit</button>
      </div>
    </form>

  </div>
</div>


问:
SwiftCharts cutting off points (clips bounds)
I am tweaking the Areas Example project from SwiftCharts and I am running into the issue where the point indicators are getting cut off like so:

In the github issues a found this and this other issue where the solutions were to set chartSettings.clipInnerFrame = false

However, when I do this the the area color awkward shape also becomes visible like so:

How can I get the whole shape of the points but all the other stuff?

答:
You have to pass to the ChartPointsViewsLayer with the points clipViews: false (see example). ChartSettings.clipInnerFrame has to be true (i.e. the default). This way only the layer with the points is clipped.

Finally, if you want to clip the unclipped points layer (to limit the area outside of the chart where they are displayed), you can do it passing a custom rectangle, like here (this setting is admittedly not very intuitive).


问:
Setting memory address of nodes in C++
I seem to be having trouble understanding how to build a function that adds nodes into a linked list.

Thus far, i have this.

```<code>void StringList::add(string value){
StringNode *temp = new StringNode;
temp->data = value;
temp->next = NULL;

if(head==NULL){
    head = temp;
    temp = NULL;
}
</code>```

I do not understand how I can set the memory address for the previous node each time i add to the list. Ideally, I would have given myself a tail node, however i was provided a driver and a header file which are to remain unchanged. Any insight would be appreciated.

答:
If you want to add your new node to the end of the list without having maintained a tail, you'll have to go through the whole list each time:

```<code>void StringList::add(string value){
  StringNode *temp = new StringNode;
  temp->data = value;
  temp->next = NULL;

  if(head==NULL){
     head = temp;
  }
  else {
     StringNode* last = head;
     while (last->next) {
       last=last->next;
     }
     last->next = temp;
  }
}
</code>```

Title: Setting memory address of nodes in C++

Body:
I seem to be having trouble understanding how to build a function that adds nodes into a linked list.

Thus far, i have this.

void StringList::add(string value){
StringNode *temp = new StringNode;
temp->data = value;
temp->next = NULL;

if(head==NULL){
    head = temp;
    temp = NULL;
}

I do not understand how I can set the memory address for the previous node each time i add to the list. Ideally, I would have given myself a tail node, however i was provided a driver and a header file which are to remain unchanged. Any insight would be appreciated.

Body:
If you want to add your new node to the end of the list without having maintained a tail, you'll have to go through the whole list each time:

void StringList::add(string value){
  StringNode *temp = new StringNode;
  temp->data = value;
  temp->next = NULL;

  if(head==NULL){
     head = temp;
  }
  else {
     StringNode* last = head;
     while (last->next) {
       last=last->next;
     }
     last->next = temp;
  }
}


问:
numpy how to change an array into a zero one except the max value
I want to make a function that when fed an array, it returns an array of the same shape but with all zeros expect for 1 value that is the max one. eg. with an array like this:

```<code>my_array = np.arange(9).reshape((3,3))

[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]]
</code>```

when passed in the function I want it out like this:

```<code>[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  8.]]
</code>```

exeption:

When there is many max value that are equal, I only want one out of them and the rest gets zero'ed out (the order doesn't matter).

I am honeslty clueless as to how to make this in an elegant way that is furthermore efficient, how would you do it?

答:
For efficiency, use array-initialization and argmax to get the max index (first one linearly indexed if more than one) -

```<code>def app_flat(my_array):
    out = np.zeros_like(my_array)
    idx  = my_array.argmax()
    out.flat[idx] = my_array.flat[idx]
    return out
</code>```

We can also use ndarray.ravel() in place of ndaarray.flat and I would think that the performance numbers would be comparable.

For this sparsey output, to gain memory efficiency and hence performance, you might want to use sparse matrices, especially for large arrays. Thus, for sparse matrix output, we would have an alternative one, like so -

```<code>from scipy.sparse import coo_matrix

def app_sparse(my_array):
    idx  = my_array.argmax()
    r,c = np.unravel_index(idx, my_array.shape)
    return coo_matrix(([my_array[r,c]],([r],[c])),shape=my_array.shape)
</code>```

Sample run -

```<code>In [336]: my_array
Out[336]:
array([[0, 1, 2],
       [3, 4, 5],
       [8, 7, 8]])

In [337]: app_flat(my_array)
Out[337]:
array([[0, 0, 0],
       [0, 0, 0],
       [8, 0, 0]])

In [338]: app_sparse(my_array)
Out[338]:
<3x3 sparse matrix of type '<type 'numpy.int64'>'
    with 1 stored elements in COOrdinate format>

In [339]: app_sparse(my_array).toarray() # just to confirm values
Out[339]:
array([[0, 0, 0],
       [0, 0, 0],
       [8, 0, 0]])
</code>```

Runtime test on bigger array -

```<code>In [340]: my_array =  np.random.randint(0,1000,(5000,5000))

In [341]: %timeit app_flat(my_array)
10 loops, best of 3: 34.9 ms per loop

In [342]: %timeit app_sparse(my_array) # sparse matrix output
100 loops, best of 3: 17.2 ms per loop
</code>```

Body:
I want to make a function that when fed an array, it returns an array of the same shape but with all zeros expect for 1 value that is the max one. eg. with an array like this:

my_array = np.arange(9).reshape((3,3))

[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]]

when passed in the function I want it out like this:

[[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  8.]]

exeption:

When there is many max value that are equal, I only want one out of them and the rest gets zero'ed out (the order doesn't matter).

I am honeslty clueless as to how to make this in an elegant way that is furthermore efficient, how would you do it?

Body:
For efficiency, use array-initialization and argmax to get the max index (first one linearly indexed if more than one) -

def app_flat(my_array):
    out = np.zeros_like(my_array)
    idx  = my_array.argmax()
    out.flat[idx] = my_array.flat[idx]
    return out

We can also use ndarray.ravel() in place of ndaarray.flat and I would think that the performance numbers would be comparable.

For this sparsey output, to gain memory efficiency and hence performance, you might want to use sparse matrices, especially for large arrays. Thus, for sparse matrix output, we would have an alternative one, like so -

from scipy.sparse import coo_matrix

def app_sparse(my_array):
    idx  = my_array.argmax()
    r,c = np.unravel_index(idx, my_array.shape)
    return coo_matrix(([my_array[r,c]],([r],[c])),shape=my_array.shape)

Sample run -

In [336]: my_array
Out[336]:
array([[0, 1, 2],
       [3, 4, 5],
       [8, 7, 8]])

In [337]: app_flat(my_array)
Out[337]:
array([[0, 0, 0],
       [0, 0, 0],
       [8, 0, 0]])

In [338]: app_sparse(my_array)
Out[338]:
<3x3 sparse matrix of type '<type 'numpy.int64'>'
    with 1 stored elements in COOrdinate format>

In [339]: app_sparse(my_array).toarray() # just to confirm values
Out[339]:
array([[0, 0, 0],
       [0, 0, 0],
       [8, 0, 0]])

Runtime test on bigger array -

In [340]: my_array =  np.random.randint(0,1000,(5000,5000))

In [341]: %timeit app_flat(my_array)
10 loops, best of 3: 34.9 ms per loop

In [342]: %timeit app_sparse(my_array) # sparse matrix output
100 loops, best of 3: 17.2 ms per loop


问:
Debugging keyboard events like 'Ctrl+Up Arrow'
I want to debug a part of a program that is intended to respond to keyboard input such as Ctrl+↑.

So, I put a breakpoint in the code in the area interest. However, once I press the Ctrl key the program jumps to that breakpoint. This happens before I have pressed an arrow key, so I'm finding this situation difficult to debug.

So, how can I debug a multi-key input event such as Ctrl+↑?

答:
If you are using Visual Studio to debug your code, you can debug this situation by adding a condition to your breakpoint.

To do so, right-click the break point icon to the left of your code statement and click Condition... An example of a condition that would apply to your situation is:

e.Control && e.KeyCode == Keys.Up
```

Now you can debug multi-key input events such as Ctrl+↑ without the need to change any of your code.

Body:
If you are using Visual Studio to debug your code, you can debug this situation by adding a condition to your breakpoint.

To do so, right-click the break point icon to the left of your code statement and click Condition... An example of a condition that would apply to your situation is:

e.Control && e.KeyCode == Keys.Up

Now you can debug multi-key input events such as Ctrl+↑ without the need to change any of your code.


问:
container engine ingress not working
I have a simple container in google container registry which basically does a few things and executes a binary which is a go based server, here are the contents of the DockerFile:

```<code>FROM debian:stable

WORKDIR /workspace/

COPY key.json .
COPY bin/user-creds.

EXPOSE 1108

ENV GOOGLE_APPLICATION_CREDENTIALS /workspace/key.json

RUN apt-get update \
    && apt-get install -y ca-certificates \
    && chmod +x user-creds

CMD ["./user-creds"]
</code>```

this container has been tested locally and works perfectly. So using the google cloud shell I ran this container:

```<code>kubectl run user-creds --image=eu.gcr.io/GCLOUD_PROJECT/user-creds:COMMIT_SHA --port=1108
</code>```

Then like it says on the doc, i exposed it on a nodeport

```<code>kubectl expose deployment user-creds --target-port=1108 --type=NodePort
</code>```

Then I created an ingress with a path to the sevice:

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: INGRESS_NAME
  annotations:
      kubernetes.io/ingress.global-static-ip-name: IP_NAME
spec:
  rules:
    - http:
        paths:
        - path: /user/creds/*
          backend:
            serviceName: user-creds
            servicePort: 1108
</code>```

then i created the ingress:

```<code>kubectl create -f INGRESS_NAME.yaml
</code>```

the ingress was created and i waited some time, here is the details of the ingress:

```<code>NAME                     HOSTS     ADDRESS        PORTS     AGE
INGRESS_NAME             *         IP_ADDRESS     80        38m
</code>```

but when i go the the actual url with the path I get a 502 error:

When I go to any other path I get the default backend 404 error but when i visit the specific /user/creds/ path i get the 502 error.

To check if it is something wrong with the cluster or my specific container, port or something else, I tried exposing the container as a LoadBalancer and it works perfectly, the Command:

```<code>kubectl expose deployment user-creds --target-port=1108 --port=80 --type=LoadBalancer
</code>```

service details:

```<code>NAME         TYPE           CLUSTER-IP      EXTERNAL-IP     PORT(S)        AGE
kubernetes   ClusterIP      INT_IP_ADDRESS  <none>          443/TCP        1h
user-creds   LoadBalancer   INT_IP_ADDRESS  IP_ADDRESS      80:31618/TCP   1m
</code>```

result: 200 with the correst response body.

Been stuck on this for time now, tried the ingress with no paths just the user-creds as the backend but still has the same error.

Any help or suggestion would be appreciated, thanks :)

答:
Finally figured it out, it was to do with the health check. The health check visits / and expects a 200, if it doesn't get it then it marks the backend as unhealthy and returns 502 for every requests sent to it. My problem was that I was using the / endpoint which would've normally returned a 400 if its being called with no specific request parameters.

It was really a human error on my side, it even specifically said that in the docs: https://cloud.google.com/kubernetes-engine/docs/tutorials/http-balancer#remarks

Another thing to consider is that the ingress returns all the the paths before the route so the the server needs to literally listen for /user/creds/ in my case.

Title: container engine ingress not working

Body:
I have a simple container in google container registry which basically does a few things and executes a binary which is a go based server, here are the contents of the DockerFile:

FROM debian:stable

WORKDIR /workspace/

COPY key.json .
COPY bin/user-creds.

EXPOSE 1108

ENV GOOGLE_APPLICATION_CREDENTIALS /workspace/key.json

RUN apt-get update \
    && apt-get install -y ca-certificates \
    && chmod +x user-creds

CMD ["./user-creds"]

this container has been tested locally and works perfectly. So using the google cloud shell I ran this container:

kubectl run user-creds --image=eu.gcr.io/GCLOUD_PROJECT/user-creds:COMMIT_SHA --port=1108

Then like it says on the doc, i exposed it on a nodeport

kubectl expose deployment user-creds --target-port=1108 --type=NodePort

Then I created an ingress with a path to the sevice:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: INGRESS_NAME
  annotations:
      kubernetes.io/ingress.global-static-ip-name: IP_NAME
spec:
  rules:
    - http:
        paths:
        - path: /user/creds/*
          backend:
            serviceName: user-creds
            servicePort: 1108

then i created the ingress:

kubectl create -f INGRESS_NAME.yaml

the ingress was created and i waited some time, here is the details of the ingress:

NAME                     HOSTS     ADDRESS        PORTS     AGE
INGRESS_NAME             *         IP_ADDRESS     80        38m

but when i go the the actual url with the path I get a 502 error:

When I go to any other path I get the default backend 404 error but when i visit the specific /user/creds/ path i get the 502 error.

To check if it is something wrong with the cluster or my specific container, port or something else, I tried exposing the container as a LoadBalancer and it works perfectly, the Command:

kubectl expose deployment user-creds --target-port=1108 --port=80 --type=LoadBalancer

service details:

NAME         TYPE           CLUSTER-IP      EXTERNAL-IP     PORT(S)        AGE
kubernetes   ClusterIP      INT_IP_ADDRESS  <none>          443/TCP        1h
user-creds   LoadBalancer   INT_IP_ADDRESS  IP_ADDRESS      80:31618/TCP   1m

result: 200 with the correst response body.

Been stuck on this for time now, tried the ingress with no paths just the user-creds as the backend but still has the same error.

Any help or suggestion would be appreciated, thanks :)


问:
unshare user namespace and set uid mapping with newuidmap
I'm trying to gain a better understanding of user namespaces by experimenting with the unshare and newuidmap commands.

These are the commands I ran:

```<code>[root@host ~]$ ls -l /usr/bin/newuidmap
-rwsr-xr-x 1 root root 32944 May 16 19:37 /usr/bin/newuidmap
[root@host ~]$  unshare -U bash namespace
[nobody@host ~]$ echo $$
7134
[nobody@host ~]$ newuidmap 7134 65534 5000 1
newuidmap: write to uid_map failed: Operation not permitted
</code>```

/etc/subuid:

```<code>nobody:5000:1
root:5000:1
</code>```

Any idea why this is failing?

I then tried to run the newuidmap command on the same PID from the parent namespace and it appeared to work:

```<code>[root@host ~]$ newuidmap 7134 65534 5000 1
[root@host ~]$ cat /proc/7134/uid_map
 65534       5000          1
</code>```

But when I run a process from within the new namespace it still seems to run as root instead of UID 5000:

```<code>[nobody@host ~]$ exec sleep 20
</code>```

From another shell:

```<code>[root@host ~]$ ps aux | grep 7134
root      7134  0.0  0.0   7292   708 pts/2    S+   02:07   0:00 sleep 20
</code>```

What am I missing?

答:
catanman

1)

```<code>[nobody@host ~]$ newuidmap 7134 65534 5000 1
newuidmap: write to uid_map failed: Operation not permitted
</code>```

Any idea why this is failing?

Documentation (http://man7.org/linux/man-pages/man7/user_namespaces.7.html) states the following:

The child process created by clone(2) with the CLONE_NEWUSER flag
  starts out with a complete set of capabilities in the new user
  namespace. <...> Note that a call to execve(2) will cause a process's
  capabilities to be recalculated in the usual way (see
  capabilities(7)).

This happens because unshare calls 'exec bash' before returing the control to the user and you loose the necessary capabilities, thus you cannot change uid_map/gid_map from within user namespace.

Still, if you compile some application (e.g. you can make a small fix in an example from user_namespaces(7)) which updates uid_map/gid_map before 'exec', the update will succeed.

2)

But when I run a process from within the new namespace it still seems
  to run as root instead of UID 5000:

What am I missing?

The mapping does not change the user. The mapping links ids in a child namespace to ids in its parent namespace, not the opposite way.

You can call setuid(2) or seteuid(2) from within a child namespace to change the credentials to some other credentials from the same user namespace. They of course should be mapped onto the values in the parent namespace, otherwise geteuid() function will fail.

Here are two examples:

Example 1. Suppose we have created a child user namespace.

```<code>arksnote linux-namespaces   # unshare -U bash
nobody@arksnote ~  $ id
uid=65534(nobody) gid=65534(nobody) группы=65534(nobody)
nobody@arksnote ~  $ echo $$
18526
</code>```

Now let's link root from parent namespace with some id (0 in this case) in a child namespace:

```<code>arksnote linux-namespaces   # newuidmap 18526 0 0 1
arksnote linux-namespaces   # cat /proc/18526/uid_map
         0          0          1
</code>```

Here's what happens to the child namespace:

```<code>nobody@arksnote ~  $ id
uid=0(root) gid=65534(nobody) группы=65534(nobody)
</code>```

You can try some other mappings, like newuidmap 18526 1 0 1 and see that it is applied to the child user namespace, not the parent one.

Example 2: Now we does not set a mapping for root:

```<code>arksnote linux-namespaces   # newuidmap 18868 0  1000 1
arksnote linux-namespaces   # cat /proc/18868/uid_map
         0       1000          1
</code>```

In this case the user root is left unknown for the child user namespace:

```<code>nobody@arksnote ~  $ id
uid=65534(nobody) gid=65534(nobody) группы=65534(nobody)
</code>```

What you have done with [root@host ~]$ newuidmap 7134 65534 5000 1 was association of userid 5000 in a parent namespace with uid 65534 in a child namespace, but the process still runs as root. It is shown as 65534 only because this value is used for any unknown id:

Functions getuid(), getgid() returns the value from /proc/sys/kernel/overflowgid for uids/gids which does not have a mapping. The value corresponds to a special user without any system rights:nobody, as you can see in uid/gid in the output above.

See Unmapped user and group IDs in user_namespaces(7).

Body:
I'm trying to gain a better understanding of user namespaces by experimenting with the unshare and newuidmap commands.

These are the commands I ran:

[root@host ~]$ ls -l /usr/bin/newuidmap
-rwsr-xr-x 1 root root 32944 May 16 19:37 /usr/bin/newuidmap
[root@host ~]$  unshare -U bash namespace
[nobody@host ~]$ echo $$
7134
[nobody@host ~]$ newuidmap 7134 65534 5000 1
newuidmap: write to uid_map failed: Operation not permitted

/etc/subuid:

nobody:5000:1
root:5000:1

Any idea why this is failing?

I then tried to run the newuidmap command on the same PID from the parent namespace and it appeared to work:

[root@host ~]$ newuidmap 7134 65534 5000 1
[root@host ~]$ cat /proc/7134/uid_map
 65534       5000          1

But when I run a process from within the new namespace it still seems to run as root instead of UID 5000:

[nobody@host ~]$ exec sleep 20

From another shell:

[root@host ~]$ ps aux | grep 7134
root      7134  0.0  0.0   7292   708 pts/2    S+   02:07   0:00 sleep 20

What am I missing?

Body:
catanman

1)

[nobody@host ~]$ newuidmap 7134 65534 5000 1
newuidmap: write to uid_map failed: Operation not permitted

Any idea why this is failing?

Documentation (http://man7.org/linux/man-pages/man7/user_namespaces.7.html) states the following:

The child process created by clone(2) with the CLONE_NEWUSER flag
  starts out with a complete set of capabilities in the new user
  namespace. <...> Note that a call to execve(2) will cause a process's
  capabilities to be recalculated in the usual way (see
  capabilities(7)).

This happens because unshare calls 'exec bash' before returing the control to the user and you loose the necessary capabilities, thus you cannot change uid_map/gid_map from within user namespace.

Still, if you compile some application (e.g. you can make a small fix in an example from user_namespaces(7)) which updates uid_map/gid_map before 'exec', the update will succeed.

2)

But when I run a process from within the new namespace it still seems
  to run as root instead of UID 5000:

What am I missing?

The mapping does not change the user. The mapping links ids in a child namespace to ids in its parent namespace, not the opposite way.

You can call setuid(2) or seteuid(2) from within a child namespace to change the credentials to some other credentials from the same user namespace. They of course should be mapped onto the values in the parent namespace, otherwise geteuid() function will fail.

Here are two examples:

Example 1. Suppose we have created a child user namespace.

arksnote linux-namespaces   # unshare -U bash
nobody@arksnote ~  $ id
uid=65534(nobody) gid=65534(nobody) группы=65534(nobody)
nobody@arksnote ~  $ echo $$
18526

Now let's link root from parent namespace with some id (0 in this case) in a child namespace:

arksnote linux-namespaces   # newuidmap 18526 0 0 1
arksnote linux-namespaces   # cat /proc/18526/uid_map
         0          0          1

Here's what happens to the child namespace:

nobody@arksnote ~  $ id
uid=0(root) gid=65534(nobody) группы=65534(nobody)

You can try some other mappings, like newuidmap 18526 1 0 1 and see that it is applied to the child user namespace, not the parent one.

Example 2: Now we does not set a mapping for root:

arksnote linux-namespaces   # newuidmap 18868 0  1000 1
arksnote linux-namespaces   # cat /proc/18868/uid_map
         0       1000          1

In this case the user root is left unknown for the child user namespace:

nobody@arksnote ~  $ id
uid=65534(nobody) gid=65534(nobody) группы=65534(nobody)

What you have done with [root@host ~]$ newuidmap 7134 65534 5000 1 was association of userid 5000 in a parent namespace with uid 65534 in a child namespace, but the process still runs as root. It is shown as 65534 only because this value is used for any unknown id:

Functions getuid(), getgid() returns the value from /proc/sys/kernel/overflowgid for uids/gids which does not have a mapping. The value corresponds to a special user without any system rights:nobody, as you can see in uid/gid in the output above.

See Unmapped user and group IDs in user_namespaces(7).


问:
JHipster - Maven and Yarn Execution
As per the JHipster documentation, I am supposed to be able to access the application by default at localhost:8080 but the page comes out to be blank. I installed yarn 0.27.5 and issues the command yarn start to start the UI. Now I am able to access the application at localhost:9000. I have to run the mvnw and yarn commands at the same time for the application to be available for use, but it should be just the maven command. Can someone please explain the reason and how do I do this from Eclipse.</p>

答:
You must run both yarn and maven in dev because yarn takes care of building your angular app while hot reloading your changes, maven takes care of building your spring boot app (including generating some code using annotation processors) and spring devtools takes care of hot reloading your java code changes.

I don't use Eclipse but I suppose that running yarn is just a matter of launching from the integrated terminal. Anyway this is not a problem because you have to do it only once thanks to hot reloading. More information about Eclipse here: http://www.jhipster.tech/configuring-ide-eclipse/

Title: JHipster - Maven and Yarn Execution


问:
Android - Can't connect to database from click listener
I have an AlertDialog that shows, prompts the user to enter text, and if the "Ok" button is pressed, I want it to call a method that connects to a database.

The database methods work because I tried connecting to the database outside the click listener and it works fine.

This is the exception I get:

```<code>com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
</code>```

And this is the method that shows the dialog:

```<code>RetrieveFolder() {
        AlertDialog.Builder inputBox = new AlertDialog.Builder(activity);
        inputBox.setTitle(getResources().getString(R.string.enter_share_code));
        EditText etInput = new EditText(activity);
        etInput.setMaxLines(1);
        inputBox.setView(etInput);

        inputBox.setPositiveButton("Ok", (dialog, whichButton) -> {
            input = etInput.getText().toString();
            if (folderExistsAndIsValid(input) && !alreadyShared(input)) {
                StudE.sendToDatabase("INSERT INTO tblSHARED VALUES(?, ?);", username, input);
                StudE.toast(getResources().getString(R.string.folder_retrieved_successfully), activity);

                finish();
                startActivity(getIntent());
            }
        });

        inputBox.setNegativeButton("Cancel", (dialog, whichButton) -> {});
        inputBox.show();
}
</code>```

Full Stack Trace:

```<code>W/System.err: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.Util.getInstance(Util.java:408)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2275)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2024)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
W/System.err:     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
W/System.err:     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:569)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err:     at woodward.stude.StudE.makeConnection(StudE.java:91)
W/System.err:     at woodward.stude.StudE.queryDatabase(StudE.java:145)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder.folderExistsAndIsValid(FlashcardFoldersActivity.java:305)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder.lambda$new$0$FlashcardFoldersActivity$RetrieveFolder(FlashcardFoldersActivity.java:291)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder$$Lambda$0.onClick(Unknown Source:0)
W/System.err:     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
W/System.err:     at android.os.Looper.loop(Looper.java:164)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6494)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
W/System.err:     at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:787)
W/System.err:     at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
W/System.err:     at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2196)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2229)
W/System.err:   ... 22 more
</code>```

答:
```<code>new Thread(new Runnable() {
    @Override
    public void run() {
        StudE.sendToDatabase("INSERT INTO tblSHARED VALUES(?, ?);", username, input);
    }
}).start();

StudE.toast(getResources().getString(R.string.folder_retrieved_successfully), activity);
</code>```

Creating a new thread and running database connections on that should work.

Body:
I have an AlertDialog that shows, prompts the user to enter text, and if the "Ok" button is pressed, I want it to call a method that connects to a database.

The database methods work because I tried connecting to the database outside the click listener and it works fine.

This is the exception I get:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.

And this is the method that shows the dialog:

RetrieveFolder() {
        AlertDialog.Builder inputBox = new AlertDialog.Builder(activity);
        inputBox.setTitle(getResources().getString(R.string.enter_share_code));
        EditText etInput = new EditText(activity);
        etInput.setMaxLines(1);
        inputBox.setView(etInput);

        inputBox.setPositiveButton("Ok", (dialog, whichButton) -> {
            input = etInput.getText().toString();
            if (folderExistsAndIsValid(input) && !alreadyShared(input)) {
                StudE.sendToDatabase("INSERT INTO tblSHARED VALUES(?, ?);", username, input);
                StudE.toast(getResources().getString(R.string.folder_retrieved_successfully), activity);

                finish();
                startActivity(getIntent());
            }
        });

        inputBox.setNegativeButton("Cancel", (dialog, whichButton) -> {});
        inputBox.show();
}

Full Stack Trace:

W/System.err: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.Util.getInstance(Util.java:408)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
W/System.err:     at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2275)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2024)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:779)
W/System.err:     at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
W/System.err:     at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
W/System.err:     at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
W/System.err:     at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:569)
W/System.err:     at java.sql.DriverManager.getConnection(DriverManager.java:219)
W/System.err:     at woodward.stude.StudE.makeConnection(StudE.java:91)
W/System.err:     at woodward.stude.StudE.queryDatabase(StudE.java:145)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder.folderExistsAndIsValid(FlashcardFoldersActivity.java:305)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder.lambda$new$0$FlashcardFoldersActivity$RetrieveFolder(FlashcardFoldersActivity.java:291)
W/System.err:     at woodward.stude.FlashcardFoldersActivity$RetrieveFolder$$Lambda$0.onClick(Unknown Source:0)
W/System.err:     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:106)
W/System.err:     at android.os.Looper.loop(Looper.java:164)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6494)
W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
W/System.err: Caused by: android.os.NetworkOnMainThreadException
W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
W/System.err:     at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:787)
W/System.err:     at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:188)
W/System.err:     at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:300)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2196)
W/System.err:     at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2229)
W/System.err:   ... 22 more

Body:
new Thread(new Runnable() {
    @Override
    public void run() {
        StudE.sendToDatabase("INSERT INTO tblSHARED VALUES(?, ?);", username, input);
    }
}).start();

StudE.toast(getResources().getString(R.string.folder_retrieved_successfully), activity);

Creating a new thread and running database connections on that should work.


问:
Excel how to find values in 1 column exist in the range of values in another
I have two columns- column A which extends upto 11027(values) and column I which extends to 42000(values).Both the columns contains some code details.

Something like this

```<code>A               B
q123           as124
as124          gh456
ff45           q123
dd1             dd2
xx2
xx3
xx4
</code>```

and so on...

I want to find if the names in column A exists in column B or not.using excel

答:
Use the formula by tigeravatar:

=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50

as conditional formatting.  Highlight column A.  Choose conditional formatting by forumula.  Enter the formula (above) - this finds values in col B that are also in A.  Choose a format (I like to use FILL and a bold color).

To find all of those values, highlight col A.  Data > Filter and choose Filter by color.

Body:
I have two columns- column A which extends upto 11027(values) and column I which extends to 42000(values).Both the columns contains some code details.

Something like this

A               B
q123           as124
as124          gh456
ff45           q123
dd1             dd2
xx2
xx3
xx4

and so on...

I want to find if the names in column A exists in column B or not.using excel


问:
try-catch block not catching the Exception
I'm using a try-catch block to identify the lack of some data in a database. Before I started using the while to check user input it was doing fine but now the try-catch block wont be executed (the while is inside the try-catch).
The exception I'm trying to catch is the InvalidOperationException thrown by the OleDbDataReader when the query returns nothing.</p>

```<code>try
{
    string _cmd = "SELECT razao_social FROM tblImobiliarias WHERE cnpj ='" + ValorConsulta.Text + "'";
    string conn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\\\\10.7.41.153\\Apoio\\Davi_Database\\Base_Imo.accdb";
    OleDbConnection Connection = new OleDbConnection(conn);
    OleDbCommand Command = new OleDbCommand(_cmd, Connection);
    Connection.Open();
    OleDbDataReader reader = Command.ExecuteReader();
    while (reader.Read())
    {
        int _resMatriz = 0;
        DialogResult result;
        result = MessageBox.Show(
              "Encontrado imobiliária: "
            + reader[_resMatriz]
            + ".\nEstá correto?", "Pesquisa", MessageBoxButtons.YesNo);
        _resMatriz++;
        if (result == System.Windows.Forms.DialogResult.Yes)
        {
            MessageBox.Show("CarregaImo()");
            break;
        }
        else
        {
            continue;
        }
    }
}
catch (InvalidOperationException ex)
{
    MessageBox.Show(
        "O CNPJ "
        + ValorConsulta.Text
        + " não foi localizado no sistema.\nOs dados não podem ter pontuação. Tente novamente",
        "Pesquisa",
        MessageBoxButtons.OK,
        MessageBoxIcon.Error);
    throw new InvalidOperationException();
}
</code>```

答:
I would advise against using an Exception for normal application logic. If your reader has no results, you can use the 'HasRows` property like so:

```<code>OleDbDataReader reader = Command.ExecuteReader();
if(reader.HasRows)
{
    // Do what you need if there are rows
}
else // Instead of an exception handler
{
    MessageBox.Show("O CNPJ " + ValorConsulta.Text + " não foi localizado no sistema.\nOs dados não podem ter pontuação. Tente novamente", "Pesquisa", MessageBoxButtons.OK, MessageBoxIcon.Error);
    throw new InvalidOperationException(); // If you must throw the exception
}
</code>```

Body:
I'm using a try-catch block to identify the lack of some data in a database. Before I started using the while to check user input it was doing fine but now the try-catch block wont be executed (the while is inside the try-catch).
The exception I'm trying to catch is the InvalidOperationException thrown by the OleDbDataReader when the query returns nothing.

try
{
    string _cmd = "SELECT razao_social FROM tblImobiliarias WHERE cnpj ='" + ValorConsulta.Text + "'";
    string conn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\\\\10.7.41.153\\Apoio\\Davi_Database\\Base_Imo.accdb";
    OleDbConnection Connection = new OleDbConnection(conn);
    OleDbCommand Command = new OleDbCommand(_cmd, Connection);
    Connection.Open();
    OleDbDataReader reader = Command.ExecuteReader();
    while (reader.Read())
    {
        int _resMatriz = 0;
        DialogResult result;
        result = MessageBox.Show(
              "Encontrado imobiliária: "
            + reader[_resMatriz]
            + ".\nEstá correto?", "Pesquisa", MessageBoxButtons.YesNo);
        _resMatriz++;
        if (result == System.Windows.Forms.DialogResult.Yes)
        {
            MessageBox.Show("CarregaImo()");
            break;
        }
        else
        {
            continue;
        }
    }
}
catch (InvalidOperationException ex)
{
    MessageBox.Show(
        "O CNPJ "
        + ValorConsulta.Text
        + " não foi localizado no sistema.\nOs dados não podem ter pontuação. Tente novamente",
        "Pesquisa",
        MessageBoxButtons.OK,
        MessageBoxIcon.Error);
    throw new InvalidOperationException();
}

Body:
I would advise against using an Exception for normal application logic. If your reader has no results, you can use the 'HasRows` property like so:

OleDbDataReader reader = Command.ExecuteReader();
if(reader.HasRows)
{
    // Do what you need if there are rows
}
else // Instead of an exception handler
{
    MessageBox.Show("O CNPJ " + ValorConsulta.Text + " não foi localizado no sistema.\nOs dados não podem ter pontuação. Tente novamente", "Pesquisa", MessageBoxButtons.OK, MessageBoxIcon.Error);
    throw new InvalidOperationException(); // If you must throw the exception
}


问:
How do I group all values in a pandas column that have a frequency of 2 or less
Here is a fictitious example:

```<code>id cluster
1 3
2 3
3 3
4 1
5 5
</code>```

So the cluster for id 4 and 5 should be replaced by some text.

So, I'm able to find which values have a frequency of less than 3 using:

```<code>counts = distclust.groupby("cluster")["cluster"].count()
counts[counts < 3].index.values
</code>```

Now, I'm not sure I go and replace these values in my dataframe with some arbitrary text (i.e. "noise")

I think that is enough information, let me know if you'd like me to include anything else:

答:
```<code>df.cluster.replace((df.cluster.value_counts()<=1).replace({True:'noise',False:np.nan}).dropna())
Out[627]:
0        3
1        3
2        3
3    noise
4    noise
Name: cluster, dtype: object
</code>```

<p>After assign it back </p>

```<code>df.cluster=df.cluster.replace((df.cluster.value_counts()<=1).replace({True:'noise',False:np.nan}).dropna())
df
Out[629]:
   id cluster
0   1       3
1   2       3
2   3       3
3   4   noise
4   5   noise
</code>```

Body:
Here is a fictitious example:

id cluster
1 3
2 3
3 3
4 1
5 5

So the cluster for id 4 and 5 should be replaced by some text.

So, I'm able to find which values have a frequency of less than 3 using:

counts = distclust.groupby("cluster")["cluster"].count()
counts[counts < 3].index.values

Now, I'm not sure I go and replace these values in my dataframe with some arbitrary text (i.e. "noise")

I think that is enough information, let me know if you'd like me to include anything else:

Body:
df.cluster.replace((df.cluster.value_counts()<=1).replace({True:'noise',False:np.nan}).dropna())
Out[627]:
0        3
1        3
2        3
3    noise
4    noise
Name: cluster, dtype: object

After assign it back

df.cluster=df.cluster.replace((df.cluster.value_counts()<=1).replace({True:'noise',False:np.nan}).dropna())
df
Out[629]:
   id cluster
0   1       3
1   2       3
2   3       3
3   4   noise
4   5   noise


问:
How to export an named instance in Vue.js, stop using: var app = this
I'm using .vue templates within a vue-cli created webpack project.

I typically use "export default" to export files, like this:

```<code> export default {
   data () {
     return {
       message:''
     };
 },
 ...
</code>```

Later in the script, when I try to access the instance, it seems within any function or third party library like axios, I have to write something like this at the top:

```<code> var app = this;
</code>```

so I can access data properties...for example:

```<code>    var app = this;

    axios.post('https://test.com/api/getMessage',{}).then(res => {
        app.message = res.data.message
    })
    .catch(error => {
        console.log(error)
    });
</code>```

But calling var app = this; all the time gets really tiresome.

I would prefer to put the instance in a variable like:

```<code> let app = {
  data () {
    return {
       message:''
  };
 },
 methods :{
   getMessage:function(){

        axios.post('https://test.com/api/getMessage',{}).then(res => {
            app.message = res.data.message
        })
        .catch(error => {
            console.log(error)
        });
   }
 }
}
</code>```

But I don't understand how to export or import it properly. It seems every example just uses export default. So to restate my question, is there better /smarter way to export and import the script so I don't have to write:

```<code> var app = this;
</code>```

答:
```<code>axios.post('https://test.com/api/getMessage',{}).then(res => {
    this.message = res.data.message
})
</code>```

That should work - Arrow functions take place in the scope in which they are written, meaning this will refer to your Vue instance there.  If you were not using arrow functions, you would have to specifically bind the scope:

```<code>axios.post('https://test.com/api/getMessage',{}).then(function(res){
    this.message = res.data.message
}.bind(this))
</code>```

Body:
I'm using .vue templates within a vue-cli created webpack project.

I typically use "export default" to export files, like this:

 export default {
   data () {
     return {
       message:''
     };
 },
 ...

Later in the script, when I try to access the instance, it seems within any function or third party library like axios, I have to write something like this at the top:

 var app = this;

so I can access data properties...for example:

    var app = this;

    axios.post('https://test.com/api/getMessage',{}).then(res => {
        app.message = res.data.message
    })
    .catch(error => {
        console.log(error)
    });

But calling var app = this; all the time gets really tiresome.

I would prefer to put the instance in a variable like:

 let app = {
  data () {
    return {
       message:''
  };
 },
 methods :{
   getMessage:function(){

        axios.post('https://test.com/api/getMessage',{}).then(res => {
            app.message = res.data.message
        })
        .catch(error => {
            console.log(error)
        });
   }
 }
}

But I don't understand how to export or import it properly. It seems every example just uses export default. So to restate my question, is there better /smarter way to export and import the script so I don't have to write:

 var app = this;

Body:
axios.post('https://test.com/api/getMessage',{}).then(res => {
    this.message = res.data.message
})

That should work - Arrow functions take place in the scope in which they are written, meaning this will refer to your Vue instance there.  If you were not using arrow functions, you would have to specifically bind the scope:

axios.post('https://test.com/api/getMessage',{}).then(function(res){
    this.message = res.data.message
}.bind(this))


问:
starting cassandra on windows 7 error the system can not find the path specified
I have tried to get cassandra working on windows 7. I followed the instructions from:
http://php-cms-job.blogspot.de/2012/09/how-to-install-cassandra-and-configure.html
I have double checked the steps of creating the folders and changing the yaml file but always get the message after running cassandra.bat:
Starting Cassandra Server
The System cannot find the Path Specified

I can not find which path exactly, any tips?

答:
Cassandra will fail to start with no logs if the values in
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Apache Software Foundation\Procrun 2.0\cassandra\Parameters\Java are not correct.

For example, if the Jvm REG_SZ value is not pointing to the correct path for jvm.dll you will get a System event log Error with

"The cassandra service terminated with the following service-specific error: Incorrect function".

You can find where java is with >echo %JAVA_HOME%


问:
IE title changes to <afterHash> if the page has a url with '#' , and has flash/swf embedded in it
The issue is, if IE (6.0+) , has flash content embedded in it, and the url of the page has a # somewhere in it, then when the flash content loads ,or if the user interacts with it, then the title of the window, changes to the content that is places after hash.

e.g http://adobeflashwebsite.com/index.html#somediv

Then the title of the page changes to 'somediv' , the moment a user will click on flash content, or many a times even the moment the flash content loads.

This happens only in IE.

This below is a very specific case I was facing:

The following is the environment I am facing issues with:

Shinding engine to show an iGoogle like page

Sammy.js

Gadgets rendering flash/swf

The issue here is, no matter which plugin I try to embed flash with, I end up having the following problem

When the flash loads completely, it appends something like #tab/xx , which actually is a string used by sammy to store the last navigational history within the page

When, a user starts interacting with the flash, then the title is completely removed and only #tab/xx remains as the title.

When a gadget is refreshed, even then there is issue like #2.

Could someone suggest, what the issue could be?
Most probably is it related to sammy.js, as iGoogle doesn't have that issue.

答:
It is IE bug:

http://bugs.adobe.com/jira/browse/FP-240 (includes couple of workarounds)

http://www.mail-archive.com/discuss@jquery.com/msg14509.html

http://code.google.com/p/swfobject/issues/detail?id=293

If you are using sammy's title method you could delay the execution a bit to make it behave on IE.

```<code>setTimeout(function() {
    context.title('Some title');
}, 1000);
</code>```

This won't solve it really, but I have noticed that a little delay helps IE sometimes.

Body:
It is IE bug:

http://bugs.adobe.com/jira/browse/FP-240 (includes couple of workarounds)

http://www.mail-archive.com/discuss@jquery.com/msg14509.html

http://code.google.com/p/swfobject/issues/detail?id=293

If you are using sammy's title method you could delay the execution a bit to make it behave on IE.

setTimeout(function() {
    context.title('Some title');
}, 1000);

This won't solve it really, but I have noticed that a little delay helps IE sometimes.


问:
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 4130
I have the following json: (I see a map in an object called locations)
I make a gson call to convert it to an object with a map.
Maybe I am seeing the json wrong.
What I am doing wrong?

```<code>{
  "locations": {
    "0": {
      "locationNo": "10014",
      "inventoryLocationNo": "10014"
    },
    "1": {
      "locationNo": "10022",
      "inventoryLocationNo": "10022"
    },
    "2": {
      "locationNo": "10030",
      "inventoryLocationNo": "10030"
    },
 },
  "errors": {}
}
</code>```

Here is my code

I get the the exception when I make this call:

```<code>BATOLocationIDAPIResponse responseObject = gson.fromJson(container.body, BATOLocationIDAPIResponse.class);
</code>```

Here is my code

```<code>/**
 * POJO that represents the response wrapper for a Location API call.
 *
 */
public class BATOLocationIDAPIResponse {
    private BATOLocationContainer locations;
    private List<String> errors;
    }
    public List<String> getErrors() {
        return errors;
    }
    public class BATOLocationContainer {
        private Map<String, BATOAPILocation> locations;
     }
}
// Location object
    public class BATOAPILocation {
        public String locationNo;
        public String inventoryLocationNo;
     }
</code>```

答: You have private List<String> errors;, but your JSON shows "errors": {} this should be an Array like "errors": []

Body:
I have the following json: (I see a map in an object called locations)
I make a gson call to convert it to an object with a map.
Maybe I am seeing the json wrong.
What I am doing wrong?

{
  "locations": {
    "0": {
      "locationNo": "10014",
      "inventoryLocationNo": "10014"
    },
    "1": {
      "locationNo": "10022",
      "inventoryLocationNo": "10022"
    },
    "2": {
      "locationNo": "10030",
      "inventoryLocationNo": "10030"
    },
 },
  "errors": {}
}

Here is my code

I get the the exception when I make this call:

BATOLocationIDAPIResponse responseObject = gson.fromJson(container.body, BATOLocationIDAPIResponse.class);

Here is my code

/**
 * POJO that represents the response wrapper for a Location API call.
 *
 */
public class BATOLocationIDAPIResponse {
    private BATOLocationContainer locations;
    private List<String> errors;
    }
    public List<String> getErrors() {
        return errors;
    }
    public class BATOLocationContainer {
        private Map<String, BATOAPILocation> locations;
     }
}
// Location object
    public class BATOAPILocation {
        public String locationNo;
        public String inventoryLocationNo;
     }