问:
Error in publishing the configuration in Eclipse
Publishing to tomcat v6.0 server at localhost..'has encountered a problem.

Publishing the configuration..

tomcat give above error. How to resolve above error. I googled alot but have not found any solution. please help me.

```<code>Publishing the configuration...

Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\catalina.policy: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\catalina.policy (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\catalina.policy (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\catalina.properties: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\catalina.properties (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\catalina.properties (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\context.xml: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\context.xml (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\context.xml (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\server.xml: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\server.xml (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\server.xml (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\tomcat-users.xml: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\tomcat-users.xml (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\tomcat-users.xml (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\web.xml: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\web.xml (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\web.xml (The system cannot find the path specified)
</code>```

答:
Option 1:

Create a backup directory and wtpwebapps(Optional) directory in
Tomcat installation folder.

And make sure the parent folder "C:\Program Files\Apache Software
Foundation" has the full control rights for all users.

You can set the rights by right clicking on the folder and go under 'Security' tab.

Option 2:

Do a fresh Tomcat install to a separate directory or folder or
simply just copy everything from the tomcat installation directory
to a different directory.

Now modify the Runtime for Apache Tomcat to point to the new
location.

I'm not sure about the root cause of this issue but the above approach seems to be a workaround.

Body:
Publishing to tomcat v6.0 server at localhost..'has encountered a problem.

Publishing the configuration..

tomcat give above error. How to resolve above error. I googled alot but have not found any solution. please help me.

Publishing the configuration...

Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\catalina.policy: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\catalina.policy (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\catalina.policy (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\catalina.properties: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\catalina.properties (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\catalina.properties (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\context.xml: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\context.xml (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\context.xml (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\server.xml: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\server.xml (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\server.xml (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\tomcat-users.xml: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\tomcat-users.xml (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\tomcat-users.xml (The system cannot find the path specified)
Error copying file to C:/Program Files/Apache Software Foundation/Tomcat 6.0/backup\web.xml: C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\web.xml (The system cannot find the path specified)
C:\Program Files\Apache Software Foundation\Tomcat 6.0\backup\web.xml (The system cannot find the path specified)


来源: stackexchange

问:
running sh script on travis CI: The command exited with 1
I am running an sh script as part of my .travis.yml. It is giving me the error below although the shell script does not fail.

The command exited with 1.

I tried running the with bash -x to debug and there are no errors.
The problem is that travis thinks that the build failed although it passed.

答:
This change fixes it.

As explained in the man bash page:

Shell builtin commands return a status of 0 (true) if successful, and
  non-zero (false) if an error
         occurs while they execute.  All builtins return an exit status of 2 to indicate incorrect usage.

Bash  itself returns the exit status of the last command executed,
  unless a syntax error occurs, in which case it exits with a non-zero
  value.  See also the exit builtin command below.

The last command executed is:

```<code>[ "$BUILD_CHROMIUM" == 1 ] &&_build_chromium_crx "${zip_file}" "${BUILD_METADATA[${CHROMIUM_TARGET}]}"
</code>```

And it is evaluated as false with exit status 1:

```<code>'[' 0 == 1 ']'
</code>```

So adding || true at the end of this line fixes it. The exit status will always be 0.

Alternatively, use the fix that better suits the expected behavior of your code like exit 0, etc.

As explained here and here:

exit [n] Cause the shell to exit with a status of n. If n is omitted,
  the exit status is that of the last command executed. A trap on EXIT
  is executed before the shell terminates.

So your clean function trap _clean_chrome EXIT is not the last to be executed.

Further information about exit status here.

ContentLicense: CC BY-SA 3.0

Body:
This change fixes it.

As explained in the man bash page:

Shell builtin commands return a status of 0 (true) if successful, and
  non-zero (false) if an error
         occurs while they execute.  All builtins return an exit status of 2 to indicate incorrect usage.

Bash  itself returns the exit status of the last command executed,
  unless a syntax error occurs, in which case it exits with a non-zero
  value.  See also the exit builtin command below.

The last command executed is:

[ "$BUILD_CHROMIUM" == 1 ] &&_build_chromium_crx "${zip_file}" "${BUILD_METADATA[${CHROMIUM_TARGET}]}"

And it is evaluated as false with exit status 1:

'[' 0 == 1 ']'

So adding || true at the end of this line fixes it. The exit status will always be 0.

Alternatively, use the fix that better suits the expected behavior of your code like exit 0, etc.

As explained here and here:

exit [n] Cause the shell to exit with a status of n. If n is omitted,
  the exit status is that of the last command executed. A trap on EXIT
  is executed before the shell terminates.

So your clean function trap _clean_chrome EXIT is not the last to be executed.

Further information about exit status here.


问:
My HTML code is not being read on Javascript/JSON
So I'm doing a quote generator in Javascript in which the quote generates on click.

The code looks like this:

```<code>$("#getQuote").on("click", function(){
var i = Math.floor((Math.random() * quote.length));

   $("#theQuote").html(quote[i] <\br> person[i]);
});
</code>```

I'm trying to make a line break between the quote and the person who made the quote but it doesn't seem the recognize any code after quote[i].

I've also tried adding \n to the strings in my array for example:

```<code>var quote = ['"With great power, comes great responsibility." \n- Uncle Ben'];
</code>```

but somehow \n is not read whereas the rest of the quote is.

答:
Change <\br> to
 or
. This is according to the HTML5 standards.

Body:
So I'm doing a quote generator in Javascript in which the quote generates on click.

The code looks like this:

$("#getQuote").on("click", function(){
var i = Math.floor((Math.random() * quote.length));

   $("#theQuote").html(quote[i] <\br> person[i]);
});

I'm trying to make a line break between the quote and the person who made the quote but it doesn't seem the recognize any code after quote[i].

I've also tried adding \n to the strings in my array for example:

var quote = ['"With great power, comes great responsibility." \n- Uncle Ben'];

but somehow \n is not read whereas the rest of the quote is.

Body: Change <\br> to <br> or <br />. This is according to the HTML5 standards.


问:
How to put up and down arrow just above dots in the slideshow of forms?
I am working on making a slideshow of forms. Here is my working codepen link. As you can see I have two dots on the right side which if I click then it opens another form. Now I want to put an up arrow just above those dots and down arrow just below those dots.

For example as shown in this image. I am trying to replicate exactly like this image and as you can see there is a up arrow just above those dots and down arrow just below those dots and they are perfectly aligned in one vertical line and  also their color is orange I believe. I want to do exactly like that. How can I achieve this? I am already using font-awesome css in my actual code, do I have to use that here?

Below is my HTML code:

```<code><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <!-- SlidesJS Required (if responsive): Sets the page width to the device width. -->
  <meta name="viewport" content="width=device-width">
  <!-- End SlidesJS Required -->

  <!-- CSS for slidesjs.com example -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <!-- End CSS for slidesjs.com example -->

  <!-- SlidesJS Optional: If you'd like to use this design -->
  <style>
    body {
      -webkit-font-smoothing: antialiased;
      font: normal 15px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
      color: #232525;
    }

    #slides,
    #slides2,
    #slides3 {
      display: none;
      margin-bottom:50px;
    }

    .slidesjs-navigation {
      margin-top:3px;
    }

    .slidesjs-previous {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-next {
      margin-right: 5px;
      float: left;
    }

    .slidesjs-pagination {
      margin: 6px 0 0;
      float: right;
      list-style: none;
    }

    .slidesjs-pagination li {
      float: left;
      margin: 0 1px;
    }

    .slidesjs-pagination li a {
      display: block;
      width: 13px;
      height: 0;
      padding-top: 13px;
      background-image: url("https://s16.postimg.org/pt4k43i9x/pagination.png");
      background-position: 0 0;
      float: left;
      overflow: hidden;
    }

    .slidesjs-pagination li a.active,
    .slidesjs-pagination li a:hover.active {
      background-position: 0 -13px
    }

    .slidesjs-pagination li a:hover {
      background-position: 0 -26px
    }
    .navbar {
      overflow: hidden
    }
  </style>
  <!-- End SlidesJS Optional-->

  <!-- SlidesJS Required: These styles are required if you'd like a responsive slideshow -->
  <style>
    #slides {
      display: none
    }

    .container {
      margin: 0 auto
    }

    /* For tablets & smart phones */
    @media (max-width: 767px) {
      body {
        padding-left: 20px;
        padding-right: 20px;
      }
      .container {
        width: auto
      }
    }

    /* For smartphones */
    @media (max-width: 480px) {
      .container {
        width: auto
      }
    }

    /* For smaller displays like laptops */
    @media (min-width: 768px) and (max-width: 979px) {
      .container {
        width: 724px
      }
    }

    /* For larger displays */
    @media (min-width: 1200px) {
      .container {
        width: 1170px
      }
    }
  </style>
  <!-- SlidesJS Required: -->
</head>
<body>
<div class="topnav">
   <img src="https://s4.postimg.org/ojd13poal/northman_wordmark_CMYK.png">
   <nav>
      <ul>
         <li class="dropdown">
            <a href="#"><b>INSURANCE</b> <i class="fa fa-angle-down"></i></a>
            <ul class="dropdown-content">
               <li><a href="#"><i>INDIVIDUAL</i></a>
               </li>
               <li><a href="#"><i>CORPORATE</i></a>
               </li>
            </ul>
         </li>
         <li class="our-story">OUR STORY</li>
         <li class="login-signup">Log In | Sign up</li>
         <li class="get-covered">GET <strong style="font-style:italic">COVERED</strong>
         </li>
      </ul>
   </nav>
</div>
  <!-- SlidesJS Required: Start Slides -->
  <!-- The container is used to define the width of the slideshow -->
  <div class="container">
   <h3>INSURANCE FORM</h3>
   <h4><i>BASIC DETAILS</i></h4>
   <br>
    <div id="slides" class="container-fluid" >
  <form action="/action_page.php" class="form-horizontal">
      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 1">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>
   </form>
  <form action="/action_page.php" class="form-horizontal">
      <div class="form-group">
         <div class="col-sm-6">
            <label>FIRST NAME</label>
            <input type="text" class="form-control" name="fname" value="Mickey 2">
         </div>
         <div class="col-sm-6">
            <label>LAST NAME</label>
            <input type="text" class="form-control" name="lname" value="Mouse">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>EMAIL</label>
            <input type="text" class="form-control" name="email" value="abc@host.com">
         </div>
         <div class="col-sm-6">
            <label>PHONE NUMBER</label>
            <input type="text" class="form-control" name="number" value="123-456-789">
         </div>
      </div>
      <div class="form-group">
         <div class="col-sm-6">
            <label>COUNTRY</label>
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>PROVINCE</label>
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>
         </div>
         <div class="col-sm-3">
            <label>CITY</label>
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>
         </div>
      </div>
   </form>
            <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left"></i></a>
      <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right"></i></a>
    </div>
  </div>
    <!-- End SlidesJS Required: Start Slides -->

  <!-- SlidesJS Required: Link to jQuery -->
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Link to jquery.slides.js -->
  <script src="js/jquery.slides.min.js"></script>
  <!-- End SlidesJS Required -->

  <!-- SlidesJS Required: Initialize SlidesJS with a jQuery doc ready -->
  <script>
    $(function() {
      $('#slides').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });

      /*
        To have multiple slideshows on the same page
        they just need to have separate IDs
      */
      $('#slides2').slidesjs({
        width: 800,
        height: 528,
        navigation: false,
        start: 3,
        play: {
          auto: true
        }
      });

      $('#slides3').slidesjs({
        width: 800,
        height: 528,
        navigation: false
      });
    });
  </script>
  <!-- End SlidesJS Required -->
</body>
</html>
</code>```

答:
Make use of these elements

```<code><a href="#" class="slidesjs-previous slidesjs-navigation">
   <i class="icon-chevron-left"></i>
</a>
<a href="#" class="slidesjs-next slidesjs-navigation">
   <i class="icon-chevron-right"></i>
</a>
</code>```

position these elements absolute align them to right.

https://codepen.io/chandrashekhar/pen/weaxqj?editors=1100

visit the codepen link here

Body:
I am working on making a slideshow of forms. Here is my working codepen link. As you can see I have two dots on the right side which if I click then it opens another form. Now I want to put an up arrow just above those dots and down arrow just below those dots.

For example as shown in this image. I am trying to replicate exactly like this image and as you can see there is a up arrow just above those dots and down arrow just below those dots and they are perfectly aligned in one vertical line and  also their color is orange I believe. I want to do exactly like that. How can I achieve this? I am already using font-awesome css in my actual code, do I have to use that here?

Below is my HTML code:

<!doctype html>

  <meta charset="utf-8">
  <title>SlidesJS Standard Code Example</title>
  <meta name="description" content="SlidesJS is a simple slideshow plugin for jQuery. Packed with a useful set of features to help novice and advanced developers alike create elegant and user-friendly slideshows.">
  <meta name="author" content="Nathan Searles">

  <meta name="viewport" content="width=device-width">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

            INSURANCE

INDIVIDUAL

CORPORATE

OUR STORY

Log In | Sign up

GET COVERED

INSURANCE FORM

BASIC DETAILS

  <form action="/action_page.php" class="form-horizontal">

            FIRST NAME
            <input type="text" class="form-control" name="fname" value="Mickey 1">

            LAST NAME
            <input type="text" class="form-control" name="lname" value="Mouse">

            EMAIL
            <input type="text" class="form-control" name="email" value="abc@host.com">

            PHONE NUMBER
            <input type="text" class="form-control" name="number" value="123-456-789">

            COUNTRY
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>

            PROVINCE
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>

            CITY
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>

   </form>
  <form action="/action_page.php" class="form-horizontal">

            FIRST NAME
            <input type="text" class="form-control" name="fname" value="Mickey 2">

            LAST NAME
            <input type="text" class="form-control" name="lname" value="Mouse">

            EMAIL
            <input type="text" class="form-control" name="email" value="abc@host.com">

            PHONE NUMBER
            <input type="text" class="form-control" name="number" value="123-456-789">

            COUNTRY
            <select name="country" class="form-control">
               <option value="canada">Canada</option>
            </select>

            PROVINCE
            <select name="province" class="form-control">
               <option value="ontario">ONTARIO</option>
            </select>

            CITY
            <select name="city" class="form-control">
               <option value="ottawa">OTTAWA</option>
            </select>

   </form>

Body:
Make use of these elements

<a href="#" class="slidesjs-previous slidesjs-navigation">
   <i class="icon-chevron-left"></i>
</a>
<a href="#" class="slidesjs-next slidesjs-navigation">
   <i class="icon-chevron-right"></i>
</a>

position these elements absolute align them to right.

https://codepen.io/chandrashekhar/pen/weaxqj?editors=1100

visit the codepen link here


问:
Usage of class in 'typing' the variable (vs interface) and 'modelling' (for Typescript Angular 2 project)
Let say I have a model class

```<code>class User {
    name: string;
    email: string;
}
</code>```

and a service related to user

```<code>class UserService {
    getInfo (usr: User) {
        console.log(usr);
    }
}
</code>```

The usr: User is an input parameter for getInfo method, and no User class is created for that statement since the User just "typing" the usr. Instead, we can replace it with interface, isn't it?

Yeah, I am aware of Angular 2 official guide that suggest try to use class instead of interface

quote: "Consider using a class instead of an interface"

and I can accept it, although it is weird.

My question is, WHY WHY WHY use a class to "type" a variable, since we don't create any instance from it? We can replace the UserService class as shown below, and it works too...

```<code>class UserService {
    getInfo (usr: any) { //this work too
        console.log(usr);
    }
}
</code>```

(please correct me if I am wrong)

[#1] This will create a property that have the class content

```<code>class UserService {
    usr: User = User; //usr = { name: '', email: ''}
}
</code>```

[#2] This is used by Angular 2 to do dependency injection (assuming I have listed the User as provider), and in this case, it is similar to #1 as we are just copy the User to usr. (usually, we do DI on service, instead of model, since injecting model will have the same effect as "assigning" it to a variable, am I correct?)

```<code>class UserService {
    constructor (private usr: User) {}
}
</code>```

[#3] And this confuse me... because why we still do it since we don't need it? (because nothing is created, no usage here)

```<code>class UserService {
    usr: User; //usr: any; (?)
}
class UserMoreService {
    getInfo (usr: User) {console.log(usr);} //usr: any (?)
}
</code>```

Lastly, may I know what is the motivation behind to create a "model" class in Angular 2 project?

We have the component to display data, and to get the data, we can ask it from related service, and the service will get it from the server.

Can you see this? we don't need a "third party" model to "hold" the data, because everything can be done without declaring a "model" class. Can please tell me when to create a "model"? I don't see any reason to create that...

答:
It is not a must but just a suggestion.

Why?

An interface-class can be a provider lookup token in Angular dependency injection.

Source: https://angular.io/styleguide#!#03-03

Creating a class is pretty much the same work with respect to creating an interface but you can use these classes as a class-interface in your provider tokens later on.

```<code>{ provide: MinimalLogger, useExisting: LoggerService },
</code>```

This can be used as a type of inheritance among Angular providers.

```<code>export abstract class MinimalLogger {
  logs: string[];
  logInfo: (msg: string) => void;
}
</code>```

When you use a class this way, it's called a class-interface. The key benefit of a class-interface is that you can get the strong-typing of an interface and you can use it as a provider token in the way you would a normal class.

Source: https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#class-interface

Side note: If you're sure that you aren't going to use it as a provider token or so IMO you should be using an interface since they disappear after the code is transpiled to JavaScript. Hence, they don't use your memory.

Using a class as an interface gives you the characteristics of an interface in a real JavaScript object.

Of course a real object occupies memory. To minimize memory cost, the class should have no implementation

Body:
Let say I have a model class

class User {
    name: string;
    email: string;
}

and a service related to user

class UserService {
    getInfo (usr: User) {
        console.log(usr);
    }
}

The usr: User is an input parameter for getInfo method, and no User class is created for that statement since the User just "typing" the usr. Instead, we can replace it with interface, isn't it?

Yeah, I am aware of Angular 2 official guide that suggest try to use class instead of interface

quote: "Consider using a class instead of an interface"

and I can accept it, although it is weird.

My question is, WHY WHY WHY use a class to "type" a variable, since we don't create any instance from it? We can replace the UserService class as shown below, and it works too...

class UserService {
    getInfo (usr: any) { //this work too
        console.log(usr);
    }
}

(please correct me if I am wrong)

[#1] This will create a property that have the class content

class UserService {
    usr: User = User; //usr = { name: '', email: ''}
}

[#2] This is used by Angular 2 to do dependency injection (assuming I have listed the User as provider), and in this case, it is similar to #1 as we are just copy the User to usr. (usually, we do DI on service, instead of model, since injecting model will have the same effect as "assigning" it to a variable, am I correct?)

class UserService {
    constructor (private usr: User) {}
}

[#3] And this confuse me... because why we still do it since we don't need it? (because nothing is created, no usage here)

class UserService {
    usr: User; //usr: any; (?)
}
class UserMoreService {
    getInfo (usr: User) {console.log(usr);} //usr: any (?)
}

Lastly, may I know what is the motivation behind to create a "model" class in Angular 2 project?

We have the component to display data, and to get the data, we can ask it from related service, and the service will get it from the server.

Can you see this? we don't need a "third party" model to "hold" the data, because everything can be done without declaring a "model" class. Can please tell me when to create a "model"? I don't see any reason to create that...

Body:
It is not a must but just a suggestion.

Why?

An interface-class can be a provider lookup token in Angular dependency injection.

Source: https://angular.io/styleguide#!#03-03

Creating a class is pretty much the same work with respect to creating an interface but you can use these classes as a class-interface in your provider tokens later on.

{ provide: MinimalLogger, useExisting: LoggerService },

This can be used as a type of inheritance among Angular providers.

export abstract class MinimalLogger {
  logs: string[];
  logInfo: (msg: string) => void;
}

When you use a class this way, it's called a class-interface. The key benefit of a class-interface is that you can get the strong-typing of an interface and you can use it as a provider token in the way you would a normal class.

Source: https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#class-interface

Side note: If you're sure that you aren't going to use it as a provider token or so IMO you should be using an interface since they disappear after the code is transpiled to JavaScript. Hence, they don't use your memory.

Using a class as an interface gives you the characteristics of an interface in a real JavaScript object.

Of course a real object occupies memory. To minimize memory cost, the class should have no implementation


问:
Deep learning using Caffe - Python
I am studying deep learning and trying to implement it using CAFFE- Python. can anybody tell that how we can assign the weights to each node in input layer instead of using weight filler in caffe? </p>

答:
There is a fundamental difference between weights and input data: the training data is used to learn the weights (aka "trainable parameters") during training. Once the net is trained, the training data is no longer needed while the weights are kept as part of the model to be used for testing/deployment.

Make sure this difference is clear to you before you precede.

Layers with trainable parameters has a filler to set the weights initially.

On the other hand, an input data layer does not have trainable parameters, but it should supply the net with input data. Thus, input layers has no filler.

Based on the type of input layer you use, you will need to prepare your training data.

Title: Deep learning using Caffe - Python


问:
can I not change partition when I use window with spark/scala?
I have a RDD , the RDD'partition of result changes to 1 when I use window,can I not change partition when I use window?
this is my code:

```<code> val rdd=sc.parallelize(List(1,3,2,4,5,6,7,8),4)
    val sqlContext = new SQLContext(m_sparkCtx)
    import sqlContext.implicits._
    val result = rdd.toDF("values").withColumn("csum", sum(col("values")).over(Window.orderBy("values"))).rdd
    println(result.getNumPartitions+"rdd2")
</code>```

My input'partition is 4,I want my result'partition is alse 4,is there any cleaner solution?

答:
The partitions of the RDD is 1 as expected this is because your are performing a Window function on a DataFrame without a partitionBy clause. So all the data has to be grouped into a single partition in this case.

When we include a partitionBy clause in our Window function then the number of partitions in the result RDD is no longer 1 as shown below. In the below example we have included an-another column in called col1 in the original dataframe and the same window function is applied with a partitionBy clause on col1 column.

```<code>scala> import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.expressions.Window

scala> val rdd = spark.sparkContext.parallelize(List((1,1),(3,1),(2,2),(4,2),(5,2),(6,3),(7,3),(8,3)),4)
rdd: org.apache.spark.rdd.RDD[(Int, Int)] = ParallelCollectionRDD[49] at parallelize at <console>:28

scala> val result = rdd.toDF("values", "col1").withColumn("csum", sum(col("values")).over(Window.partitionBy("col1").orderBy("values"))).rdd
result: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row] = MapPartitionsRDD[58] at rdd at <console>:30

scala> result.getNumPartitions
res6: Int = 200
</code>```

Body:
I have a RDD , the RDD'partition of result changes to 1 when I use window,can I not change partition when I use window?
this is my code:

 val rdd=sc.parallelize(List(1,3,2,4,5,6,7,8),4)
    val sqlContext = new SQLContext(m_sparkCtx)
    import sqlContext.implicits._
    val result = rdd.toDF("values").withColumn("csum", sum(col("values")).over(Window.orderBy("values"))).rdd
    println(result.getNumPartitions+"rdd2")

My input'partition is 4,I want my result'partition is alse 4,is there any cleaner solution?

Body:
The partitions of the RDD is 1 as expected this is because your are performing a Window function on a DataFrame without a partitionBy clause. So all the data has to be grouped into a single partition in this case.

When we include a partitionBy clause in our Window function then the number of partitions in the result RDD is no longer 1 as shown below. In the below example we have included an-another column in called col1 in the original dataframe and the same window function is applied with a partitionBy clause on col1 column.

scala> import org.apache.spark.sql.expressions.Window
import org.apache.spark.sql.expressions.Window

scala> val rdd = spark.sparkContext.parallelize(List((1,1),(3,1),(2,2),(4,2),(5,2),(6,3),(7,3),(8,3)),4)
rdd: org.apache.spark.rdd.RDD[(Int, Int)] = ParallelCollectionRDD[49] at parallelize at <console>:28

scala> val result = rdd.toDF("values", "col1").withColumn("csum", sum(col("values")).over(Window.partitionBy("col1").orderBy("values"))).rdd
result: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row] = MapPartitionsRDD[58] at rdd at <console>:30

scala> result.getNumPartitions
res6: Int = 200


问:
Can I concat a string and a variable to select a DOM element in JavaScript?
I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.

I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.

```<code>var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');

for(var i=0;i<4;i++){
 console.log(copy+i);
 console.log("copy"+i);
};
</code>```

Ideally I would be able to select an element and style that via javascript.

Much appreciated

Thanks All.

Moe

答:
Since nobody has addressed your "certain number of characters" requirement yet, I thought I would.

You could always use jQuery or write your own $ method, which works as a document.getElementById() wrapper function.

Here is a jsfiddle to see it in action.

HTML

```<code><div id="copy1">01234</div>
<div id="copy2">012345678</div>
<div id="copy3">0123456789 0123456789</div>
</code>```

JavaScript

```<code>// Isn't this just a brilliant short-cut?
function $(id) {
   return document.getElementById(id);
}

for (let i=1; i<4; i++){
   let obj = $('copy' + i);
   let value = (obj) ? obj.innerText : '';
   console.log('value.length:', value.length);
};
</code>```

Body:
I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.

I have variables copy1, copy2, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.

var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');

for(var i=0;i<4;i++){
 console.log(copy+i);
 console.log("copy"+i);
};

Ideally I would be able to select an element and style that via javascript.

Much appreciated

Thanks All.

Moe

Body:
Since nobody has addressed your "certain number of characters" requirement yet, I thought I would.

You could always use jQuery or write your own $ method, which works as a document.getElementById() wrapper function.

Here is a jsfiddle to see it in action.

HTML

<div id="copy1">01234</div>
<div id="copy2">012345678</div>
<div id="copy3">0123456789 0123456789</div>

JavaScript

// Isn't this just a brilliant short-cut?
function $(id) {
   return document.getElementById(id);
}

for (let i=1; i<4; i++){
   let obj = $('copy' + i);
   let value = (obj) ? obj.innerText : '';
   console.log('value.length:', value.length);
};


问:
Rails server is running, but cannot connect to localhost:3000
I am learning Ruby on Rails with railstutorial.org
I had set everything up and working fine from Chapter 1. However, all of a sudden my next app has an issue.

I run "rails server"

```<code>=> Booting WEBrick
=> Rails 3.2.9 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-11-15 00:45:08] INFO  WEBrick 1.3.1
[2012-11-15 00:45:08] INFO  ruby 1.9.3 (2012-11-10) [x86_64-linux]
[2012-11-15 00:45:08] INFO  WEBrick::HTTPServer#start: pid=2752 port=3000
</code>```

Seems to be working fine, just like with my previous app.

However, I try connecting to localhost:3000 , 0.0.0.0:3000 , 127.0.0.1:3000 on various browsers and they all cannot establish a connection to the server.

Some things to note:

-I was able to connect to localhost just a while ago--it just seems like it suddenly stopped working out of the blue.

-My first app was working perfectly fine, but now it doesn't work for my first app either.

-I don't have firewalls blocking the port, and my hosts file is not the problem.

-I am on Ubuntu 12.10

I almost always find solutions via search, but not this time.. so I need some help please. It's very frustrating as I feel like it's a simple problem that I spent way too long being stuck on.

Thank you.

答:
I run into the same issue. It turned out that browser-sync is also running on localhost:3000.

Due to some Rails developer would use browser-sync to test out the front end scripts quickly, I think that could be a popular reason that port 3000 is used.

Body:
I am learning Ruby on Rails with railstutorial.org
I had set everything up and working fine from Chapter 1. However, all of a sudden my next app has an issue.

I run "rails server"

=> Booting WEBrick
=> Rails 3.2.9 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-11-15 00:45:08] INFO  WEBrick 1.3.1
[2012-11-15 00:45:08] INFO  ruby 1.9.3 (2012-11-10) [x86_64-linux]
[2012-11-15 00:45:08] INFO  WEBrick::HTTPServer#start: pid=2752 port=3000

Seems to be working fine, just like with my previous app.

However, I try connecting to localhost:3000 , 0.0.0.0:3000 , 127.0.0.1:3000 on various browsers and they all cannot establish a connection to the server.

Some things to note:

-I was able to connect to localhost just a while ago--it just seems like it suddenly stopped working out of the blue.

-My first app was working perfectly fine, but now it doesn't work for my first app either.

-I don't have firewalls blocking the port, and my hosts file is not the problem.

-I am on Ubuntu 12.10

I almost always find solutions via search, but not this time.. so I need some help please. It's very frustrating as I feel like it's a simple problem that I spent way too long being stuck on.

Thank you.


问:
Increase RAM available for Knime?
Is there an easy way to increase the RAM available in Knime through a config file or through menu options?

I am constantly running into "heap-space" errors during execution and it by default limits the number of categorical variables to 1,000, as well as difficulty displaying charts with more than n values (~10,000).

Example error:

```<code>ERROR Decision Tree Learner 0:65       Execute failed: Java heap space
</code>```

Thanks!

答:
Sure, you can edit knime.ini (in the knime or knime_<version> folder) and change the row starting with -Xmx (I think by default it is 2048m, two GiB). Though do not use so much memory that would cause the OS to swap as Java do not play very well with swapping.

(Displaying too many variables might still be slow, maybe you could aggregate them somehow.)

Title: Increase RAM available for Knime?

Body:
Is there an easy way to increase the RAM available in Knime through a config file or through menu options?

I am constantly running into "heap-space" errors during execution and it by default limits the number of categorical variables to 1,000, as well as difficulty displaying charts with more than n values (~10,000).

Example error:

ERROR Decision Tree Learner 0:65       Execute failed: Java heap space

Thanks!


问:
Tomcat Maximum No. of concurrent File Uploads
I have a Tomcat Server with 250 connection threads. When I simulate concurrent file upload for 30 files (each 100 MB), the CPU and RAM Memory of the server machine goes to peak i.e., 95% usage.

I use following block of code to read the file data from HTTP Post.

```<code>// request is instance of HTTPServletRequest
int nDataLength = request.getContentLength();

byte dataBytes[] = new byte[nDataLength];

int bytesRead = 0;
int totalBytesRead = 0;
int bytesLimit = 1024;

InputStream in = new InputStream(request.getInputStream());
try
{
    while(totalBytesRead < nDataLength)
    {
        bytesRead = in.read(dataBytes, totalBytesRead, bytesLimit);
        totalBytesRead  += bytesRead;
    }
}
catch(Exception ex)
{
    throw ex;
}
finally
{
    in.close();
}
</code>```

My doubts are:

What could be the maximum number of concurrent File Uploads (each 100 MB files) that a Tomcat Server can handle ?

Is there any optimization required in my code to make use of all 250 connection threads ?

Introducing sleep can cause lengthy uploads. How to write efficient code ?

Thanks in advance.

regards,
Kingsley Reuben J

NOTE: I wont be able to use third party applications to resolve this problem

答:
You're running out of memory with the original solution, so stacker's suggestion (storing data in file) should work. Uploading files over http to tomcat is just not ideal to do bulk massive uploads.

You could try using a simpler server / more efficient protocol (e.g. ftp) or profile your Application Server & Application to see where your bottleneck is. One of the things that comes to mind is that HTTP uploads have to be MIME-decoded.

Body:
I have a Tomcat Server with 250 connection threads. When I simulate concurrent file upload for 30 files (each 100 MB), the CPU and RAM Memory of the server machine goes to peak i.e., 95% usage.

I use following block of code to read the file data from HTTP Post.

// request is instance of HTTPServletRequest
int nDataLength = request.getContentLength();

byte dataBytes[] = new byte[nDataLength];

int bytesRead = 0;
int totalBytesRead = 0;
int bytesLimit = 1024;

InputStream in = new InputStream(request.getInputStream());
try
{
    while(totalBytesRead < nDataLength)
    {
        bytesRead = in.read(dataBytes, totalBytesRead, bytesLimit);
        totalBytesRead  += bytesRead;
    }
}
catch(Exception ex)
{
    throw ex;
}
finally
{
    in.close();
}

My doubts are:

What could be the maximum number of concurrent File Uploads (each 100 MB files) that a Tomcat Server can handle ?

Is there any optimization required in my code to make use of all 250 connection threads ?

Introducing sleep can cause lengthy uploads. How to write efficient code ?

Thanks in advance.

regards,
Kingsley Reuben J

NOTE: I wont be able to use third party applications to resolve this problem

ContentLicense: CC BY-SA 2.5


问:
Ajax request not working in loopback
I am beginner in loopback and working on Get Post in loopback
This is code on client side

```<code>var datas = 'Something';
 $.ajax({
      type: 'POST',
      url: '/post',
      data: datas,
      dataType: 'text'
       })
         .done(function(data) {
            console.log('Successful');
         .fail(function(jqXhr) {
            console.log('Failed');
</code>```

});

and this is on server side(server.js)

```<code>app.post('/post', function(req, res){

 console.log('This is DATA '+ req.body);
</code>```

});

This is not working it gives me 404 not found or failed.

What am I doing wrong and Is there another method for get post in loopback?

答:
the server side needs an server and listening a port.

the client side needs to listen another port.

so they are not in one domain and cannot get access to each other.

this called a "cross-origin requests"

check this for the solution:https://www.w3.org/TR/cors/

Title: Ajax request not working in loopback

Body:
I am beginner in loopback and working on Get Post in loopback
This is code on client side

var datas = 'Something';
 $.ajax({
      type: 'POST',
      url: '/post',
      data: datas,
      dataType: 'text'
       })
         .done(function(data) {
            console.log('Successful');
         .fail(function(jqXhr) {
            console.log('Failed');

});

and this is on server side(server.js)

app.post('/post', function(req, res){

 console.log('This is DATA '+ req.body);

});

This is not working it gives me 404 not found or failed.

What am I doing wrong and Is there another method for get post in loopback?


问:
How does composition work in C#?
I have a Car Class:

```<code>public class Car
{
    private String _Brand;
    private String _Model;
    private Engine _Engine;

    public Car(){

    }

     public String Brand
     {
        get { return _Brand; }
        set { _Brand = value; }
     }

     public String Model
     {
        get { return _Model; }
        set { _Model = value; }
     }

     public Engine Engine
     {
        get { return _Engine; }
        set { _Engine = value; }
     }
}
</code>```

And an Engine Class:

```<code>public class Engine
{
     private int _Code;
     private DateTime _Year;

     public Engine(){

     }

     public int Code
     {
        get { return _Code; }
        set { _Code = value; }
     }

     public DateTime Year
     {
        get { return _Year; }
        set { _Year = value; }
     }
}
</code>```

From code-behind of Registration.aspx.cs, I wanna create using a button, a Car and an Engine w/ theirs respective relationship (Composition).

However, I have a massive confusion about how a composition for these objects should be behave. I.E., I can't figure it out if I must declare: Engine = new Engine(); in Car's constructor or if in Registration Event (Button, Code-Behind) declare: Car car = new Car() and then car.Engine = new Engine();.

I don't how composition relationship work in a scenario like this. The existence of where to declare "new" is putting me in a mixing of concepts.

Regards

答:
It's been a few years I've discussed this level of class architecture, so I'll try no to sound stupid :)

To begin with, I don't think we are talking Composition here: (in real life) the lifecycle of an Engine is not tied/controlled by a Car. If I'm assuming correctly, both classes are trying to represent a mapping of real life.

As far as I'm aware, in real, you can purchase an Engine to a Car, but a Car cannot function (but can exist) without an Engine (maybe those new fancy Teslas can?).

That screams is not a Composition since doesn't describe a relationship of ownership.

Depending on how strict you want to be, I'd call that an Aggregation (more) or an Association (less).

I personally would tend more towards the Aggregation because is a stronger relationship than, let's say, a Car and a Spoiler.

So, for that, my suggestion would be:

C#

```<code>public class Engine
{
     public Engine() { ... }

     public int Code { get; set; }

     public DateTime Year { get; set; }
}

public class Car
{
     public Car(Engine engine) : this() {
          this.Engine = engine;
     }

     public Car() {
     }

     public string Brand { get; set; }

     public String Model { get; set; }

     public Engine Engine { get; set; }
}
</code>```

Codebehind

```<code>var engine = new Engine();
var car = new Car(engine);
</code>```

That Car class definition is saying you can create a Car with or without an Engine, but for me it stresses the fact that an Engine is indeed important to a Car so a constructor accepting an Engine is available.

About composition

The composition of an Car being the "whole" and Engine being a "part" means that the Engine lifecycle is completely controlled by the Car. In this case, you are basically stating that "Upon the creation of a new object of Car, that object will internally create a new Engine which will be disposed when the Car object is no longer used."

The code for that would look like this:

```<code>//still the same
public class Engine
{
     public Engine() { ... }

     public int Code { get; set; }

     public DateTime Year { get; set; }
}

public class Car
{
     public Car() {
        //_engine = new Engine();
     }

     //Engine initialisation can be either here or inside the constructor (check constructor's commented code)
     private readonly Engine _engine = new Engine();

     public string Brand { get; set; }

     public String Model { get; set; }

     //you shouldn't be able to assign an _engine from outside
     public Engine Engine { get { return _engine; } }
}
</code>```

Composition Code-behind

```<code>var car = new Car();
car.Engine.Code = 123;
</code>```

Title: How does composition work in C#?

Body:
I have a Car Class:

public class Car
{
    private String _Brand;
    private String _Model;
    private Engine _Engine;

    public Car(){

    }

     public String Brand
     {
        get { return _Brand; }
        set { _Brand = value; }
     }

     public String Model
     {
        get { return _Model; }
        set { _Model = value; }
     }

     public Engine Engine
     {
        get { return _Engine; }
        set { _Engine = value; }
     }
}

And an Engine Class:

public class Engine
{
     private int _Code;
     private DateTime _Year;

     public Engine(){

     }

     public int Code
     {
        get { return _Code; }
        set { _Code = value; }
     }

     public DateTime Year
     {
        get { return _Year; }
        set { _Year = value; }
     }
}

From code-behind of Registration.aspx.cs, I wanna create using a button, a Car and an Engine w/ theirs respective relationship (Composition).

However, I have a massive confusion about how a composition for these objects should be behave. I.E., I can't figure it out if I must declare: Engine = new Engine(); in Car's constructor or if in Registration Event (Button, Code-Behind) declare: Car car = new Car() and then car.Engine = new Engine();.

I don't how composition relationship work in a scenario like this. The existence of where to declare "new" is putting me in a mixing of concepts.

Regards

Body:
It's been a few years I've discussed this level of class architecture, so I'll try no to sound stupid :)

To begin with, I don't think we are talking Composition here: (in real life) the lifecycle of an Engine is not tied/controlled by a Car. If I'm assuming correctly, both classes are trying to represent a mapping of real life.

As far as I'm aware, in real, you can purchase an Engine to a Car, but a Car cannot function (but can exist) without an Engine (maybe those new fancy Teslas can?).

That screams is not a Composition since doesn't describe a relationship of ownership.

Depending on how strict you want to be, I'd call that an Aggregation (more) or an Association (less).

I personally would tend more towards the Aggregation because is a stronger relationship than, let's say, a Car and a Spoiler.

So, for that, my suggestion would be:

C#

public class Engine
{
     public Engine() { ... }

     public int Code { get; set; }

     public DateTime Year { get; set; }
}

public class Car
{
     public Car(Engine engine) : this() {
          this.Engine = engine;
     }

     public Car() {
     }

     public string Brand { get; set; }

     public String Model { get; set; }

     public Engine Engine { get; set; }
}

Codebehind

var engine = new Engine();
var car = new Car(engine);

That Car class definition is saying you can create a Car with or without an Engine, but for me it stresses the fact that an Engine is indeed important to a Car so a constructor accepting an Engine is available.

About composition

The composition of an Car being the "whole" and Engine being a "part" means that the Engine lifecycle is completely controlled by the Car. In this case, you are basically stating that "Upon the creation of a new object of Car, that object will internally create a new Engine which will be disposed when the Car object is no longer used."

The code for that would look like this:

//still the same
public class Engine
{
     public Engine() { ... }

     public int Code { get; set; }

     public DateTime Year { get; set; }
}

public class Car
{
     public Car() {
        //_engine = new Engine();
     }

     //Engine initialisation can be either here or inside the constructor (check constructor's commented code)
     private readonly Engine _engine = new Engine();

     public string Brand { get; set; }

     public String Model { get; set; }

     //you shouldn't be able to assign an _engine from outside
     public Engine Engine { get { return _engine; } }
}

Composition Code-behind

var car = new Car();
car.Engine.Code = 123;


问:
add new row in gridview
UPDATE

from this i bind gridview

```<code>Public Function uplif() As DataTable
        Dim dt As New DataTable()
        gridvieew1.Visible = True

        Try

            dt.Columns.AddRange(New DataColumn(1) {New DataColumn("ID", GetType(Integer)),
                                                   New DataColumn("Name", GetType(String))}
            Dim Content As String = Request.Form(textbox1.UniqueID)
            For Each row As String In Content .Split(ControlChars.Lf)
                If Not String.IsNullOrEmpty(row) Then
                    dt.Rows.Add()
                    Dim i As Integer = 0
                    For Each cell As String In row.Split(ControlChars.Tab)
                        If i > 1 Then
                            labelmessage.Text = "More than 2 columns not Allowed !!"
                            textbox1.Text = ""
                        Else
                            If cell.Trim() = "" Then
                                cell = "0"
                            End If
                            dt.Rows(dt.Rows.Count - 1)(i) = cell
                            i += 1
                        End If
                    Next
                End If
            Next
             gridvieew1.DataSource = dt
             gridvieew1.DataBind()

        Catch Ex As Exception
            labelmessage.CssClass = "alertNo"
            labelmessage.Text = Ex.Message
        End Try
        Return dt
    End Function

  Protected Sub PasteToGridView(sender As Object, e As EventArgs)
        uplif()

    End Sub
</code>```

now when i try to add new row like this

```<code>Private Sub AddNewRowToGrid()
        Dim dt As DataTable = uplif()
        Dim NewRow As DataRow = dt.NewRow()
        dt.Rows.Add(NewRow)
         gridvieew1.DataSource = dt
         gridvieew1.DataBind()
    End Sub

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        AddNewRowToGrid()
    End Sub
</code>```

this shows same output like add new row and replace previous data which is already in gridview and also this shows an error
Object reference not set to an instance of an object.

after click on add new row

```<code>ID Name
</code>```

where as i want like this

```<code>ID Name
1  abc
2  def
(here new empty row when click on button )
</code>```

答:
Get the already assigned DataSource and then add the Row. Do not add columns as it will be already present in your datasource </p>

```<code> Private Sub AddNewRowToGrid()
        Dim dt As gridview1.DataSource
        Dim NewRow As DataRow = dt.NewRow()
        dt.Rows.Add(NewRow)
        gridview1.DataSource = dt
        gridview1.DataBind()
    End Sub

 Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    AddNewRowToGrid()
End Sub
</code>```

Title: add new row in gridview

Body:
UPDATE

from this i bind gridview

Public Function uplif() As DataTable
        Dim dt As New DataTable()
        gridvieew1.Visible = True

        Try

            dt.Columns.AddRange(New DataColumn(1) {New DataColumn("ID", GetType(Integer)),
                                                   New DataColumn("Name", GetType(String))}
            Dim Content As String = Request.Form(textbox1.UniqueID)
            For Each row As String In Content .Split(ControlChars.Lf)
                If Not String.IsNullOrEmpty(row) Then
                    dt.Rows.Add()
                    Dim i As Integer = 0
                    For Each cell As String In row.Split(ControlChars.Tab)
                        If i > 1 Then
                            labelmessage.Text = "More than 2 columns not Allowed !!"
                            textbox1.Text = ""
                        Else
                            If cell.Trim() = "" Then
                                cell = "0"
                            End If
                            dt.Rows(dt.Rows.Count - 1)(i) = cell
                            i += 1
                        End If
                    Next
                End If
            Next
             gridvieew1.DataSource = dt
             gridvieew1.DataBind()

        Catch Ex As Exception
            labelmessage.CssClass = "alertNo"
            labelmessage.Text = Ex.Message
        End Try
        Return dt
    End Function

  Protected Sub PasteToGridView(sender As Object, e As EventArgs)
        uplif()

    End Sub

now when i try to add new row like this

Private Sub AddNewRowToGrid()
        Dim dt As DataTable = uplif()
        Dim NewRow As DataRow = dt.NewRow()
        dt.Rows.Add(NewRow)
         gridvieew1.DataSource = dt
         gridvieew1.DataBind()
    End Sub

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        AddNewRowToGrid()
    End Sub

this shows same output like add new row and replace previous data which is already in gridview and also this shows an error
Object reference not set to an instance of an object.

after click on add new row

ID Name

where as i want like this

ID Name
1  abc
2  def
(here new empty row when click on button )

Body:
Get the already assigned DataSource and then add the Row. Do not add columns as it will be already present in your datasource

 Private Sub AddNewRowToGrid()
        Dim dt As gridview1.DataSource
        Dim NewRow As DataRow = dt.NewRow()
        dt.Rows.Add(NewRow)
        gridview1.DataSource = dt
        gridview1.DataBind()
    End Sub

 Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    AddNewRowToGrid()
End Sub


问:
Cordova: Cannot find module './android_sdk'
I checked out a Cordova project from SVN in IntelliJ Webstorm. When I try to run it on an emulated Android device, I receive the error message:

```<code>Error: Cannot find module './android_sdk'
</code>```

All the other people working on the project can run the project fine. And I can run every project that I have created locally.

答:
in my case (Kubuntu 16.04.2, Ionic 3.3.0, Cordova 7.0.1) i just did this:

```<code>cordova platform rm android
cordova platform add android
</code>```

and that did the trick :)

Body:
I checked out a Cordova project from SVN in IntelliJ Webstorm. When I try to run it on an emulated Android device, I receive the error message:

Error: Cannot find module './android_sdk'

All the other people working on the project can run the project fine. And I can run every project that I have created locally.

Body:
in my case (Kubuntu 16.04.2, Ionic 3.3.0, Cordova 7.0.1) i just did this:

cordova platform rm android
cordova platform add android

and that did the trick :)


问:
Put the Query result of MySql in to a C# list or array?
I've done some searching for the answer, but only find a lot of PHP answers. I need this for a C# application. Can any one point me in the right direction?

I'm doing this, but this only returns the first row into my variable:

```<code>    Query("SELECT SaksNummer FROM casetracking")

    public static string Query(string query)
    {
        string x;
        mysqlCon.Open();
        cmd = new MySqlCommand(query, mysqlCon);
        x = cmd.ExecuteScalar().ToString();
        mysqlCon.Close();
        return x;
    }
</code>```

答:
ExecuteScalar is designed to only return one (thus scalar) value:

Executes the query, and returns the
  first column of the first row in the
  result set returned by the query.
  Extra columns or rows are ignored.

Try using ExecuteReader. Example:

```<code>public void CreateMySqlDataReader(string mySelectQuery, MySqlConnection myConnection)
 {
    MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);
    myConnection.Open();
    MySqlDataReader myReader;
    myReader = myCommand.ExecuteReader();
    try
    {
      while(myReader.Read())
      {
        Console.WriteLine(myReader.GetString(0));
      }
    }
    finally
    {
      myReader.Close();
      myConnection.Close();
    }
 }
</code>```

Body:
I've done some searching for the answer, but only find a lot of PHP answers. I need this for a C# application. Can any one point me in the right direction?

I'm doing this, but this only returns the first row into my variable:

    Query("SELECT SaksNummer FROM casetracking")

    public static string Query(string query)
    {
        string x;
        mysqlCon.Open();
        cmd = new MySqlCommand(query, mysqlCon);
        x = cmd.ExecuteScalar().ToString();
        mysqlCon.Close();
        return x;
    }

Body:
ExecuteScalar is designed to only return one (thus scalar) value:

Executes the query, and returns the
  first column of the first row in the
  result set returned by the query.
  Extra columns or rows are ignored.

Try using ExecuteReader. Example:

public void CreateMySqlDataReader(string mySelectQuery, MySqlConnection myConnection)
 {
    MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);
    myConnection.Open();
    MySqlDataReader myReader;
    myReader = myCommand.ExecuteReader();
    try
    {
      while(myReader.Read())
      {
        Console.WriteLine(myReader.GetString(0));
      }
    }
    finally
    {
      myReader.Close();
      myConnection.Close();
    }
 }


问:
Using iOS8 and later devices with Xcode
Using iOS8 and later devices with Xcode?

答:
You can't run ios 11 on Xcode 8.2

You need Xcode 9 beta

https://developer.apple.com/download/

Xcode 9 beta requires a Mac running macOS 10.12.4 or later. Xcode 9
  beta includes SDKs for iOS 11, watchOS 4, macOS 10.13, and tvOS 11

.

ContentLicense: CC BY-SA 4.0

Title: Using iOS8 and later devices with Xcode


问:
Combining Either and Pair monads with transformers
I haven't used monad transformers before but I think it's what I need in my case. Here's some sample code below:

```<code>Prelude> (+) <$> Right 2 <*> Right 3
Right 5

Prelude> (+) <$> (['a'],2) <*> (['b'],3)
("ab",5)
</code>```

But I want to combine these two behaviours like so:

```<code>Prelude> (+) <$> Right ("a",2) <*> Right ("b",3)
Right ("ab",5)
</code>```

Naturally this fails to compile as numeric addition is not defined on (String, Int).

The Monad transformers Haskell wiki page suggests I need to use a transformer for the inner monad, which is in this case a pair, but searching for PairT on Hayoo! or Hoogle didn't reveal anything relevant.

Do I have to implement this transformer myself, or is there something on Hackage I've missed, or am I just misunderstanding how this should be done?

Note:

The actual outer monad I'm using isn't Either, it's a custom monad I've detailed in this question, which however is quite similar to Either.

答:
Answering my own question here, I think the Pair monad transformer is WriterT. In the example above, the type you're looking for is

```<code>WriterT String (Either l) Int
</code>```

String should be replaced by whatever is on the right hand side of the pairs.

l should be whatever the type of Left is.

Int should be replaced by whatever the result type is.

Body:
I haven't used monad transformers before but I think it's what I need in my case. Here's some sample code below:

Prelude> (+) <$> Right 2 <*> Right 3
Right 5

Prelude> (+) <$> (['a'],2) <*> (['b'],3)
("ab",5)

But I want to combine these two behaviours like so:

Prelude> (+) <$> Right ("a",2) <*> Right ("b",3)
Right ("ab",5)

Naturally this fails to compile as numeric addition is not defined on (String, Int).

The Monad transformers Haskell wiki page suggests I need to use a transformer for the inner monad, which is in this case a pair, but searching for PairT on Hayoo! or Hoogle didn't reveal anything relevant.

Do I have to implement this transformer myself, or is there something on Hackage I've missed, or am I just misunderstanding how this should be done?

Note:

The actual outer monad I'm using isn't Either, it's a custom monad I've detailed in this question, which however is quite similar to Either.

Body:
Answering my own question here, I think the Pair monad transformer is WriterT. In the example above, the type you're looking for is

WriterT String (Either l) Int

String should be replaced by whatever is on the right hand side of the pairs.

l should be whatever the type of Left is.

Int should be replaced by whatever the result type is.


问:
How to write query for created User, Created date, Modified User, Modified date for a table
I need help in knowing how to automatically make the table load the values for Created user , created date, modified user and modified date,

once any data goes into the table , we should have the Created user and created date column value to be fixed but the modified user and modified date should change

答:
You can set the default value of a column to GetDate() for the datetime columns and to SYSTEM_USER for the current user. This is good for the Creation of the records.

For the modification columns you need to add a trigger.

Also worth reading...

How to use system_user in audit trigger but still use connection pooling?


问:
The jquery $.each function console.log(this) ,prints result is string like "a" 'b' 'c'
```<code>var arr=["aaa","bbb","cccc"];
$.each(arr,function(a,b){
    console.log(this);
})
</code>```

the result is in the Chrome console following :

the Chrome console

i think the result is "aaa" "bbb","cccc",why the result is "a" "a" "a" 'b''b''b'....

答:
```<code>var arr=["aaa","bbb","cccc"];

console.log(new String(arr[0]));
console.log(new String(arr[1]));
console.log(new String(arr[2]));
</code>```

when you use the jQuery.each to loop the "arr", the callback while bind to new String(arr[i])

```<code>$.each(arr,function(a,b){
    console.log(new String(b));
    console.log(this);
})
</code>```

and the param "b" is your expected results

Body:
var arr=["aaa","bbb","cccc"];
$.each(arr,function(a,b){
    console.log(this);
})

the result is in the Chrome console following :

the Chrome console

i think the result is "aaa" "bbb","cccc",why the result is "a" "a" "a" 'b''b''b'....

Body:
var arr=["aaa","bbb","cccc"];

console.log(new String(arr[0]));
console.log(new String(arr[1]));
console.log(new String(arr[2]));

when you use the jQuery.each to loop the "arr", the callback while bind to new String(arr[i])

$.each(arr,function(a,b){
    console.log(new String(b));
    console.log(this);
})

and the param "b" is your expected results


问:
Java switch smart enough to rearrange?
Given a hot piece of code that has switch with many case options (and all are with breaks e.g. can be rearranged) will JVM figure out the frequent entries to check them ahead of others? </p>

答:
Frequency or likelihood of execution of individual cases doesn't come into it.  The compiler will generate either:

a tableswitch instruction with an associated jump table that is indexed directly by the switch value, or

a lookupswitch instruction with a table of key/target pairs that can (typically) be binary-searched.

See the JVM Specification #3.10.

Title: Java switch smart enough to rearrange?


问:
calculate minimum value from row calculation in pandas
I have a list of throughput values in one column of a pandas DataFrame.  I want to calculate a value's variation from a threshold as a percent of that threshold.

So if I have thresholds at 2 and 7.  I'd want to calculate the minimum of the following functions.

```<code>(df.throughput - 2)/2
(df.throughput - 7)/7

x   throughtput
1   3
4   4
7   9
</code>```

I tried using the following to create a new column, but I keep getting an error.  I fell like there's something really obvious i'm missing here.

```<code>df['pct'] =  np.min(  (df.throughput-2)/2,  (df.throughput - 7)/7  )
df['pct'] =  np.min(  (df['throughput']-2)/2,  (df['throughput'] - 7)/7  )
'Series' objects are mutable, thus they cannot be hashed
</code>```

答:
You can create new Series, compare them and use numpy.where for new column:

```<code>a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = np.where(a < b, a, b)
print (df)
   x  throughtput       pct
0  1            3 -0.571429
1  4            4 -0.428571
2  7            9  0.285714
</code>```

Solution with concat and DataFrame.min:

```<code>a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = pd.concat([a,b], axis=1).min(axis=1)
print (df)
   x  throughtput       pct
0  1            3 -0.571429
1  4            4 -0.428571
2  7            9  0.285714
</code>```

Or create 2d array by numpy.column_stack and get min by numpy.amin:

```<code>a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
print (df)
   x  throughtput       pct
0  1            3 -0.571429
1  4            4 -0.428571
2  7            9  0.285714
</code>```

```<code>a = (df['throughtput'].values - 2)/2
b = (df['throughtput'].values - 7)/7
df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
print (df)
   x  throughtput       pct
0  1            3 -0.571429
1  4            4 -0.428571
2  7            9  0.285714
</code>```

Timings:

```<code>N = 1000000
#N = 10
df = pd.DataFrame({'x': np.random.randint(10,size=N),
                   'throughtput':np.random.randint(10,size=N)})
print (df)

In [50]: %%timeit
    ...: a = (df['throughtput'] - 2)/2
    ...: b = (df['throughtput'] - 7)/7
    ...: df['pct'] = np.where(a < b, a, b)
    ...:
10 loops, best of 3: 21.1 ms per loop

In [51]: %%timeit
    ...: a = (df['throughtput'] - 2)/2
    ...: b = (df['throughtput'] - 7)/7
    ...: df['pct'] = pd.concat([a,b], axis=1).min(axis=1)
    ...:
10 loops, best of 3: 56.4 ms per loop

In [52]: %%timeit
    ...: a = (df['throughtput'] - 2)/2
    ...: b = (df['throughtput'] - 7)/7
    ...: df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
    ...:
10 loops, best of 3: 35.1 ms per loop

In [53]: %%timeit
    ...: a = (df['throughtput'].values - 2)/2
    ...: b = (df['throughtput'].values - 7)/7
    ...: df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
    ...:
10 loops, best of 3: 38.5 ms per loop
</code>```

Another answer by Tiny.D:

```<code>In [54]: %%timeit
    ...: df['cal_1'] = (df.throughtput - 2)/2
    ...: df['cal_2'] = (df.throughtput - 7)/7
    ...: df['pct'] = df[['cal_1','cal_2']].min(axis=1)
    ...: df[['x','throughtput','pct']]
    ...:
10 loops, best of 3: 73.7 ms per loop

In [55]: %%timeit
    ...: df['pct']=[min(i,j) for i,j in (zip((df.throughtput - 2)/2,(df.throughtput - 7)/7))]
    ...:
1 loop, best of 3: 435 ms per loop
</code>```

Body:
I have a list of throughput values in one column of a pandas DataFrame.  I want to calculate a value's variation from a threshold as a percent of that threshold.

So if I have thresholds at 2 and 7.  I'd want to calculate the minimum of the following functions.

(df.throughput - 2)/2
(df.throughput - 7)/7

x   throughtput
1   3
4   4
7   9

I tried using the following to create a new column, but I keep getting an error.  I fell like there's something really obvious i'm missing here.

df['pct'] =  np.min(  (df.throughput-2)/2,  (df.throughput - 7)/7  )
df['pct'] =  np.min(  (df['throughput']-2)/2,  (df['throughput'] - 7)/7  )
'Series' objects are mutable, thus they cannot be hashed

Body:
You can create new Series, compare them and use numpy.where for new column:

a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = np.where(a < b, a, b)
print (df)
   x  throughtput       pct
0  1            3 -0.571429
1  4            4 -0.428571
2  7            9  0.285714

Solution with concat and DataFrame.min:

a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = pd.concat([a,b], axis=1).min(axis=1)
print (df)
   x  throughtput       pct
0  1            3 -0.571429
1  4            4 -0.428571
2  7            9  0.285714

Or create 2d array by numpy.column_stack and get min by numpy.amin:

a = (df['throughtput'] - 2)/2
b = (df['throughtput'] - 7)/7
df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
print (df)
   x  throughtput       pct
0  1            3 -0.571429
1  4            4 -0.428571
2  7            9  0.285714

a = (df['throughtput'].values - 2)/2
b = (df['throughtput'].values - 7)/7
df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
print (df)
   x  throughtput       pct
0  1            3 -0.571429
1  4            4 -0.428571
2  7            9  0.285714

Timings:

N = 1000000
#N = 10
df = pd.DataFrame({'x': np.random.randint(10,size=N),
                   'throughtput':np.random.randint(10,size=N)})
print (df)

In [50]: %%timeit
    ...: a = (df['throughtput'] - 2)/2
    ...: b = (df['throughtput'] - 7)/7
    ...: df['pct'] = np.where(a < b, a, b)
    ...:
10 loops, best of 3: 21.1 ms per loop

In [51]: %%timeit
    ...: a = (df['throughtput'] - 2)/2
    ...: b = (df['throughtput'] - 7)/7
    ...: df['pct'] = pd.concat([a,b], axis=1).min(axis=1)
    ...:
10 loops, best of 3: 56.4 ms per loop

In [52]: %%timeit
    ...: a = (df['throughtput'] - 2)/2
    ...: b = (df['throughtput'] - 7)/7
    ...: df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
    ...:
10 loops, best of 3: 35.1 ms per loop

In [53]: %%timeit
    ...: a = (df['throughtput'].values - 2)/2
    ...: b = (df['throughtput'].values - 7)/7
    ...: df['pct'] = np.amin(np.column_stack([a,b]), axis=1)
    ...:
10 loops, best of 3: 38.5 ms per loop

Another answer by Tiny.D:

In [54]: %%timeit
    ...: df['cal_1'] = (df.throughtput - 2)/2
    ...: df['cal_2'] = (df.throughtput - 7)/7
    ...: df['pct'] = df[['cal_1','cal_2']].min(axis=1)
    ...: df[['x','throughtput','pct']]
    ...:
10 loops, best of 3: 73.7 ms per loop

In [55]: %%timeit
    ...: df['pct']=[min(i,j) for i,j in (zip((df.throughtput - 2)/2,(df.throughtput - 7)/7))]
    ...:
1 loop, best of 3: 435 ms per loop


问:
using class to represent a task in c++
I'm writing a function to do a specific task. This function need some temporary data to process the task. The problem is if I do everything in this function then the size of this function will be big. Then I think about breaking this function into many small functions. But if I do that, I need to pass some temporary data to those small functions. It make the code look not very well. So I consider to create a class that have private data including input, output and temporary data and those small function become the method of class. Below is pseudo code to represent my idea.

```<code>/* big function */
output big_function(input)
{
    temporary_data data1;
    temporary_data data2;
    temporary_data data3;
    temporary_data data4;
    /* do task here*/
    ...
    return output;
}

/* many small function*/
output function1(input)
{
    temporary_data data1;
    temporary_data data2;
    temporary_data data3;
    temporary_data data4;
    /*do some thing */
    function2(input,data1,data2, data3, data4);
    output = function3(input,data1,data2, data3, data4);
    return output;
}

/* use class*/
class Task
{
public:
    Task(input);
    function1();
    output get_output();
private:
    function2();
    function3();
private:
    input;
    output;
    data1;
    data2;
    data3;
    data4;
}
</code>```

And my question is: using class to represent a task is a right way or not?

答:
Using an object's member variables so as to avoid argument passing generally leads to very fragile code and hard to read code (similar to using global variables).

It seems to me like what you want is:

```<code>output function(input);
</code>```

Rather than the three (in truth four) steps required by your object:

```<code>Task t(input);
t.function1();
output o = t.get_output();
// destructor is implicitly called at some point
</code>```

The other issue with this is that the function on t must be called in a specific order (@VolAnd mentioned this in his comment).

To solve the issue of passing in and out large numbers of parameters, pass structs into and out of the functions (so at their calling its clear what is read and what is modified):

```<code>struct params {
  temporary_data data1;
  temporary_data data2;
  temporary_data data3;
  temporary_data data4;
};
</code>```

If appropriate, use multiple structs to communicate and enforce the state changes in the temporary data (e.g., struct unsortedData and struct sortedData).

Title: using class to represent a task in c++

Body:
I'm writing a function to do a specific task. This function need some temporary data to process the task. The problem is if I do everything in this function then the size of this function will be big. Then I think about breaking this function into many small functions. But if I do that, I need to pass some temporary data to those small functions. It make the code look not very well. So I consider to create a class that have private data including input, output and temporary data and those small function become the method of class. Below is pseudo code to represent my idea.

/* big function */
output big_function(input)
{
    temporary_data data1;
    temporary_data data2;
    temporary_data data3;
    temporary_data data4;
    /* do task here*/
    ...
    return output;
}

/* many small function*/
output function1(input)
{
    temporary_data data1;
    temporary_data data2;
    temporary_data data3;
    temporary_data data4;
    /*do some thing */
    function2(input,data1,data2, data3, data4);
    output = function3(input,data1,data2, data3, data4);
    return output;
}

/* use class*/
class Task
{
public:
    Task(input);
    function1();
    output get_output();
private:
    function2();
    function3();
private:
    input;
    output;
    data1;
    data2;
    data3;
    data4;
}

And my question is: using class to represent a task is a right way or not?

Body:
Using an object's member variables so as to avoid argument passing generally leads to very fragile code and hard to read code (similar to using global variables).

It seems to me like what you want is:

output function(input);

Rather than the three (in truth four) steps required by your object:

Task t(input);
t.function1();
output o = t.get_output();
// destructor is implicitly called at some point

The other issue with this is that the function on t must be called in a specific order (@VolAnd mentioned this in his comment).

To solve the issue of passing in and out large numbers of parameters, pass structs into and out of the functions (so at their calling its clear what is read and what is modified):

struct params {
  temporary_data data1;
  temporary_data data2;
  temporary_data data3;
  temporary_data data4;
};

If appropriate, use multiple structs to communicate and enforce the state changes in the temporary data (e.g., struct unsortedData and struct sortedData).


问:
Authentication with both email and username (same field) (laravel API )
I am building laravel API of my website . I am using laravel 5.3

I am using the API in building mobile app .

In login section, there are two fields :

Enter email or username

Enter password

In my DB , email and username are different columns.

Here is the function:

```<code>public function authenticate()
{

$credentials=request()->only('username','password');

try {

    $token=JWTAuth::attempt($credentials);

    if(!$token){
        return response()->json(['error'=>'credentials wrong'],401);
    }
}
catch(JWTException $e) {

 return response()->json(['error'=>'something_went_wrong'],500);

}
return response()->json(['token'=>$token],200);
}
</code>```

Here only username is used,I want to use both username and password.

If need any other info please ask.

ty:)

答:
Override this method in your AuthController

```<code>/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function getCredentials(Request $request)
{
    $login = $request->get('loginEmail');
    $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

    return [
        $field => $login,
        'password' => $request->get('password'),
    ];
}
</code>```

Body:
I am building laravel API of my website . I am using laravel 5.3

I am using the API in building mobile app .

In login section, there are two fields :

Enter email or username

Enter password

In my DB , email and username are different columns.

Here is the function:

public function authenticate()
{

$credentials=request()->only('username','password');

try {

    $token=JWTAuth::attempt($credentials);

    if(!$token){
        return response()->json(['error'=>'credentials wrong'],401);
    }
}
catch(JWTException $e) {

 return response()->json(['error'=>'something_went_wrong'],500);

}
return response()->json(['token'=>$token],200);
}

Here only username is used,I want to use both username and password.

If need any other info please ask.

ty:)

Body:
Override this method in your AuthController

/**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function getCredentials(Request $request)
{
    $login = $request->get('loginEmail');
    $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

    return [
        $field => $login,
        'password' => $request->get('password'),
    ];
}


问:
Different coloured fly out menu
I'm creating a custom master page for a MOSS publishing site. The designers have come up with this idea for the fly out menu...

alt text http://www.abbeylegal.com/Downloads/2009-01-06/gradient%20menu.jpg

which uses graduated/different backgrond and text colours for each menu option.

Does anyone know how to accomplish this?

答:
I would probably use the Suckerfish method with different a CSS class for each level of
 in the menu:

```<code><ul id="menu">
    <li class="root"><a href="#">Home</a></li>
    <!-- etc. -->
    <li><a href="#">Products</a>
        <ul>
             <li class="sub1"><a href="#">BTE Legal Expense Insurance</a></li>
             <li class="sub2"><a href="#">Legal Services</a></li>
             <!-- etc. -->
        </ul>
    </li>
    <!-- etc. -->
</ul>
</code>```

OwnerDisplayName: Rob

Title: Different coloured fly out menu

Body:
I would probably use the Suckerfish method with different a CSS class for each level of <li> in the menu:

<ul id="menu">
    <li class="root"><a href="#">Home</a></li>
    <!-- etc. -->
    <li><a href="#">Products</a>
        <ul>
             <li class="sub1"><a href="#">BTE Legal Expense Insurance</a></li>
             <li class="sub2"><a href="#">Legal Services</a></li>
             <!-- etc. -->
        </ul>
    </li>
    <!-- etc. -->
</ul>

OwnerDisplayName: Ryan Arana


问:
asp.net MVC: reroute to action in custom action attribute
i'm trying to create an attribute that i can set on my controllers action in which i can check if a user in some kind of role.
I know with standard asp.net authentication this is already possible, but i'm not using that.

So what i want to accomplish is this:

```<code>[Role("Admin", "SuperUser")]
public ActionResult SafeCourse()
</code>```

I've constructed this:

```<code>public class AdminAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
</code>```

Ans now..... i want to redirect the user to some controller/action or if that isn't possible to some view when he / she is not in the right role.
But i'm not in my usual context (= controller) and i'm somewhat lost :)

Michel

答:
The proper/correct way of doing this

Asp.net MVC has extensibility point exactly for your needs. You should be writing a custom action method selector attribute that would actually select the correct action method based on the definition in the attribute.

```<code>public class RoleAttribute: ActionMethodSelectorAttribute
{
    ...
}
</code>```

Check this blog post that talks about action method selectors. One of the good extensibility points in Asp.net MVC yet not many developers know about it.

Body:
i'm trying to create an attribute that i can set on my controllers action in which i can check if a user in some kind of role.
I know with standard asp.net authentication this is already possible, but i'm not using that.

So what i want to accomplish is this:

[Role("Admin", "SuperUser")]
public ActionResult SafeCourse()

I've constructed this:

public class AdminAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

Ans now..... i want to redirect the user to some controller/action or if that isn't possible to some view when he / she is not in the right role.
But i'm not in my usual context (= controller) and i'm somewhat lost :)

Michel

Body:
The proper/correct way of doing this

Asp.net MVC has extensibility point exactly for your needs. You should be writing a custom action method selector attribute that would actually select the correct action method based on the definition in the attribute.

public class RoleAttribute: ActionMethodSelectorAttribute
{
    ...
}

Check this blog post that talks about action method selectors. One of the good extensibility points in Asp.net MVC yet not many developers know about it.


问:
wondering if there is an efficient way to shorten this code
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

```<code>private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}
</code>```

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

答:
If you are talking about the length of the code, I would suggest using switch-case-break-default construct
Switch the books variable.
This wont improve the performance though</p>

Body:
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.


答:
Your URL starts with '/'.
Whenever a URL starts with '/' it is treated as absolute URL.

Whereas, most of the time, web apps are bounded with a context root.
Try using URL without initial '/' and it should work.

Title: Ajax request not working in loopback

Body:
I am beginner in loopback and working on Get Post in loopback
This is code on client side

var datas = 'Something';
 $.ajax({
      type: 'POST',
      url: '/post',
      data: datas,
      dataType: 'text'
       })
         .done(function(data) {
            console.log('Successful');
         .fail(function(jqXhr) {
            console.log('Failed');

});

and this is on server side(server.js)

app.post('/post', function(req, res){

 console.log('This is DATA '+ req.body);

});

This is not working it gives me 404 not found or failed.

What am I doing wrong and Is there another method for get post in loopback?


问:
Sql server is not opening

when i try to open my sql server this message pops up...

see the blue link, when it click "Here" it takes me to the site and the site says We're sorry, this download is no longer available. what should i do.....

答: Thanks to all,the problem has been solved, the problem was i had both 2010 and 2013 VS installed on my pc and i was using only 2013, 2010 needed some upgrades so it was blocking the SSMS studio. All i have to do, was to uninstall 2010 VS.</p>

Title: Sql server is not opening


问:
My HTML code is not being read on Javascript/JSON
So I'm doing a quote generator in Javascript in which the quote generates on click.

The code looks like this:

```<code>$("#getQuote").on("click", function(){
var i = Math.floor((Math.random() * quote.length));

   $("#theQuote").html(quote[i] <\br> person[i]);
});
</code>```

I'm trying to make a line break between the quote and the person who made the quote but it doesn't seem the recognize any code after quote[i].

I've also tried adding \n to the strings in my array for example:

```<code>var quote = ['"With great power, comes great responsibility." \n- Uncle Ben'];
</code>```

but somehow \n is not read whereas the rest of the quote is.

答:
1st $("#theQuote").html(quote[0] + '
' + person[0]); anything without wrap by ' or " are either number or variable, and .html take string as html, so you need concate them use +

2nd this way will also work, var quote = ['"With great power, comes great responsibility."
 - TEST_1 Uncle Ben'];

var quote = ['"With great power, comes great responsibility."
 - TEST_1 Uncle Ben'];
var person = ['TEST_2 Uncle Ben'];

$("#getQuote").on("click", function() {
  //var i = Math.floor((Math.random() * quote.length));

  $("#theQuote").html(quote[0] + '
' + person[0]);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="getQuote">getQuote</button>

<br><br>
<div id="theQuote">N/A</div></code>```

Body:
So I'm doing a quote generator in Javascript in which the quote generates on click.

The code looks like this:

$("#getQuote").on("click", function(){
var i = Math.floor((Math.random() * quote.length));

   $("#theQuote").html(quote[i] <\br> person[i]);
});

I'm trying to make a line break between the quote and the person who made the quote but it doesn't seem the recognize any code after quote[i].

I've also tried adding \n to the strings in my array for example:

var quote = ['"With great power, comes great responsibility." \n- Uncle Ben'];

but somehow \n is not read whereas the rest of the quote is.

Body:
1st $("#theQuote").html(quote[0] + '<br>' + person[0]); anything without wrap by ' or " are either number or variable, and .html take string as html, so you need concate them use +

2nd this way will also work, var quote = ['"With great power, comes great responsibility." <br> - TEST_1 Uncle Ben'];

var quote = ['"With great power, comes great responsibility." <br> - TEST_1 Uncle Ben'];
var person = ['TEST_2 Uncle Ben'];

$("#getQuote").on("click", function() {
  //var i = Math.floor((Math.random() * quote.length));

  $("#theQuote").html(quote[0] + '<br>' + person[0]);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="getQuote">getQuote</button>

<br><br>
<div id="theQuote">N/A</div>


问:
Configuring WCF in IIS7 & Windows 7
I am having a problem when I try to browse WCF service (.svc file) which is hosted in IIS7 & Windows7. It throws following error.

HTTP Error 404.3 - Not Found
The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

I tried to run ServiceModelReg, but it say I should have admin rights in order to run this, although I am admin on this machine.

Does any one know how to resolve this issue.

答:
Your issued is answered here. Trying to be short:

When you start the command prompt, can
  you right-click on the icon to open it
  and select "Run as Administrator"? I
  don't know exactly what's the logic
  behind that, but on Vista there are
  two kinds of administrative users, one
  "normal" administrator and one
  "elevated" administrator. I'd guess
  the tool needs the second kind.

and second

Also, Why do you need to run
  Servicemodelreg.exe on VIsta?
  Officially this is not supported on
  Vista. Instead you can go to WIndows
  features menu throught Add remove
  programs and enabled Http Activation
  under .Net framework 3.0 feature.

This will enable everything you might
  want to do via Servicemodelreg.exe.

Edit

And also here.

Title: Configuring WCF in IIS7 & Windows 7


问:
How to pass a NoneType error
I'm currently having an issue with my text adventure code, the program runs perfectly fine, but whenever the character winds up dying, the program calls this error:

```<code>    NextSceneName = CurrentScene.enter()
AttributeError: 'NoneType' object has no attribute 'enter'
</code>```

The program will crash after this, which is no big deal in itself.

The code for this part of the program is:

```<code>def play(self):
        CurrentScene = self.sceneMap.OpeningScene()
        LastScene = self.sceneMap.NextScene('Finished')

        while CurrentScene != LastScene:
            NextSceneName = CurrentScene.enter()
            CurrentScene = self.sceneMap.NextScene(NextSceneName)

        CurrentScene.enter()
</code>```

What I want to know is, how do I use something like an If statement, or a Try Except statement to pass the NoneType/AttributeError?

答:
First, CurrentScene must be evaluated as None, that's why you're getting the error. The smart move would be to figure out why is that happening if that's not expected

But, if you want to catch that exception, replace your last line CurrentScene.enter() with this:

```<code>try:
    CurrentScene.enter()
except AttributeError:
    dosomething()
</code>```

Or if you want to catch all that before you try to "enter", you can do this:

```<code>if CurrentScene == None:
    dosomething()
</code>```

If that doesn't work it's probably because you are also calling CurrentScene.enter() from within the while loop, so do it there instead

Title: How to pass a NoneType error

Body:
I'm currently having an issue with my text adventure code, the program runs perfectly fine, but whenever the character winds up dying, the program calls this error:

    NextSceneName = CurrentScene.enter()
AttributeError: 'NoneType' object has no attribute 'enter'

The program will crash after this, which is no big deal in itself.

The code for this part of the program is:

def play(self):
        CurrentScene = self.sceneMap.OpeningScene()
        LastScene = self.sceneMap.NextScene('Finished')

        while CurrentScene != LastScene:
            NextSceneName = CurrentScene.enter()
            CurrentScene = self.sceneMap.NextScene(NextSceneName)

        CurrentScene.enter()

What I want to know is, how do I use something like an If statement, or a Try Except statement to pass the NoneType/AttributeError?

Body:
First, CurrentScene must be evaluated as None, that's why you're getting the error. The smart move would be to figure out why is that happening if that's not expected

But, if you want to catch that exception, replace your last line CurrentScene.enter() with this:

try:
    CurrentScene.enter()
except AttributeError:
    dosomething()

Or if you want to catch all that before you try to "enter", you can do this:

if CurrentScene == None:
    dosomething()

If that doesn't work it's probably because you are also calling CurrentScene.enter() from within the while loop, so do it there instead