问:
Node.JS raw socket: how to do repeated connect-disconnect?
Currently I am trying to repeatedly connect and disconnect to a device (TCP socket). Here is the flow

Connect to the device

Send a "data".

Have a delay of 200msec to ensure that the other end receives the data and it has already replied.

Process the data

Disconnect.

Wait for 1 second

Go back to 1.

This 1-time connection code is working (I got it from the web):

```<code>var net = require('net');
var HOST = '127.0.0.1';
var PORT = 23;

// (a) =========
var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
    client.write('data');

});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {

    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();
});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

// (b) =========
</code>```

Currently, the code above works for 1 time connection. I did put the code from (a) to (b) in a while(true) loops and placed a sleep of 1 second at the end using https://www.npmjs.com/package/sleep and it seems the connect isn't executing on that setup.

Any thoughts on this will be helpful.

答:
I think the best way to do this, is to encapsule what you want to do in a function "loopConnection", and call recursively on each client.on('close') like this :

```<code>var net = require('net');
var HOST = '127.0.0.1';
var PORT = 23;

var loopConnection = function() {
    var client = new net.Socket();

    client.connect(PORT, HOST, function() {
        console.log('CONNECTED TO: ' + HOST + ':' + PORT);
        client.write('data');
    });

    client.on('data', function(data) {
        console.log('DATA: ' + data);
        client.destroy();
    });

    client.on('close', function() {
        console.log('Connection closed');
        setTimeout(function() {
            loopConnection(); // restart again
        }, 1000); // Wait for one second
    });
};

loopConnection(); // Initialize and first call loopConnection
</code>```

Hope it helps.

Body:
Currently I am trying to repeatedly connect and disconnect to a device (TCP socket). Here is the flow

Connect to the device

Send a "data".

Have a delay of 200msec to ensure that the other end receives the data and it has already replied.

Process the data

Disconnect.

Wait for 1 second

Go back to 1.

This 1-time connection code is working (I got it from the web):

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 23;

// (a) =========
var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
    client.write('data');

});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {

    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();
});

// Add a 'close' event handler for the client socket
client.on('close', function() {
    console.log('Connection closed');
});

// (b) =========

Currently, the code above works for 1 time connection. I did put the code from (a) to (b) in a while(true) loops and placed a sleep of 1 second at the end using https://www.npmjs.com/package/sleep and it seems the connect isn't executing on that setup.

Any thoughts on this will be helpful.

Body:
I think the best way to do this, is to encapsule what you want to do in a function "loopConnection", and call recursively on each client.on('close') like this :

var net = require('net');
var HOST = '127.0.0.1';
var PORT = 23;

var loopConnection = function() {
    var client = new net.Socket();

    client.connect(PORT, HOST, function() {
        console.log('CONNECTED TO: ' + HOST + ':' + PORT);
        client.write('data');
    });

    client.on('data', function(data) {
        console.log('DATA: ' + data);
        client.destroy();
    });

    client.on('close', function() {
        console.log('Connection closed');
        setTimeout(function() {
            loopConnection(); // restart again
        }, 1000); // Wait for one second
    });
};

loopConnection(); // Initialize and first call loopConnection

Hope it helps.


来源: stackexchange

问:
Safely locking variable in Swift 3 using GCD
How to lock variable and prevent from different thread changing it at the same time, which leads to error?

I tried using

```<code>func lock(obj: AnyObject, blk:() -> ()) {
     objc_sync_enter(obj)
     blk()
     objc_sync_exit(obj)
}
</code>```

but i still have multithreading issues.

答:
Shared Value

If you have a shared value that you want to access in a thread safe way like this

```<code>var list:[Int] = []
</code>```

DispatchQueue

You can create your own serial DispatchQueue.

```<code>let serialQueue = DispatchQueue(label: "SerialQueue")
</code>```

Dispatch Synch

Now different threads can safely access list, you just need to write the code into a closure dispatched to your serial queue.

```<code>serialQueue.sync {
   // update list <---
}
// This line will always run AFTER the closure on the previous line
</code>```

Since the serial queue executes the closures one at the time, the access to list will be safe.

Please note that the previous code will block the current thread until the closure is executed.

Dispatch Asynch

If you don't want to block the current thread until the closure is processed by the serial queue, you can dispatch the closure asynchronously

```<code>serialQueue.async {
   // update list <---
}
// This line can run BEFORE the closure on the previous line
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to lock variable and prevent from different thread changing it at the same time, which leads to error?

I tried using

func lock(obj: AnyObject, blk:() -> ()) {
     objc_sync_enter(obj)
     blk()
     objc_sync_exit(obj)
}

but i still have multithreading issues.

Body:
Shared Value

If you have a shared value that you want to access in a thread safe way like this

var list:[Int] = []

DispatchQueue

You can create your own serial DispatchQueue.

let serialQueue = DispatchQueue(label: "SerialQueue")

Dispatch Synch

Now different threads can safely access list, you just need to write the code into a closure dispatched to your serial queue.

serialQueue.sync {
   // update list <---
}
// This line will always run AFTER the closure on the previous line

Since the serial queue executes the closures one at the time, the access to list will be safe.

Please note that the previous code will block the current thread until the closure is executed.

Dispatch Asynch

If you don't want to block the current thread until the closure is processed by the serial queue, you can dispatch the closure asynchronously

serialQueue.async {
   // update list <---
}
// This line can run BEFORE the closure on the previous line

ContentLicense: CC BY-SA 4.0


问:
Why is not updated model in ngFor after changed model?
I have an property:

```<code>public rows: any[];
</code>```

Then I fill this array in constructor:

```<code>this.rows.push({"id": 1, "subject": "Subject", "scope": "Learn basics", "hours": 2});
</code>```

In template I iterate array like as:

```<code><tr *ngFor="let p of rows; let i = index;">
</code>```

So, if I remove element from array:

```<code>this.rows.splice(this.rows.length - 1, 1);
</code>```

It does not change model, I see as before one row in array.

答: re-assign the array so that angular can notice a change and update the array</p>

Body:
I have an property:

public rows: any[];

Then I fill this array in constructor:

this.rows.push({"id": 1, "subject": "Subject", "scope": "Learn basics", "hours": 2});

In template I iterate array like as:

So, if I remove element from array:

this.rows.splice(this.rows.length - 1, 1);

It does not change model, I see as before one row in array.


问:
double(<character>) gives different result in MATLAB and Octave
MATLAB (documentation):

```<code>>> double('α')
ans =
   945
</code>```

Octave 4.0.0, Ubuntu 16.04 (documentation):

```<code>>> double('α')
ans =
   206   177
</code>```

Why do I get different results?

Note: 'α' is a greek lowercase alpha.

答:
This is because the default encoding in MATLAB is 'US-ASCII' (can be different depending on Locale settings) while in Octave, it is 'UTF-8'.

To confirm, here is the result from MATLAB:

```<code>>> unicode2native('α', 'UTF-8')

ans =

  1×2 uint8 row vector

   206   177
</code>```

You can check your encoding with feature or slCharacterEncoding() :

```<code>feature('DefaultCharacterSet')
</code>```

or

```<code>slCharacterEncoding()
</code>```

According to Mathworks, you can change your encoding with:

```<code>slCharacterEncoding(encoding)
</code>```

I didn't have much luck in changing the encoding and getting the same results afterwards. It could be a bug.

Body:
MATLAB (documentation):

>> double('α')
ans =
   945

Octave 4.0.0, Ubuntu 16.04 (documentation):

>> double('α')
ans =
   206   177

Why do I get different results?

Note: 'α' is a greek lowercase alpha.

Body:
This is because the default encoding in MATLAB is 'US-ASCII' (can be different depending on Locale settings) while in Octave, it is 'UTF-8'.

To confirm, here is the result from MATLAB:

>> unicode2native('α', 'UTF-8')

ans =

  1×2 uint8 row vector

   206   177

You can check your encoding with feature or slCharacterEncoding() :

feature('DefaultCharacterSet')

or

slCharacterEncoding()

According to Mathworks, you can change your encoding with:

slCharacterEncoding(encoding)

I didn't have much luck in changing the encoding and getting the same results afterwards. It could be a bug.


问:
When i click edit button Dropdown value is not display using mvc?
When i click edit button. the drop down value is not coming but in  ViewBag.DomainID value is present but it is not displaying. it shows The specified cast from a materialized 'System.Int64' type to the 'System.Int32' type is not valid.

Controller:

```<code>[Authorize]
        [MyExceptionHandler]
        public ActionResult EditModules(int id)
        {
            EditDomain_Bind();
            userType type = new userType();
            var ModID = type.GetEditRoleModulesViews(id).Find(Emp => Emp.ModuleID == id);
            int domainID = ModID.DomainID;
            AccountContext db = new AccountContext();
            string selected = (from sub in db.domain
                               where sub.DomainID == domainID
                               select sub.DomainName).First();
            ViewBag.DomainID = new SelectList(db.domain, "DomainID", "DomainName", selected);

            return View(ModID);
        }
</code>```

Cs.HTML:

```<code><div class="col-lg-4">
                            <fieldset class="form-group">
                                <label class="form-label" for="exampleInput">Domain Name</label>
                                @Html.DropDownList("DomainID")
                                @Html.ValidationMessageFor(model => Model.DomainID, null, new { @style = "color: red" })
                            </fieldset>
                        </div>
</code>```

Models:

```<code>public DbSet<Domain> domain { get; set; }
    public class Domain
    {
        [Key]
        public int DomainID { get; set; }
        public string DomainName { get; set; }

    }
</code>```

答:
The problem is that you have defined DomainID as:

```<code>public int DomainID { get; set; }
</code>```

in C#, but it is a bigint (i.e. long) in the database. Thus instead you need to use:

```<code>public long DomainID { get; set; }
</code>```

And change all other int DomainID references as well. Such as:

```<code>long domainID = ModID.DomainID;
</code>```

Body:
When i click edit button. the drop down value is not coming but in  ViewBag.DomainID value is present but it is not displaying. it shows The specified cast from a materialized 'System.Int64' type to the 'System.Int32' type is not valid.

Controller:

[Authorize]
        [MyExceptionHandler]
        public ActionResult EditModules(int id)
        {
            EditDomain_Bind();
            userType type = new userType();
            var ModID = type.GetEditRoleModulesViews(id).Find(Emp => Emp.ModuleID == id);
            int domainID = ModID.DomainID;
            AccountContext db = new AccountContext();
            string selected = (from sub in db.domain
                               where sub.DomainID == domainID
                               select sub.DomainName).First();
            ViewBag.DomainID = new SelectList(db.domain, "DomainID", "DomainName", selected);

            return View(ModID);
        }

Cs.HTML:

                            <fieldset class="form-group">
                                Domain Name
                                @Html.DropDownList("DomainID")
                                @Html.ValidationMessageFor(model => Model.DomainID, null, new { @style = "color: red" })
                            </fieldset>

Models:

public DbSet<Domain> domain { get; set; }
    public class Domain
    {
        [Key]
        public int DomainID { get; set; }
        public string DomainName { get; set; }

    }

Body:
The problem is that you have defined DomainID as:

public int DomainID { get; set; }

in C#, but it is a bigint (i.e. long) in the database. Thus instead you need to use:

public long DomainID { get; set; }

And change all other int DomainID references as well. Such as:

long domainID = ModID.DomainID;


问:
How can I get the equivalent non-utf8 chars from a utf8 string?
ruby 1.8.6, rails 2.3.8

Im doing some evals to write some methods to a class, and its working out nice(first time playing w/ metaprogramming :p), except that some strings that need to go into the methods(as code, and not strings) have accented characters and etc...

for example, I need to get "restricao" from the string "restrição", how can I do that, please?

答:
Use Iconv with TRANSLIT-feature, for example:</p>

```<code>require 'iconv'
Iconv.conv("ASCII//TRANSLIT", "UTF-8", "restrição") == "restricao"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Use Iconv with TRANSLIT-feature, for example:

require 'iconv'
Iconv.conv("ASCII//TRANSLIT", "UTF-8", "restrição") == "restricao"


问:
RxSwift - Stop duplicate subscribes to an observer
I'm subscribing an UITableViewCell to an Observer in order to handle changes to that cell (I'm currently doing this at:

```<code>tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
</code>```

Problem I have is as the cell on any kind of reload is then re-subscribed and anytime I do an "onNext" the observer is fired multiple times.

Is there anyway to stop a particular Observer from being subscribed multiple times?

I've attempted to keep a list of Cells that have been subscribed and stop them from re-subscribing - but this seems to cause other issues further down the line (and doesn't feel like the right solution)

答:
Create a DisposeBag in your cell, then attach your subscribe event on it.

Reset the bag in the prepareForReuse.

You can also add a debug() call bedfore the subscribe to check if onComplete is properly called

Body:
I'm subscribing an UITableViewCell to an Observer in order to handle changes to that cell (I'm currently doing this at:

tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

Problem I have is as the cell on any kind of reload is then re-subscribed and anytime I do an "onNext" the observer is fired multiple times.

Is there anyway to stop a particular Observer from being subscribed multiple times?

I've attempted to keep a list of Cells that have been subscribed and stop them from re-subscribing - but this seems to cause other issues further down the line (and doesn't feel like the right solution)


问:
Weird deployement on Tomcat with Eclipse
I have been working on a Java (Java 8) web application in Eclipse, using maven for one year. I created this webapp and use Maven v 3.5 since the beginning of my project. I usually deploy my web application on a tomcat 8.5 server ('Run as => run on server').

I have always managed my dependencies with my pom.xml, preventing with doing weird things using hte build path configuration menu from Eclipse.

The issue started yesterday : I add a dependency from other java/maven project I have madeand installed simply before, and add this lines on my pom.xml :

```<code>    <dependency>
        <groupId>tlnPdf</groupId>
        <artifactId>tlnPdf</artifactId>
        <version>1.0</version>
    </dependency>
</code>```

As my eclipse does sometimes when I add a new dependancy from other project, I had an issue when deploying the webapp, some message (sorry but I can't remember it) about the pom.properties from my other project. In this case, and as I always did, I just have to close my webapp project, launch a mvn eclipse:clean from a command prompt and then reopen my project; and the issue disappear.

Eclipse doesn't show issue on the classes that import classes from the new dependancy included.

Also I have a listener on a class at the starting of my webapp, declared on my web.xml :

```<code>  <listener>
    <listener-class>com.package.InitTomcat</listener-class>
</listener>
</code>```

This listener is funcional and I have not modified it lastly.

But yesterday, a new issue appear; when I wanted to deploy my webapp on my server, I had a lot of warning like this :
org.apache.catalina.webresources.Cache.getResource Unable to add the resource at [...] to the cache because there was insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache. And then, an error telling me that the InitTomcat class does not exist :
java.lang.ClassNotFoundException: com.package.InitTomcat

So, firstly I thought that the cache warning was causing the issue. I did what this this stackoverflow post explain, and the warnings disappeared; but not the error.

Outside from eclipse, in a command prompt, I try to compile my project and getting my app.war file using mvn clean install. The compilation did not show any error, and the war is correct. I deployed manually my war on tomcat and no issue appeared.

Thus, I look on the two deployed directory (one from eclipse, the other manually by my app.war) and I saw something curious on the tree of repository deployed :

On the good deployed webapp (from app.war), I have something like that:

```<code> |*some directories and files
 |*META-INF
 |*WEB-INF
     |*classes
       |com (etc...)
     |*lib
     |web.xml
</code>```

And in the deployed webapp from eclipse :

```<code>*some directories and files
*META-INF
*WEB-INF
    |*classes
       |*.settings (why the hell does this directory are here ?)
       |*bin
          |*.settings
          |*src
          |*target
              |*classes
                  |*com ect... (my .class files are here !!)
              |*generated-sources
              |*m2e-wtp
              |*maven-archiver
              |*maven-status
              |*myapp (this directory have the same content as the "good web app deployed")
              |*test-classes
              |*WebContent
          |*temp
          |*webContent
          |pom.xml
          |.project
       |*src
       |*target
       |*temp
       |*WebContent
              |*...
    |*lib
    |web.xml
</code>```

The "good" webapp as a size of 275Mb, the other is 865Mb

I suspect that the issue occur when eclipse deploy my web-app and which explain that it could not find the InitTomcat class since it seems to be at the wrong place. But I have no idea why it decided to do this now.

I tries to delete the project from eclipse, cleaning eclipse, etc... but no result. I have tried with 3 different versions of tomcat : 8.5.14, 8.2.23 and 9.0.2, always with the same behaviour

As I was depressed, I download the last version of eclipse, and import my webapp project into it with maven; but it has the same result.

Finally, my question is simple : does anyone has an idea of what it is happening, and how to solve it ? Thanks in advance !

答:
I finally saw where my problem was: looking on properties > "deployment Assembly" of my project, the deploy pathes were weird. I dont know when did he change, nor why, but I did the following to reinitiate "cleanly" them:

Delete the project (but not the sources) in eclipse

Manually delete .settings directory, .classpath and .project files

Import as a maven project in eclipse

These do the tricks. The issue is that before, I had not deleted the properties files from eclipse and the bag configuration was reload when importing the project.

Body:
I have been working on a Java (Java 8) web application in Eclipse, using maven for one year. I created this webapp and use Maven v 3.5 since the beginning of my project. I usually deploy my web application on a tomcat 8.5 server ('Run as => run on server').

I have always managed my dependencies with my pom.xml, preventing with doing weird things using hte build path configuration menu from Eclipse.

The issue started yesterday : I add a dependency from other java/maven project I have madeand installed simply before, and add this lines on my pom.xml :

    <dependency>
        <groupId>tlnPdf</groupId>
        <artifactId>tlnPdf</artifactId>
        <version>1.0</version>
    </dependency>

As my eclipse does sometimes when I add a new dependancy from other project, I had an issue when deploying the webapp, some message (sorry but I can't remember it) about the pom.properties from my other project. In this case, and as I always did, I just have to close my webapp project, launch a mvn eclipse:clean from a command prompt and then reopen my project; and the issue disappear.

Eclipse doesn't show issue on the classes that import classes from the new dependancy included.

Also I have a listener on a class at the starting of my webapp, declared on my web.xml :

  <listener>
    <listener-class>com.package.InitTomcat</listener-class>
</listener>

This listener is funcional and I have not modified it lastly.

But yesterday, a new issue appear; when I wanted to deploy my webapp on my server, I had a lot of warning like this :
org.apache.catalina.webresources.Cache.getResource Unable to add the resource at [...] to the cache because there was insufficient free space available after evicting expired cache entries - consider increasing the maximum size of the cache. And then, an error telling me that the InitTomcat class does not exist :
java.lang.ClassNotFoundException: com.package.InitTomcat

So, firstly I thought that the cache warning was causing the issue. I did what this this stackoverflow post explain, and the warnings disappeared; but not the error.

Outside from eclipse, in a command prompt, I try to compile my project and getting my app.war file using mvn clean install. The compilation did not show any error, and the war is correct. I deployed manually my war on tomcat and no issue appeared.

Thus, I look on the two deployed directory (one from eclipse, the other manually by my app.war) and I saw something curious on the tree of repository deployed :

On the good deployed webapp (from app.war), I have something like that:

 |*some directories and files
 |*META-INF
 |*WEB-INF
     |*classes
       |com (etc...)
     |*lib
     |web.xml

And in the deployed webapp from eclipse :

*some directories and files
*META-INF
*WEB-INF
    |*classes
       |*.settings (why the hell does this directory are here ?)
       |*bin
          |*.settings
          |*src
          |*target
              |*classes
                  |*com ect... (my .class files are here !!)
              |*generated-sources
              |*m2e-wtp
              |*maven-archiver
              |*maven-status
              |*myapp (this directory have the same content as the "good web app deployed")
              |*test-classes
              |*WebContent
          |*temp
          |*webContent
          |pom.xml
          |.project
       |*src
       |*target
       |*temp
       |*WebContent
              |*...
    |*lib
    |web.xml

The "good" webapp as a size of 275Mb, the other is 865Mb

I suspect that the issue occur when eclipse deploy my web-app and which explain that it could not find the InitTomcat class since it seems to be at the wrong place. But I have no idea why it decided to do this now.

I tries to delete the project from eclipse, cleaning eclipse, etc... but no result. I have tried with 3 different versions of tomcat : 8.5.14, 8.2.23 and 9.0.2, always with the same behaviour

As I was depressed, I download the last version of eclipse, and import my webapp project into it with maven; but it has the same result.

Finally, my question is simple : does anyone has an idea of what it is happening, and how to solve it ? Thanks in advance !


问:
Form Validation in JavaScript-html
I've built a simple website that contains three pages. I created a form in home page and something goes wrong with my JavaScript - I'm having a problem in setting a field right next to the input field with a relevant message to the user telling him what they did wrong(prompt).
so I'm inputting below the homepage (the form which is in the body of the page -html) and the script itself which includes a simple function.

My purpose is to check if user fills the field name and after that they delete it, so I want to display a red color message that tells the user that this field is required.
I'd be glad if someone can help me with that.

function validateName(){
  var name=document.getElementById("fullName").value;
  if (name.length == null)
  {
    nameRequiredPromt("Name Is Required",fullNamePrompt,"white");
    return false;
  }
}

function nameRequiredPromt(message,promtLocation,color){
  document.getElementById(promtLocation).innerHTML=message;
  document.getElementById(promtLocation).style.color=color;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form" style="color:white;">
  <table>
    <tr>
      <td>
      FullName :
      </td>
      <td>
        <input type="text" placeholder="fullName" id="fullName"
        onkeyup="validateName()" type="text"/> <label id="fullNamePrompt">aaaa
        </label> <br>
      </td>
    </tr>
    <tr>
      <td>
      E-mail :
      </td>
      <td>
        <input type="email" placeholder="email" id="email"/><label
        id="emailPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>
      New Password :
      </td>
      <td>
        <input type="password" placeholder="password" id="newPassWord"/> <label
            id="PasswordPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>
      Repeat Password :
      </td>
      <td>
        <input type="password" placeholder="repeatedPassword"
        id="repeatedPassWord"/> <label id="repeatedPassWordPrompt"> </label><br>
      </td>
    </tr>
    <tr>
      <td>

      </td>
      <td>
        <input type="submit" value="submit" id="submit"/> <label
        id="submitPrompt"> </label><br>
      </td>
    </tr>
  </table>
</form></code>```

I did some checks to be sure that the script works and it did work so I think my problem is in the declaration of the label "id".

答:
```<code>if (name && !name.length)
{
    nameRequiredPromt("Name Is Required","fullNamePrompt","white");
    return false;
}
</code>```

first condition checks if name is null, second for checking if name.length is 0.

Title: Form Validation in JavaScript-html

Body:
I've built a simple website that contains three pages. I created a form in home page and something goes wrong with my JavaScript - I'm having a problem in setting a field right next to the input field with a relevant message to the user telling him what they did wrong(prompt).
so I'm inputting below the homepage (the form which is in the body of the page -html) and the script itself which includes a simple function.

My purpose is to check if user fills the field name and after that they delete it, so I want to display a red color message that tells the user that this field is required.
I'd be glad if someone can help me with that.

function validateName(){
  var name=document.getElementById("fullName").value;
  if (name.length == null)
  {
    nameRequiredPromt("Name Is Required",fullNamePrompt,"white");
    return false;
  }
}

function nameRequiredPromt(message,promtLocation,color){
  document.getElementById(promtLocation).innerHTML=message;
  document.getElementById(promtLocation).style.color=color;
}

<form id="form" style="color:white;">

      FullName :

        <input type="text" placeholder="fullName" id="fullName"
        onkeyup="validateName()" type="text"/> aaaa

      E-mail :

        <input type="email" placeholder="email" id="email"/>

      New Password :

        <input type="password" placeholder="password" id="newPassWord"/>

      Repeat Password :

        <input type="password" placeholder="repeatedPassword"
        id="repeatedPassWord"/>

        <input type="submit" value="submit" id="submit"/>

</form>

I did some checks to be sure that the script works and it did work so I think my problem is in the declaration of the label "id".

Body:
if (name && !name.length)
{
    nameRequiredPromt("Name Is Required","fullNamePrompt","white");
    return false;
}

first condition checks if name is null, second for checking if name.length is 0.


问:
How to select the parent's parent in CSS?
```<code><div id="maincontent">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>
</code>```

Is it possible to have a rule that would match #maincontent only if #admin exists using just CSS?

It's just I have a background colour in the control panel but don't want it there for visitors.

答:
Unfortunately, there is no parent selector in CSS.  </p>

<p>You will have to use javascript to do this on the client. </p>

Body:
Unfortunately, there is no parent selector in CSS.

You will have to use javascript to do this on the client.


问:
not able to read iio file from userspace
I am trying to read following file from C code.

file:   /sys/bus/iio/devices/iio\:device0/in_voltage7_raw

but file pointer I am getting is -1.

Using cat command it is able to read the file.

But I am trying to read the same from my code as follows:

```<code>nos_int32 nos_adc_read_port (ADC_PORT_DB *p_port, nos_int32 *data)
{

    char file_name[VALUE_MAX];
    int value;
    char buffer[BUFFER_LENGTH];
    char intBuffer[INT_BUFFER_LENGTH];
    int fd;

    sprintf(file_name, "/sys/bus/iio/devices/iio\\:device0/in_voltage7_raw");

    fd = open(file_name, O_RDONLY);

    if (fd == -1) {
        return(-1);
    }
    if (read(fd, buffer, BUFFER_LENGTH) == -1) {
        return(-1);
    }
    close(fd);
    memcpy(intBuffer, buffer, BUFFER_LENGTH);
    intBuffer[INT_BUFFER_LENGTH-1] = '\0';
    value = atoi(intBuffer);
    *data = value;
    return(0);
}
</code>```

After the line:
fd = open(file_name, O_RDONLY);

value of fd is -1.  How can it be solved?

答:
Most command line shells use some characters for special actions and if you're trying to use them as their actual character, you need to prefix them with a backslash to escape them. In this case, your shell needs you to escape the colon when accessing that filename.

In C you don't have this issue so you can put in your code the filename as it truly is, such as:

"/sys/bus/iio/devices/iio:device0/in_voltage7_raw"

Body:
I am trying to read following file from C code.

file:   /sys/bus/iio/devices/iio\:device0/in_voltage7_raw

but file pointer I am getting is -1.

Using cat command it is able to read the file.

But I am trying to read the same from my code as follows:

nos_int32 nos_adc_read_port (ADC_PORT_DB *p_port, nos_int32 *data)
{

    char file_name[VALUE_MAX];
    int value;
    char buffer[BUFFER_LENGTH];
    char intBuffer[INT_BUFFER_LENGTH];
    int fd;

    sprintf(file_name, "/sys/bus/iio/devices/iio\\:device0/in_voltage7_raw");

    fd = open(file_name, O_RDONLY);

    if (fd == -1) {
        return(-1);
    }
    if (read(fd, buffer, BUFFER_LENGTH) == -1) {
        return(-1);
    }
    close(fd);
    memcpy(intBuffer, buffer, BUFFER_LENGTH);
    intBuffer[INT_BUFFER_LENGTH-1] = '\0';
    value = atoi(intBuffer);
    *data = value;
    return(0);
}

After the line:
fd = open(file_name, O_RDONLY);

value of fd is -1.  How can it be solved?


问:
Capture barcode scan when minimized
I'm dealing with a barcode scanner that acts as a keyboard emulation.
I print my barcode labels with a custom heading character (pipe) .
In my main form, I listen to the keypress event and as soon as I see the custom header character, I start receiving the scan and than do my stuffs.

This method works pretty well if my application is focused but can't do nothing if the application is minimized or unfocused.

I tried to setup a keyboard hotkey. It partialli works: my application get focused on the first character but is not fast enought to capture the subsequent characters spitted very fast from the scanner.

Any idea on how to capture this keystrokes with the application unfocused?
Obviously if the heading char id detected the subsequent characters must be suppressed until the sequence is completed with a vbcr or a timeout is reached.

Note that the scanner spits a sequence of 15 characters in less than a tenth of a second

答:
This is how Windows works, only the active application will handle keyboard input.  Thus, when your application is minimized, it will not receive or handle any keyboard input.

As Bradley Uffner commented, you need a global keyboard handler, I've used this in the past and it works quite well.  Basically a system wide listener that will handle keyboard input even while minimized.

Title: Capture barcode scan when minimized


问:
Run Zalenium Tests from another Docker instance
For our automated testing purposes, I am trying to run UI tests using the Zalenium Docker system.

The tests execute on a Jenkins slave, and are executed from a Pipeline script:

```<code>docker run --rm --name zalenium --detach -p 4444:4444 -v /var/run/docker.sock:/var/run/docker.sock -v /tmp/videos:/home/seluser/videos --privileged dosel/zalenium start"
</code>```

I then use another Docker container to execute the tests:

```<code>docker run --privileged --rm --volume=${workingDirectory}:/volume/git --workdir='/volume/git' some-container-name:0.1 mvn -f /project/pom.xml clean test -Dselenium.hub='http://localhost:4444'
</code>```

When I execute the tests, I see the following error:

```<code>    Tests run: 3, Failures: 2, Errors: 0,
    Skipped: 1, Time elapsed: 1.824  sec <<< FAILURE!
     - in TestSuite setupBrowser(com.skybet.myaccount.login.usingCorrectDetails)  Time elapsed: 1.108 sec  <<< FAILURE!
org.openqa.selenium.remote.UnreachableBrowserException:
 Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T18:33:54.468Z'
System info: host: '96a52140dee0', ip: 'X.X.X.X', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-693.5.2.el7.x86_64', java.version: '1.8.0_151' Driver info: driver.version: RemoteWebDriver Caused by: org.apache.http.conn.HttpHostConnectException: Connect to
    127.0.0.1:4444 [/127.0.0.1] failed: Connection refused (Connection refused) Caused by: java.net.ConnectException: Connection refused (Connection    refused)
</code>```

I'm not really sure what the correct address should be. Any ideas?

答:
I've found that the solution to my issue is to use the --link command, so I could link the Docker instance which executes my tests, to the Zalenium instance which hosts the grid system:

```<code>docker run --privileged --name stg-selenium-client --rm=true --link zalenium:hub hub.platformservices.io/sbg_core_automation/core-test-runner-with-maven-dependencies:0.12 mvn -f /project/pom.xml test -P ui -Denvironment=test5 -Dgroups=smoketest -Dbrowser.name=chrome -Dselenium.hub=hub:4444
</code>```

Body:
For our automated testing purposes, I am trying to run UI tests using the Zalenium Docker system.

The tests execute on a Jenkins slave, and are executed from a Pipeline script:

docker run --rm --name zalenium --detach -p 4444:4444 -v /var/run/docker.sock:/var/run/docker.sock -v /tmp/videos:/home/seluser/videos --privileged dosel/zalenium start"

I then use another Docker container to execute the tests:

docker run --privileged --rm --volume=${workingDirectory}:/volume/git --workdir='/volume/git' some-container-name:0.1 mvn -f /project/pom.xml clean test -Dselenium.hub='http://localhost:4444'

When I execute the tests, I see the following error:

    Tests run: 3, Failures: 2, Errors: 0,
    Skipped: 1, Time elapsed: 1.824  sec <<< FAILURE!
     - in TestSuite setupBrowser(com.skybet.myaccount.login.usingCorrectDetails)  Time elapsed: 1.108 sec  <<< FAILURE!
org.openqa.selenium.remote.UnreachableBrowserException:
 Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T18:33:54.468Z'
System info: host: '96a52140dee0', ip: 'X.X.X.X', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-693.5.2.el7.x86_64', java.version: '1.8.0_151' Driver info: driver.version: RemoteWebDriver Caused by: org.apache.http.conn.HttpHostConnectException: Connect to
    127.0.0.1:4444 [/127.0.0.1] failed: Connection refused (Connection refused) Caused by: java.net.ConnectException: Connection refused (Connection    refused)

I'm not really sure what the correct address should be. Any ideas?

Body:
I've found that the solution to my issue is to use the --link command, so I could link the Docker instance which executes my tests, to the Zalenium instance which hosts the grid system:

docker run --privileged --name stg-selenium-client --rm=true --link zalenium:hub hub.platformservices.io/sbg_core_automation/core-test-runner-with-maven-dependencies:0.12 mvn -f /project/pom.xml test -P ui -Denvironment=test5 -Dgroups=smoketest -Dbrowser.name=chrome -Dselenium.hub=hub:4444


问:
'Interface error: 2003' when connecting to database
I'm trying to use MySQL Connection/Python to connect to my database.

Here's the output I'm getting:

```<code>Traceback (most recent call last):
  File "bh2000.py", line 33, in <module>
    cnx = mysql.connector.connect(**config)
  File "/Library/Python/2.7/site-packages/mysql/connector/__init__.py", line 155, in connect
    return MySQLConnection(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 123, in __init__
    self.connect(**kwargs)
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 430, in connect
    self._open_connection()
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 393, in _open_connection
    self._socket.open_connection()
  File "/Library/Python/2.7/site-packages/mysql/connector/network.py", line 375, in open_connection
    errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'host xxx.db.1and1.com:3306' (8 nodename nor servname provided, or not known)
</code>```

Here's the code I'm using:

```<code>import mysql.connector

cnx = mysql.connector.connect(user='xxx', password='xxx',
                              host='xxx.db.1and1.com',
                              database='xxx')
cnx.close()
</code>```

Where am I going wrong?

答: I got the same error. Once crosscheck the details you have entered. The host must be in the format 127.0.0.1. There should not be any / after the url.

Body:
I'm trying to use MySQL Connection/Python to connect to my database.

Here's the output I'm getting:

Traceback (most recent call last):
  File "bh2000.py", line 33, in <module>
    cnx = mysql.connector.connect(**config)
  File "/Library/Python/2.7/site-packages/mysql/connector/__init__.py", line 155, in connect
    return MySQLConnection(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 123, in __init__
    self.connect(**kwargs)
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 430, in connect
    self._open_connection()
  File "/Library/Python/2.7/site-packages/mysql/connector/connection.py", line 393, in _open_connection
    self._socket.open_connection()
  File "/Library/Python/2.7/site-packages/mysql/connector/network.py", line 375, in open_connection
    errno=2003, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'host xxx.db.1and1.com:3306' (8 nodename nor servname provided, or not known)

Here's the code I'm using:

import mysql.connector

cnx = mysql.connector.connect(user='xxx', password='xxx',
                              host='xxx.db.1and1.com',
                              database='xxx')
cnx.close()

Where am I going wrong?


问:
groupby ngFor angular2
Good day, i've been trying to display an array by groups title, i get my array from a webservice and i want to display the item by groups title

example

Group1
item 1
item 2
item 3

Group2
item 1
item 2
item 3

here is my array

```<code>                [
                {
                    "id": "1",
                    "title": "Item 1",
                    "groups": [
                        {
                            "id": "2",
                            "title": "Communication"
                        }
                    ]
                },
                {
                    "id": "2",
                    "title": "Item 2",
                    "groups": [
                        {
                            "id": "2",
                            "title": "Communication"
                        }
                    ]
                },
                {
                    "id": "3",
                    "title": "Item 1",
                    "groups": [
                        {
                            "id": "1",
                            "title": "Creativie Art"
                        }
                    ]
                },
                {
                    "id": "4",
                    "title": "Item 3",
                    "groups": [
                        {
                            "id": "2",
                            "title": "Communication"
                        }
                    ]
                },
                {
                    "id": "5",
                    "title": "Item 2",
                    "groups": [
                        {
                            "id": "1",
                            "title": "Creativie Art"
                        }
                    ]
                },
                {
                    "id": "6",
                    "title": "Item 3",
                    "groups": [
                        {
                            "id": "1",
                            "title": "Creativie Art"
                        }
                    ]
                }
            ]
</code>```

i cant paste all the array data because its too long but this is the array structure

答:
Here is one option of how we can do it:

app.component.ts

const groupsDict = this.arr.reduce((acc, cur) => {
  cur.groups.forEach(({ id, title}) => {
    acc[id] = acc[id] || { id, title };
    acc[id].items = acc[id].items || [];
    acc[id].items.push({ id: cur.id, title: cur.title });
  });
  return acc;
}, {});
this.groups = Object.keys(groupsDict).map(x => groupsDict[x]);
```

<p><strong>app.component.html</strong></p>

<pre class="lang-html prettyprint-override"><code><div class="grid">
  <div *ngFor="let group of groups" class="col">
    <h2>{{ group.title }}</h2>
    <div *ngFor="let item of group.items">
      {{ item.title }}
    </div>
  </div>
</div>
</code>```

Stackblitz Example

Title: groupby ngFor angular2

Body:
Good day, i've been trying to display an array by groups title, i get my array from a webservice and i want to display the item by groups title

example

Group1
item 1
item 2
item 3

Group2
item 1
item 2
item 3

here is my array

                [
                {
                    "id": "1",
                    "title": "Item 1",
                    "groups": [
                        {
                            "id": "2",
                            "title": "Communication"
                        }
                    ]
                },
                {
                    "id": "2",
                    "title": "Item 2",
                    "groups": [
                        {
                            "id": "2",
                            "title": "Communication"
                        }
                    ]
                },
                {
                    "id": "3",
                    "title": "Item 1",
                    "groups": [
                        {
                            "id": "1",
                            "title": "Creativie Art"
                        }
                    ]
                },
                {
                    "id": "4",
                    "title": "Item 3",
                    "groups": [
                        {
                            "id": "2",
                            "title": "Communication"
                        }
                    ]
                },
                {
                    "id": "5",
                    "title": "Item 2",
                    "groups": [
                        {
                            "id": "1",
                            "title": "Creativie Art"
                        }
                    ]
                },
                {
                    "id": "6",
                    "title": "Item 3",
                    "groups": [
                        {
                            "id": "1",
                            "title": "Creativie Art"
                        }
                    ]
                }
            ]

i cant paste all the array data because its too long but this is the array structure

Body:
Here is one option of how we can do it:

app.component.ts

const groupsDict = this.arr.reduce((acc, cur) => {
  cur.groups.forEach(({ id, title}) => {
    acc[id] = acc[id] || { id, title };
    acc[id].items = acc[id].items || [];
    acc[id].items.push({ id: cur.id, title: cur.title });
  });
  return acc;
}, {});
this.groups = Object.keys(groupsDict).map(x => groupsDict[x]);

app.component.html

<div class="grid">
  <div *ngFor="let group of groups" class="col">
    <h2>{{ group.title }}</h2>
    <div *ngFor="let item of group.items">
      {{ item.title }}
    </div>
  </div>
</div>

Stackblitz Example


问:
Missing ) after argument list. What is missing from this?
```<code>var formBody = [];
for (var property in submitLeadData) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(`enter code here`submitLeadData[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

$.ajax({
    url: 'post.php',
    type: 'POST',
    dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
    data: submitLeadData,
    success: function() {
        $.ajax({
            type: "GET",
            url: submitBrokerLead,
            data: formBody,
            success: function(){
                alert(5);
            }

}

});
</code>```

What is missing?

答:
You dont close your functions correctly in the lines given below:</p>

```<code>$.ajax({
  url: 'post.php',
  type: 'POST',
  dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
  data: submitLeadData,
  success: function() {
    $.ajax({
      type: "GET",
      url: submitBrokerLead,
      data: formBody,
      success: function() {
        alert(5);
      }
    }); //add the bracket '(' and semi-colon ';' here
  } //add the curly bracket here
});
</code>```

Body:
var formBody = [];
for (var property in submitLeadData) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(`enter code here`submitLeadData[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

$.ajax({
    url: 'post.php',
    type: 'POST',
    dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
    data: submitLeadData,
    success: function() {
        $.ajax({
            type: "GET",
            url: submitBrokerLead,
            data: formBody,
            success: function(){
                alert(5);
            }

}

});

What is missing?

Body:
You dont close your functions correctly in the lines given below:

$.ajax({
  url: 'post.php',
  type: 'POST',
  dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
  data: submitLeadData,
  success: function() {
    $.ajax({
      type: "GET",
      url: submitBrokerLead,
      data: formBody,
      success: function() {
        alert(5);
      }
    }); //add the bracket '(' and semi-colon ';' here
  } //add the curly bracket here
});


问:
EditText underline color styling
I have a problem, I know that the underline in Lollipop is styled by colorControlNormal, so I have set it inside my styles-v21 like:

```<code><item name="colorControlNormal">?android:textColorSecondary</item>
</code>```

and then in my style for EditText I have set

```<code><item name="android:textColorSecondary">@color/color_green</item>
</code>```

However this does not work, it works when I change it inside my style to

```<code><item name="colorControlNormal">@color/color_green</item>
</code>```

But thats not what I want.

答:
I know that the underline (of EditText) in Lollipop is styled by colorControlNormal

That's not true, it's controlled by colorAccent attribute.

Create your custom theme:

```<code><style name="MyCustomTheme" parent="AppTheme">
    <item name="colorAccent">#00FF00</item>
</style>
</code>```

And then apply this theme to your EditText in the xml:

```<code><EditText
    android:layout_width="matc_parent"
    android:layout_height="wrap_content"
    android:theme="@style/MyCustomTheme"/>
</code>```

You'll get this output:

Title: EditText underline color styling

Body:
I have a problem, I know that the underline in Lollipop is styled by colorControlNormal, so I have set it inside my styles-v21 like:

<item name="colorControlNormal">?android:textColorSecondary</item>

and then in my style for EditText I have set

<item name="android:textColorSecondary">@color/color_green</item>

However this does not work, it works when I change it inside my style to

<item name="colorControlNormal">@color/color_green</item>

But thats not what I want.

Body:
I know that the underline (of EditText) in Lollipop is styled by colorControlNormal

That's not true, it's controlled by colorAccent attribute.

Create your custom theme:

<style name="MyCustomTheme" parent="AppTheme">
    <item name="colorAccent">#00FF00</item>
</style>

And then apply this theme to your EditText in the xml:

<EditText
    android:layout_width="matc_parent"
    android:layout_height="wrap_content"
    android:theme="@style/MyCustomTheme"/>

You'll get this output:


问:
How to allow only numbers in textbox in mvc4 razor
I have 3 text box which takes values postal code & mobile number & residential number.
I got the solution for allowing only number in text box using jquery from Bellow post.

I would like to make an EditFor textbox accept numbers only

but can we do this using data annotations as I am using MVC4 razor ?

答:
```<code>function NumValidate(e) {
    var evt = (e) ? e : window.event;
    var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        alert('Only Number ');
        return false;
    }    return true;
}  function NumValidateWithDecimal(e) {

var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;

if (!(charCode == 8 || charCode == 46 || charCode == 110 || charCode == 13 || charCode == 9) && (charCode < 48 || charCode > 57)) {
    alert('Only Number With desimal e.g.: 0.0');
    return false;
}
else {
    return true;
} } function onlyAlphabets(e) {
try {
    if (window.event) {
        var charCode = window.event.keyCode;
    }
    else if (e) {
        var charCode = e.which;
    }
    else { return true; }

    if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode == 46) || (charCode == 32))
        return true;
    else
        alert("Only text And White Space And . Allow");
    return false;

}
catch (err) {
    alert(err.Description);
}} function checkAlphaNumeric(e) {

if (window.event) {
    var charCode = window.event.keyCode;
}
else if (e) {
    var charCode = e.which;
}
else { return true; }

if ((charCode >= 48 && charCode <= 57) || (charCode >= 65 && charCode <= 90) || (charCode == 32) || (charCode >= 97 && charCode <= 122)) {
    return true;
} else {
    alert('Only Text And Number');
    return false;
}}
</code>```


答:
Unfortunately, you cannot target a node's parent only by using css selectors. You would have to do so by using some Javascript or jQuery. Here are two examples of how to achieve what you want using both javascript and jQuery.

Here's how in javscript:

```<code>if (document.getElementById("admin") != null) { // if there is a node with "admin" as ID
    document.getElementById("maincontent").style.backgroundColor = "#000"; // changes the background to black
}
</code>```

Here's how in jQuery:

```<code>if ($("#admin").size() === 1) { // if there is a node with "admin" as ID
    $("#maincontent").css("background-color", "#000"); // changes the background to black
}
</code>```

Title: How to select the parent's parent in CSS?

Body:
Is it possible to have a rule that would match #maincontent only if #admin exists using just CSS?

It's just I have a background colour in the control panel but don't want it there for visitors.

Body:
Unfortunately, you cannot target a node's parent only by using css selectors. You would have to do so by using some Javascript or jQuery. Here are two examples of how to achieve what you want using both javascript and jQuery.

Here's how in javscript:

if (document.getElementById("admin") != null) { // if there is a node with "admin" as ID
    document.getElementById("maincontent").style.backgroundColor = "#000"; // changes the background to black
}

Here's how in jQuery:

if ($("#admin").size() === 1) { // if there is a node with "admin" as ID
    $("#maincontent").css("background-color", "#000"); // changes the background to black
}


问:
Cannot open OGR file
I have already tried re-writing this code using dsn=path.expand and shapefile. However, this keeps giving me an error.

```<code>mapfile <-readOGR("/Users/kajoribanerjee/Documents/PhD/bayesian geoadditive model/india_2011.shp")
</code>```

Error in ogrListLayers(dsn = dsn) : Cannot open data source}

答:
In rgdal you have to name a layer destination (dsn) and a layer name (layer).

In case of a shapefile located at /home/user/folder/shapefile.shp that would be dsn = "/home/user/folder" and layer = "shapefile"

So you should use it like this:

```<code>mapfile <- readOGR("/Users/kajoribanerjee/Documents/PhD/bayesian geoadditive model",
                   "india_2011")
</code>```

You should also have a look at ?readOGR where it is stated that:

If reading a shapefile, the data source name (dsn= argument) is the folder (directory) where the shapefile is, and the layer is the name of the shapefile (without the .shp extension)

Another way is shown here by using raster::shapefile.

Title: Cannot open OGR file

Body:
I have already tried re-writing this code using dsn=path.expand and shapefile. However, this keeps giving me an error.

mapfile <-readOGR("/Users/kajoribanerjee/Documents/PhD/bayesian geoadditive model/india_2011.shp")

Error in ogrListLayers(dsn = dsn) : Cannot open data source}

Body:
In rgdal you have to name a layer destination (dsn) and a layer name (layer).

In case of a shapefile located at /home/user/folder/shapefile.shp that would be dsn = "/home/user/folder" and layer = "shapefile"

So you should use it like this:

mapfile <- readOGR("/Users/kajoribanerjee/Documents/PhD/bayesian geoadditive model",
                   "india_2011")

You should also have a look at ?readOGR where it is stated that:

If reading a shapefile, the data source name (dsn= argument) is the folder (directory) where the shapefile is, and the layer is the name of the shapefile (without the .shp extension)

Another way is shown here by using raster::shapefile.


问:
Key value pairs in C# Params
I'm looking for a way to have a function such as:

```<code>myFunction({"Key", value}, {"Key2", value});
</code>```

I'm sure there's something with anonymous types that would be pretty easy, but I'm not seeing it.

The only solution I can think of is to have a params KeyValuePair<String, object>[] pairs parameter, but that ends up being something similar to:

```<code>myFunction(new KeyValuePair<String, object>("Key", value),
           new KeyValuePair<String, object>("Key2", value));
</code>```

Which is, admittedly, much uglier.

EDIT:

To clarify, I'm writing a Message class to pass between 2 different systems.  It contains a ushort specifying the the Message Type, and a dictionary of string to object for "Data" associated with the message.  I'd like to be able to pass all this information in the constructor, so I am able to do this:

```<code>Agent.SendMessage(new Message(MessageTypes.SomethingHappened, "A", x, "B", y, "C", z));
</code>```

or similar syntax.

答:
You could also reference the nugetpackage "valuetuple", which allows you to do the following:

```<code>public static void MyFunction(params ValueTuple<string, object>[] pairs)
{
    var pair = pairs[1];
    var stringValue = pair.item1;
    var objectValue = pair.item2;
}
</code>```

You can then call the method like this:

```<code>MyFunction(("string",object),("string", object));
</code>```

Title: Key value pairs in C# Params

Body:
I'm looking for a way to have a function such as:

myFunction({"Key", value}, {"Key2", value});

I'm sure there's something with anonymous types that would be pretty easy, but I'm not seeing it.

The only solution I can think of is to have a params KeyValuePair<String, object>[] pairs parameter, but that ends up being something similar to:

myFunction(new KeyValuePair<String, object>("Key", value),
           new KeyValuePair<String, object>("Key2", value));

Which is, admittedly, much uglier.

EDIT:

To clarify, I'm writing a Message class to pass between 2 different systems.  It contains a ushort specifying the the Message Type, and a dictionary of string to object for "Data" associated with the message.  I'd like to be able to pass all this information in the constructor, so I am able to do this:

Agent.SendMessage(new Message(MessageTypes.SomethingHappened, "A", x, "B", y, "C", z));

or similar syntax.

Body:
You could also reference the nugetpackage "valuetuple", which allows you to do the following:

public static void MyFunction(params ValueTuple<string, object>[] pairs)
{
    var pair = pairs[1];
    var stringValue = pair.item1;
    var objectValue = pair.item2;
}

You can then call the method like this:

MyFunction(("string",object),("string", object));


问:
Implement Gocardless webhook in Laravel
I was trying to implement a webhook in laravel.

I have created access token and created webhook endpoint also.

my webhook end point is like,https://www.example.com/gocardless.php

and my route is like,

```<code>Route::get('/gocardless.php',
'\App\Http\Controllers\gocardlessController@remote')->name('remote');
</code>```

Controller code like,

```<code>class gocardlessController extends Controller
 {

  public function remote(Request $request)
  {

 $token ="token";

 $raw_payload = file_get_contents('php://input');

 $headers = getallheaders();

 $provided_signature = $headers["Webhook-Signature"];
 $calculated_signature = hash_hmac("sha256",$raw_payload,$token);
 if ($provided_signature == $calculated_signature) {

  $payload = json_decode($raw_payload, true);
   }
   }
   }
</code>```

But when i clik on send test webhook in gocardless account,they are given "405 no method found" as responce.

How i can solve this?

答:
The HTTP 405 error you're seeing indicates that your Laravel application doesn't know how to handle the method of the incoming request.

GoCardless webhooks use the POST method to send you a request with a JSON body, but the route you've written is for handling a GET request (Route::get). To resolve this, you should define a route for POST requests to the endpoint which will receive webhooks.

Title: Implement Gocardless webhook in Laravel

Body:
I was trying to implement a webhook in laravel.

I have created access token and created webhook endpoint also.

my webhook end point is like,https://www.example.com/gocardless.php

and my route is like,

Route::get('/gocardless.php',
'\App\Http\Controllers\gocardlessController@remote')->name('remote');

Controller code like,

class gocardlessController extends Controller
 {

  public function remote(Request $request)
  {

 $token ="token";

 $raw_payload = file_get_contents('php://input');

 $headers = getallheaders();

 $provided_signature = $headers["Webhook-Signature"];
 $calculated_signature = hash_hmac("sha256",$raw_payload,$token);
 if ($provided_signature == $calculated_signature) {

  $payload = json_decode($raw_payload, true);
   }
   }
   }

But when i clik on send test webhook in gocardless account,they are given "405 no method found" as responce.

How i can solve this?


问:
Realm select row from 0 to 20
I have 100 elements in my database. I want to initially select the first 20 elements and show it in recyclerview. My goal is to increase this by 20 in the recyclerView load more event. I know how to catch load more events in recyclerView ,but I don't know how to increase select element from table in load more action.

I have written a function which can select all the elements:

```<code>    public void getTransactions(int start,int end)
{
    try {
        CoreApplication.realm = Realm.getDefaultInstance();
        CoreApplication.realm.executeTransaction(realm -> {
            final RealmResults<Transactions> transactions =
                    realm.where(Transactions.class).findAll();
            if (transactions != null && transactions.size() > 0) {
                for (int i = 0; i < transactions.size(); i++) {
                    Log.e("terminalTables", transactions.get(i).getAdditionalText());
                    Log.e("terminalTables", transactions.get(i).getId()+"");

                }
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (CoreApplication.realm!= null) {
            CoreApplication.realm.close();
        }
    }

}
</code>```

How I can rewrite my code to add two options in RealmResults? ( start and end)

答:
Here is a solution</p>

```<code>    public void getTransactions(int start, int end) {
    try {
        CoreApplication.realm = Realm.getDefaultInstance();
        CoreApplication.realm.executeTransaction(realm -> {
            final OrderedRealmCollection<Transactions> transactions =
                    realm.where(Transactions.class).between("id", start, start+end).findAll().createSnapshot();
            if (transactions != null && transactions.size() > 0) {
                for (int i = 0; i < transactions.size(); i++) {
                    Log.e("terminalTables", transactions.get(i).getAdditionalText());
                    Log.e("terminalTables", transactions.get(i).getId() + "");

                }
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (CoreApplication.realm != null) {
            CoreApplication.realm.close();
        }
    }

}
</code>```

Title: Realm select row from 0 to 20

Body:
I have 100 elements in my database. I want to initially select the first 20 elements and show it in recyclerview. My goal is to increase this by 20 in the recyclerView load more event. I know how to catch load more events in recyclerView ,but I don't know how to increase select element from table in load more action.

I have written a function which can select all the elements:

    public void getTransactions(int start,int end)
{
    try {
        CoreApplication.realm = Realm.getDefaultInstance();
        CoreApplication.realm.executeTransaction(realm -> {
            final RealmResults<Transactions> transactions =
                    realm.where(Transactions.class).findAll();
            if (transactions != null && transactions.size() > 0) {
                for (int i = 0; i < transactions.size(); i++) {
                    Log.e("terminalTables", transactions.get(i).getAdditionalText());
                    Log.e("terminalTables", transactions.get(i).getId()+"");

                }
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (CoreApplication.realm!= null) {
            CoreApplication.realm.close();
        }
    }

}

How I can rewrite my code to add two options in RealmResults? ( start and end)

Body:
Here is a solution

    public void getTransactions(int start, int end) {
    try {
        CoreApplication.realm = Realm.getDefaultInstance();
        CoreApplication.realm.executeTransaction(realm -> {
            final OrderedRealmCollection<Transactions> transactions =
                    realm.where(Transactions.class).between("id", start, start+end).findAll().createSnapshot();
            if (transactions != null && transactions.size() > 0) {
                for (int i = 0; i < transactions.size(); i++) {
                    Log.e("terminalTables", transactions.get(i).getAdditionalText());
                    Log.e("terminalTables", transactions.get(i).getId() + "");

                }
            }
        });

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (CoreApplication.realm != null) {
            CoreApplication.realm.close();
        }
    }

}


问:
IoT Hub Device Explorer SAS maximum TTL
In the Device Explorer for IoT Hub when generating the SAS token what is the maximum TTL that can be set?

I don't want to it ever expire in the best case scenario.

Inserting 0 doesn't help, when the connection is lost it never gets reconnected.

答:
Have a look at the Device Explorer implementation in the GitHub:

```<code> decimal ttlValue = numericUpDown1.Value;
 var sasBuilder = new SharedAccessSignatureBuilder()
 {
      Key = this.selectedDeviceKey,
      Target = String.Format("{0}/devices/{1}", iotHubHostName, WebUtility.UrlEncode(this.selectedDeviceId)),
      TimeToLive = TimeSpan.FromDays(Convert.ToDouble(ttlValue))
 };
 sasRichTextBox.Text = deviceConnectionStringWithSAS(sasBuilder.ToSignature()) + "\r\n";
</code>```

Title: IoT Hub Device Explorer SAS maximum TTL

Body:
Have a look at the Device Explorer implementation in the GitHub:

 decimal ttlValue = numericUpDown1.Value;
 var sasBuilder = new SharedAccessSignatureBuilder()
 {
      Key = this.selectedDeviceKey,
      Target = String.Format("{0}/devices/{1}", iotHubHostName, WebUtility.UrlEncode(this.selectedDeviceId)),
      TimeToLive = TimeSpan.FromDays(Convert.ToDouble(ttlValue))
 };
 sasRichTextBox.Text = deviceConnectionStringWithSAS(sasBuilder.ToSignature()) + "\r\n";


问:
How can I copy an image contained in a mat, on a bigger mat?
I'm trying to copy a smaller image, contained in a Mat, inside another larger image, contained in another mat.

The next code is the original mat.

```<code>cv::Mat mat(image.height(),image.width()+750,
            CV_8UC3,image.bits(), image.bytesPerLine());
</code>```

and that is the matter what i want to copy in the previous mat:

```<code>QImage your_image;
your_image.load(":/Sombrero.png");

your_image = your_image.convertToFormat(
    QImage::Format_RGBA8888, Qt::ThresholdDither|Qt::AutoColor);

cv::Mat mat_im(your_image.height(),your_image.width(),CV_8UC3,your_image.bits(),
               your_image.bytesPerLine());
</code>```

As you can see, change the format of the image so that it has the same as the image stored in the original, but it is not working.

This question is different because i dont want to put an image over a regular image, like in other questions,i want to put a mat of a image over another mat image....

答:
You can use

Mat(Rect) to specify a ROI and copy them. Like

```<code>Mat big, small;
cv::Rect rect;

small.copyTo(big(Rect));
</code>```

The big and small mat has to be initialised. The Rect has to be the width and height of the small mat, x and y are the origin in the big mat.

You have to check the size of the mat (if the smaller one fit in the big at the origin) and the mats should have the same bit depth.

Edit:
Full example

```<code>QImage src;
src.load(":/Sombrero.png"); // load to QImage

src = src.convertToFormat(QImage::Format::Format_RGB888); //convert to get sure the format
cv::Mat small(src.height(), src.width(), CV_8UC3, src.scanLine(0)); // convert the QImage to Mat

cv::Mat big(small.rows + 10, small.cols + 10, small.type(), cv::Scalar(0, 0, 0)); // generate a (10,10)px bigger mat
small.copyTo(big(cv::Rect(5, 5, small.cols, small.rows))); // copy the small to the big, you get a 5px black boarder

QImage result = QImage(big.data, big.cols, big.rows, 3 * big.cols, QImage::Format_RGB888); // if you want it back as QImage (3 is the count of channels)
</code>```

Body:
I'm trying to copy a smaller image, contained in a Mat, inside another larger image, contained in another mat.

The next code is the original mat.

cv::Mat mat(image.height(),image.width()+750,
            CV_8UC3,image.bits(), image.bytesPerLine());

and that is the matter what i want to copy in the previous mat:

QImage your_image;
your_image.load(":/Sombrero.png");

your_image = your_image.convertToFormat(
    QImage::Format_RGBA8888, Qt::ThresholdDither|Qt::AutoColor);

cv::Mat mat_im(your_image.height(),your_image.width(),CV_8UC3,your_image.bits(),
               your_image.bytesPerLine());

As you can see, change the format of the image so that it has the same as the image stored in the original, but it is not working.

This question is different because i dont want to put an image over a regular image, like in other questions,i want to put a mat of a image over another mat image....

Body:
You can use

Mat(Rect) to specify a ROI and copy them. Like

Mat big, small;
cv::Rect rect;

small.copyTo(big(Rect));

The big and small mat has to be initialised. The Rect has to be the width and height of the small mat, x and y are the origin in the big mat.

You have to check the size of the mat (if the smaller one fit in the big at the origin) and the mats should have the same bit depth.

Edit:
Full example

QImage src;
src.load(":/Sombrero.png"); // load to QImage

src = src.convertToFormat(QImage::Format::Format_RGB888); //convert to get sure the format
cv::Mat small(src.height(), src.width(), CV_8UC3, src.scanLine(0)); // convert the QImage to Mat

cv::Mat big(small.rows + 10, small.cols + 10, small.type(), cv::Scalar(0, 0, 0)); // generate a (10,10)px bigger mat
small.copyTo(big(cv::Rect(5, 5, small.cols, small.rows))); // copy the small to the big, you get a 5px black boarder

QImage result = QImage(big.data, big.cols, big.rows, 3 * big.cols, QImage::Format_RGB888); // if you want it back as QImage (3 is the count of channels)


问:
return array from trait function in laravel
i have a problem , an
error when  return array or  variable from function..
here is my code:

in Traits\UserTrait.php

```<code> public function login()
             {
               $errors   = new MessageBag; // initiate MessageBag
               $username = Input::get('email');
               $password = Input::get('password');
              return compact('username', 'password','email');
             }
</code>```

and
in UserController.php

```<code>       public function __construct(user $model)
        {
         $this->model=$model;

        }
       public function login()
        {
            $this->model->login();
          if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
            $user = User::where('email',$request['email'])->first();
            if($user && $user->email_active != 1)
            {
                $errors = new MessageBag(['email' => [__('auth.emailVerify')]]);
                return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
            }
}
}
</code>```

actually in user model, i put  use UserTrait;

答:
This is not how traits work, they do no magically fill variables that are missing.
On the line

```<code>if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
</code>```

Your are using $username, which is not set.

Body:
i have a problem , an
error when  return array or  variable from function..
here is my code:

in Traits\UserTrait.php

 public function login()
             {
               $errors   = new MessageBag; // initiate MessageBag
               $username = Input::get('email');
               $password = Input::get('password');
              return compact('username', 'password','email');
             }

and
in UserController.php

       public function __construct(user $model)
        {
         $this->model=$model;

        }
       public function login()
        {
            $this->model->login();
          if(filter_var($username, FILTER_VALIDATE_EMAIL)) {
            $user = User::where('email',$request['email'])->first();
            if($user && $user->email_active != 1)
            {
                $errors = new MessageBag(['email' => [__('auth.emailVerify')]]);
                return Redirect::back()->withErrors($errors)->withInput(Input::except('password'));
            }
}
}

actually in user model, i put  use UserTrait;

Body:
This is not how traits work, they do no magically fill variables that are missing.
On the line

if(filter_var($username, FILTER_VALIDATE_EMAIL)) {

Your are using $username, which is not set.


问:
Navigation drawer without AppCompat theme
I am trying to setup navigation drawer "without" AppCompat. I am getting an error You need to use a Theme.AppCompat theme (or descendant) with the design library
Any ideas?

I setup my `styles.xml as:

```<code><resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="@android:style/Theme.Material.Light">
        <!-- Customize your theme here. -->
    </style>
</resources>
</code>```

and in my AndroidManifest.xml file I have the android:theme="@style/AppTheme" only.

My activity_main.xml has:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />

    </RelativeLayout>
    <!-- The navigation drawer -->
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
</code>```

nav_header_main and activity_main drawer contents are same as from android studio examples and my MainActivity onCreate function is pretty straightforward:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
</code>```

My build.bradle dependencies are:

```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:support-v13:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

The error is:

```<code>12-08 15:11:19.095 16936-16936/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.xxx.xxx, PID: 16936
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.xxx/com.xxx.xxx.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                    Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                    Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                    Caused by: java.lang.reflect.InvocationTargetException
                                                       at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                       at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                                                       at android.view.LayoutInflater.createView(LayoutInflater.java:645)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                       at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
                                                       at android.app.Activity.setContentView(Activity.java:2415)
                                                       at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:24)
                                                       at android.app.Activity.performCreate(Activity.java:6684)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                    Caused by: java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
                                                       at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:33)
                                                       at android.support.design.widget.NavigationView.<init>(NavigationView.java:104)
                                                       at android.support.design.widget.NavigationView.<init>(NavigationView.java:98)
                                                       at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                       at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                                                       at android.view.LayoutInflater.createView(LayoutInflater.java:645)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                       at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
                                                       at android.app.Activity.setContentView(Activity.java:2415)
                                                       at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:24)
                                                       at android.app.Activity.performCreate(Activity.java:6684)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code>```

答:
```<code>implementation 'com.android.support:design:26.1.0'
</code>```

Anything you pull in from this artifact will require appcompat-v7, Theme.AppCompat, etc. In your case, NavigationView is from this library.

I do not have NavigationView in my cross-port of the Design widgets to Theme.Material. AFAIK, you will need to drop this widget and use something else for the drawer contents (e.g., RecyclerView).

Note that DrawerLayout does not require appcompat-v7, so that part is fine.

Body:
I am trying to setup navigation drawer "without" AppCompat. I am getting an error You need to use a Theme.AppCompat theme (or descendant) with the design library
Any ideas?

I setup my `styles.xml as:

<resources>

</resources>

and in my AndroidManifest.xml file I have the android:theme="@style/AppTheme" only.

My activity_main.xml has:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!" />

    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

nav_header_main and activity_main drawer contents are same as from android studio examples and my MainActivity onCreate function is pretty straightforward:

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

My build.bradle dependencies are:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:support-v13:26.1.0'
    implementation 'com.android.support:design:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

The error is:

12-08 15:11:19.095 16936-16936/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.xxx.xxx, PID: 16936
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.xxx/com.xxx.xxx.MainActivity}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2684)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                    Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                    Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
                                                    Caused by: java.lang.reflect.InvocationTargetException
                                                       at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                       at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                                                       at android.view.LayoutInflater.createView(LayoutInflater.java:645)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                       at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
                                                       at android.app.Activity.setContentView(Activity.java:2415)
                                                       at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:24)
                                                       at android.app.Activity.performCreate(Activity.java:6684)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                    Caused by: java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library.
                                                       at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:33)
                                                       at android.support.design.widget.NavigationView.<init>(NavigationView.java:104)
                                                       at android.support.design.widget.NavigationView.<init>(NavigationView.java:98)
                                                       at java.lang.reflect.Constructor.newInstance0(Native Method)
                                                       at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
                                                       at android.view.LayoutInflater.createView(LayoutInflater.java:645)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                       at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                       at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
                                                       at android.app.Activity.setContentView(Activity.java:2415)
                                                       at com.xxx.xxx.MainActivity.onCreate(MainActivity.java:24)
                                                       at android.app.Activity.performCreate(Activity.java:6684)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2637)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2751)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6186)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Body:
implementation 'com.android.support:design:26.1.0'

Anything you pull in from this artifact will require appcompat-v7, Theme.AppCompat, etc. In your case, NavigationView is from this library.

I do not have NavigationView in my cross-port of the Design widgets to Theme.Material. AFAIK, you will need to drop this widget and use something else for the drawer contents (e.g., RecyclerView).

Note that DrawerLayout does not require appcompat-v7, so that part is fine.