问:
Excel VBA - How to compare two ranges at 1 to 1 level in For Loop?
This question is slightly different from the existing questions on this site listed here, here & here.

I want to write a UDF in Excel VBA (and not use any existing VBA Functions) to loop thru two ranges simultaneously at same level (1 to 1) and check if the two values match.

enter image description here

```<code>Public Function compare(r1 As Range, r2 As Range) As Integer
Dim i
For Each cell In r1
     if cell.Value = 'value from r2 at same range level,  1 to 1 compare
        i = i + 1
     End If
Next cell
compare = i
End Function
</code>```

In this UDF it takes in two ranges as input. Assume they are single column and equal rows for simplicity. Now using a For Each cell in Range loop I wish to compare the two ranges at same cell level. Is this possible?

Would I need to create a Nested For and in every inner For, skips those many cells to match the cells of Outer For?

答:
Change to a numbered loop.

```<code>Public Function compare(r1 As Range, r2 As Range) As long
    Dim i as long, r as long
    For r=1 to r1.cells.count
         if r1.cells(r).Value = r2.cells(r).Value Then
            i = i + 1
         End If
    Next r
    compare = i
End Function
</code>```

There may other benefits from variant arrays, resizing r2 to always be the same rows x columns as r1 and restricting r1 and r2 to the .UsedRange.

```<code>Public Function compare(r1 As Range, r2 As Range) As long
    Dim i as long, r as long

    'restrict to .usedrange so full columns can be input
    set r1 = intersect(r1, r1.parent.usedrange)
    'make sure r2 is same dimensions as r1
    set r2 = r2.cells(1).resize(r1.rows.count, r1.columns.count)

    For r=1 to r1.cells.count
         if r1.cells(r).Value = r2.cells(r).Value Then
            i = i + 1
         End If
    Next r
    compare = i
End Function
</code>```

Body:
This question is slightly different from the existing questions on this site listed here, here & here.

I want to write a UDF in Excel VBA (and not use any existing VBA Functions) to loop thru two ranges simultaneously at same level (1 to 1) and check if the two values match.

enter image description here

Public Function compare(r1 As Range, r2 As Range) As Integer
Dim i
For Each cell In r1
     if cell.Value = 'value from r2 at same range level,  1 to 1 compare
        i = i + 1
     End If
Next cell
compare = i
End Function

In this UDF it takes in two ranges as input. Assume they are single column and equal rows for simplicity. Now using a For Each cell in Range loop I wish to compare the two ranges at same cell level. Is this possible?

Would I need to create a Nested For and in every inner For, skips those many cells to match the cells of Outer For?

Body:
Change to a numbered loop.

Public Function compare(r1 As Range, r2 As Range) As long
    Dim i as long, r as long
    For r=1 to r1.cells.count
         if r1.cells(r).Value = r2.cells(r).Value Then
            i = i + 1
         End If
    Next r
    compare = i
End Function

There may other benefits from variant arrays, resizing r2 to always be the same rows x columns as r1 and restricting r1 and r2 to the .UsedRange.

Public Function compare(r1 As Range, r2 As Range) As long
    Dim i as long, r as long

    'restrict to .usedrange so full columns can be input
    set r1 = intersect(r1, r1.parent.usedrange)
    'make sure r2 is same dimensions as r1
    set r2 = r2.cells(1).resize(r1.rows.count, r1.columns.count)

    For r=1 to r1.cells.count
         if r1.cells(r).Value = r2.cells(r).Value Then
            i = i + 1
         End If
    Next r
    compare = i
End Function


来源: stackexchange

问:
Project multiple documents from a field's value using aggregation framework
Consider this document

```<code>{
    "_id" : ObjectId("56d06614070b7f2b117b23db"),
    "name" : "joe",
    "value" : 3,
}
</code>```

I need to get the following aggregation result :

```<code>[{
    "name" : "joe",
},
{
    "name" : "joe",
},
{
    "name" : "joe",
}]
</code>```

Do you have an idea on how to do that with aggregation framework ?

答:
You can use $range:

```<code>db.collection.aggregate([
  { "$project": {
    "_id": 0,
    "name": {
      "$map": {
        "input": { "$range": [0,"$value"] },
        "in": "$name"
      }
    }
  }},
  { "$unwind": "$name" }
])
</code>```

That essentially supplies [0,1,2] as in input array to $map, from which you can emit each value of "name" repeated. So the "$value" field in the document is being used as the upper bound or "length" of the array to produce.

Not really any other option if your MongoDB does not support that, other than you simply transform on the cursor instead.

ContentLicense: CC BY-SA 3.0

Body:
Consider this document

{
    "_id" : ObjectId("56d06614070b7f2b117b23db"),
    "name" : "joe",
    "value" : 3,
}

I need to get the following aggregation result :

[{
    "name" : "joe",
},
{
    "name" : "joe",
},
{
    "name" : "joe",
}]

Do you have an idea on how to do that with aggregation framework ?

Body:
You can use $range:

db.collection.aggregate([
  { "$project": {
    "_id": 0,
    "name": {
      "$map": {
        "input": { "$range": [0,"$value"] },
        "in": "$name"
      }
    }
  }},
  { "$unwind": "$name" }
])

That essentially supplies [0,1,2] as in input array to $map, from which you can emit each value of "name" repeated. So the "$value" field in the document is being used as the upper bound or "length" of the array to produce.

Not really any other option if your MongoDB does not support that, other than you simply transform on the cursor instead.


问:
How to implement authentication with access and refresh token using retrofit in android?
I am trying to implement the token based authentication with access and refresh token. The access token expires after some limited time. Then using the refresh token it needs to be updated again. I am following this reference and this answer as well. As I am new to android I got no idea about how to implement these concepts.

This is my interface to get access token using the refresh token.

```<code>  //get access Token with Refresh Token
    @POST("/api/token")
    Call<ResponseBody> getAccessToken(@Body JSONObject jsonObject);
</code>```

This is my Retrofit Client:

```<code>public class ApiClient {
        public static final String BASE_URL = "https://lit-cove-70675.herokuapp.com";
        private static Retrofit retrofit = null;
          public static Retrofit getClient() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }
</code>```

I have no idea where and how to implement those Service Generators and Authenticator. I have to pass "Authentication"=>ACCESSTOKEN in header with every API URL.

答:
Please use below code to create your service:

```<code>public <S> S createService(Class<S> serviceClass, AuthToken authToken) {

            final String token = "Bearer" + " " + authToken.getAceessToken();
            Log.d("ServiceGenerator", "Token:::::::  " + token);

            httpClient.addInterceptor(chain -> {
                Request original = chain.request();

                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder()
                        .header(KEY_AUTH_HEADER, token).header("Content-Type", "application/json");

                Request request = requestBuilder.build();
                return chain.proceed(request);
            });

            Retrofit retrofit = builder.client(httpClient.build()).build();
            return retrofit.create(serviceClass);
        }
</code>```

Add following line to call method:

```<code> ApiService service = serviceGenerator.createService(ApiService.class, token);
        Call<ResponseBody> call = service.getMovielist(id);
</code>```

serviceGenerator is the class where i have defined create service method.You can declare whenever you want.

Body:
I am trying to implement the token based authentication with access and refresh token. The access token expires after some limited time. Then using the refresh token it needs to be updated again. I am following this reference and this answer as well. As I am new to android I got no idea about how to implement these concepts.

This is my interface to get access token using the refresh token.

  //get access Token with Refresh Token
    @POST("/api/token")
    Call<ResponseBody> getAccessToken(@Body JSONObject jsonObject);

This is my Retrofit Client:

public class ApiClient {
        public static final String BASE_URL = "https://lit-cove-70675.herokuapp.com";
        private static Retrofit retrofit = null;
          public static Retrofit getClient() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }

I have no idea where and how to implement those Service Generators and Authenticator. I have to pass "Authentication"=>ACCESSTOKEN in header with every API URL.

Body:
Please use below code to create your service:

public <S> S createService(Class<S> serviceClass, AuthToken authToken) {

            final String token = "Bearer" + " " + authToken.getAceessToken();
            Log.d("ServiceGenerator", "Token:::::::  " + token);

            httpClient.addInterceptor(chain -> {
                Request original = chain.request();

                // Request customization: add request headers
                Request.Builder requestBuilder = original.newBuilder()
                        .header(KEY_AUTH_HEADER, token).header("Content-Type", "application/json");

                Request request = requestBuilder.build();
                return chain.proceed(request);
            });

            Retrofit retrofit = builder.client(httpClient.build()).build();
            return retrofit.create(serviceClass);
        }

Add following line to call method:

 ApiService service = serviceGenerator.createService(ApiService.class, token);
        Call<ResponseBody> call = service.getMovielist(id);

serviceGenerator is the class where i have defined create service method.You can declare whenever you want.


问:
How can I make a series of steps for a progress bar in a multi-step form?
Currently I have the following code

```<code><div class="progress">
   <div class='progress-bar bar-style' role='progressbar' aria-valueactive='1' aria-valuemin='0' aria-valuemax="8" id='userProgress'>
       <span id="progressStatus"></span>
    </div>
</div>
</code>```

It produces a basic static nav that updates where I want and I am modifying the inside span with JS.

I want to build a label on top that shows the following:

Step 1: Setup

Step 2: Input Config

Step 3: Output Header

Step 4: Output Zip

The purpose is to be a static header over the progress bar of a multi-step form.
Issue is I have no idea how to code this, or how to even start. Bootstrap-3 doesn't seem to have any simple snippets for how to make one.

I'd assume I'd have some means of adding text above the nav and javascript change which text is highlighted on  form navigation? Can anyone share any links or point in the direction of some documentation to get started?

答:
You can try bootstrap multistep form example

//jQuery time
var current_fs, next_fs, previous_fs; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches

$(".next").click(function(){
 if(animating) return false;
 animating = true;

 current_fs = $(this).parent();
 next_fs = $(this).parent().next();

 //activate next step on progressbar using the index of next_fs
 $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

 //show the next fieldset
 next_fs.show();
 //hide the current fieldset with style
 current_fs.animate({opacity: 0}, {
  step: function(now, mx) {
   //as the opacity of current_fs reduces to 0 - stored in "now"
   //1. scale current_fs down to 80%
   scale = 1 - (1 - now) * 0.2;
   //2. bring next_fs from the right(50%)
   left = (now * 50)+"%";
   //3. increase opacity of next_fs to 1 as it moves in
   opacity = 1 - now;
   current_fs.css({
        'transform': 'scale('+scale+')',
        'position': 'absolute'
      });
   next_fs.css({'left': left, 'opacity': opacity});
  },
  duration: 800,
  complete: function(){
   current_fs.hide();
   animating = false;
  },
  //this comes from the custom easing plugin
  easing: 'easeInOutBack'
 });
});

$(".previous").click(function(){
 if(animating) return false;
 animating = true;

 current_fs = $(this).parent();
 previous_fs = $(this).parent().prev();

 //de-activate current step on progressbar
 $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

 //show the previous fieldset
 previous_fs.show();
 //hide the current fieldset with style
 current_fs.animate({opacity: 0}, {
  step: function(now, mx) {
   //as the opacity of current_fs reduces to 0 - stored in "now"
   //1. scale previous_fs from 80% to 100%
   scale = 0.8 + (1 - now) * 0.2;
   //2. take current_fs to the right(50%) - from 0%
   left = ((1-now) * 50)+"%";
   //3. increase opacity of previous_fs to 1 as it moves in
   opacity = 1 - now;
   current_fs.css({'left': left});
   previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});
  },
  duration: 800,
  complete: function(){
   current_fs.hide();
   animating = false;
  },
  //this comes from the custom easing plugin
  easing: 'easeInOutBack'
 });
});

$(".submit").click(function(){
 return false;
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*custom font*/
@import url(https://fonts.googleapis.com/css?family=Montserrat);

/*basic reset*/
* {
    margin: 0;
    padding: 0;
}

html {
    height: 100%;
    background: #6441A5; /* fallback for old browsers */
    background: -webkit-linear-gradient(to left, #6441A5, #2a0845); /* Chrome 10-25, Safari 5.1-6 */
}

body {
    font-family: montserrat, arial, verdana;
    background: transparent;
}

/*form styles*/
#msform {
    text-align: center;
    position: relative;
    margin-top: 30px;
}

#msform fieldset {
    background: white;
    border: 0 none;
    border-radius: 0px;
    box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4);
    padding: 20px 30px;
    box-sizing: border-box;
    width: 80%;
    margin: 0 10%;

    /*stacking fieldsets above each other*/
    position: relative;
}

/*Hide all except first fieldset*/
#msform fieldset:not(:first-of-type) {
    display: none;
}

/*inputs*/
#msform input, #msform textarea {
    padding: 15px;
    border: 1px solid #ccc;
    border-radius: 0px;
    margin-bottom: 10px;
    width: 100%;
    box-sizing: border-box;
    font-family: montserrat;
    color: #2C3E50;
    font-size: 13px;
}

#msform input:focus, #msform textarea:focus {
    -moz-box-shadow: none !important;
    -webkit-box-shadow: none !important;
    box-shadow: none !important;
    border: 1px solid #ee0979;
    outline-width: 0;
    transition: All 0.5s ease-in;
    -webkit-transition: All 0.5s ease-in;
    -moz-transition: All 0.5s ease-in;
    -o-transition: All 0.5s ease-in;
}

/*buttons*/
#msform .action-button {
    width: 100px;
    background: #ee0979;
    font-weight: bold;
    color: white;
    border: 0 none;
    border-radius: 25px;
    cursor: pointer;
    padding: 10px 5px;
    margin: 10px 5px;
}

#msform .action-button:hover, #msform .action-button:focus {
    box-shadow: 0 0 0 2px white, 0 0 0 3px #ee0979;
}

#msform .action-button-previous {
    width: 100px;
    background: #C5C5F1;
    font-weight: bold;
    color: white;
    border: 0 none;
    border-radius: 25px;
    cursor: pointer;
    padding: 10px 5px;
    margin: 10px 5px;
}

#msform .action-button-previous:hover, #msform .action-button-previous:focus {
    box-shadow: 0 0 0 2px white, 0 0 0 3px #C5C5F1;
}

/*headings*/
.fs-title {
    font-size: 18px;
    text-transform: uppercase;
    color: #2C3E50;
    margin-bottom: 10px;
    letter-spacing: 2px;
    font-weight: bold;
}

.fs-subtitle {
    font-weight: normal;
    font-size: 13px;
    color: #666;
    margin-bottom: 20px;
}

/*progressbar*/
#progressbar {
    margin-bottom: 30px;
    overflow: hidden;
    /*CSS counters to number the steps*/
    counter-reset: step;
}

#progressbar li {
    list-style-type: none;
    color: white;
    text-transform: uppercase;
    font-size: 9px;
    width: 33.33%;
    float: left;
    position: relative;
    letter-spacing: 1px;
}

#progressbar li:before {
    content: counter(step);
    counter-increment: step;
    width: 24px;
    height: 24px;
    line-height: 26px;
    display: block;
    font-size: 12px;
    color: #333;
    background: white;
    border-radius: 25px;
    margin: 0 auto 10px auto;
}

/*progressbar connectors*/
#progressbar li:after {
    content: '';
    width: 100%;
    height: 2px;
    background: white;
    position: absolute;
    left: -50%;
    top: 9px;
    z-index: -1; /*put it behind the numbers*/
}

#progressbar li:first-child:after {
    /*connector not needed before the first step*/
    content: none;
}

/*marking active/completed steps green*/
/*The number of the step and the connector before it = green*/
#progressbar li.active:before, #progressbar li.active:after {
    background: #ee0979;
    color: white;
}

/* Not relevant to this form */
.dme_link {
    margin-top: 30px;
    text-align: center;
}
.dme_link a {
    background: #FFF;
    font-weight: bold;
    color: #ee0979;
    border: 0 none;
    border-radius: 25px;
    cursor: pointer;
    padding: 5px 25px;
    font-size: 12px;
}

.dme_link a:hover, .dme_link a:focus {
    background: #C5C5F1;
    text-decoration: none;
}</code>```

        <form id="msform">

Personal Details

Social Profiles

Account Setup

            <fieldset>

Personal Details

Tell us something more about you

                <input type="text" name="fname" placeholder="First Name"/>
                <input type="text" name="lname" placeholder="Last Name"/>
                <input type="text" name="phone" placeholder="Phone"/>
                <input type="button" name="next" class="next action-button" value="Next"/>
            </fieldset>
            <fieldset>

Social Profiles

Your presence on the social network

                <input type="text" name="twitter" placeholder="Twitter"/>
                <input type="text" name="facebook" placeholder="Facebook"/>
                <input type="text" name="gplus" placeholder="Google Plus"/>
                <input type="button" name="previous" class="previous action-button-previous" value="Previous"/>
                <input type="button" name="next" class="next action-button" value="Next"/>
            </fieldset>
            <fieldset>

Create your account

Fill in your credentials

                <input type="text" name="email" placeholder="Email"/>
                <input type="password" name="pass" placeholder="Password"/>
                <input type="password" name="cpass" placeholder="Confirm Password"/>
                <input type="button" name="previous" class="previous action-button-previous" value="Previous"/>
                <input type="submit" name="submit" class="submit action-button" value="Submit"/>
            </fieldset>
        </form>

More Code Snippets

```

Body:
Currently I have the following code

It produces a basic static nav that updates where I want and I am modifying the inside span with JS.

I want to build a label on top that shows the following:

Step 1: Setup

Step 2: Input Config

Step 3: Output Header

Step 4: Output Zip

The purpose is to be a static header over the progress bar of a multi-step form.
Issue is I have no idea how to code this, or how to even start. Bootstrap-3 doesn't seem to have any simple snippets for how to make one.

I'd assume I'd have some means of adding text above the nav and javascript change which text is highlighted on  form navigation? Can anyone share any links or point in the direction of some documentation to get started?

Body:
You can try bootstrap multistep form example

//jQuery time
var current_fs, next_fs, previous_fs; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches

$(".next").click(function(){
 if(animating) return false;
 animating = true;

 current_fs = $(this).parent();
 next_fs = $(this).parent().next();

 //activate next step on progressbar using the index of next_fs
 $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

 //show the next fieldset
 next_fs.show();
 //hide the current fieldset with style
 current_fs.animate({opacity: 0}, {
  step: function(now, mx) {
   //as the opacity of current_fs reduces to 0 - stored in "now"
   //1. scale current_fs down to 80%
   scale = 1 - (1 - now) * 0.2;
   //2. bring next_fs from the right(50%)
   left = (now * 50)+"%";
   //3. increase opacity of next_fs to 1 as it moves in
   opacity = 1 - now;
   current_fs.css({
        'transform': 'scale('+scale+')',
        'position': 'absolute'
      });
   next_fs.css({'left': left, 'opacity': opacity});
  },
  duration: 800,
  complete: function(){
   current_fs.hide();
   animating = false;
  },
  //this comes from the custom easing plugin
  easing: 'easeInOutBack'
 });
});

$(".previous").click(function(){
 if(animating) return false;
 animating = true;

 current_fs = $(this).parent();
 previous_fs = $(this).parent().prev();

 //de-activate current step on progressbar
 $("#progressbar li").eq($("fieldset").index(current_fs)).removeClass("active");

 //show the previous fieldset
 previous_fs.show();
 //hide the current fieldset with style
 current_fs.animate({opacity: 0}, {
  step: function(now, mx) {
   //as the opacity of current_fs reduces to 0 - stored in "now"
   //1. scale previous_fs from 80% to 100%
   scale = 0.8 + (1 - now) * 0.2;
   //2. take current_fs to the right(50%) - from 0%
   left = ((1-now) * 50)+"%";
   //3. increase opacity of previous_fs to 1 as it moves in
   opacity = 1 - now;
   current_fs.css({'left': left});
   previous_fs.css({'transform': 'scale('+scale+')', 'opacity': opacity});
  },
  duration: 800,
  complete: function(){
   current_fs.hide();
   animating = false;
  },
  //this comes from the custom easing plugin
  easing: 'easeInOutBack'
 });
});

$(".submit").click(function(){
 return false;
})

/*custom font*/
@import url(https://fonts.googleapis.com/css?family=Montserrat);

/*basic reset*/
* {
    margin: 0;
    padding: 0;
}

html {
    height: 100%;
    background: #6441A5; /* fallback for old browsers */
    background: -webkit-linear-gradient(to left, #6441A5, #2a0845); /* Chrome 10-25, Safari 5.1-6 */
}

body {
    font-family: montserrat, arial, verdana;
    background: transparent;
}

/*form styles*/
#msform {
    text-align: center;
    position: relative;
    margin-top: 30px;
}

#msform fieldset {
    background: white;
    border: 0 none;
    border-radius: 0px;
    box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4);
    padding: 20px 30px;
    box-sizing: border-box;
    width: 80%;
    margin: 0 10%;

    /*stacking fieldsets above each other*/
    position: relative;
}

/*Hide all except first fieldset*/
#msform fieldset:not(:first-of-type) {
    display: none;
}

/*inputs*/
#msform input, #msform textarea {
    padding: 15px;
    border: 1px solid #ccc;
    border-radius: 0px;
    margin-bottom: 10px;
    width: 100%;
    box-sizing: border-box;
    font-family: montserrat;
    color: #2C3E50;
    font-size: 13px;
}

#msform input:focus, #msform textarea:focus {
    -moz-box-shadow: none !important;
    -webkit-box-shadow: none !important;
    box-shadow: none !important;
    border: 1px solid #ee0979;
    outline-width: 0;
    transition: All 0.5s ease-in;
    -webkit-transition: All 0.5s ease-in;
    -moz-transition: All 0.5s ease-in;
    -o-transition: All 0.5s ease-in;
}

/*buttons*/
#msform .action-button {
    width: 100px;
    background: #ee0979;
    font-weight: bold;
    color: white;
    border: 0 none;
    border-radius: 25px;
    cursor: pointer;
    padding: 10px 5px;
    margin: 10px 5px;
}

#msform .action-button:hover, #msform .action-button:focus {
    box-shadow: 0 0 0 2px white, 0 0 0 3px #ee0979;
}

#msform .action-button-previous {
    width: 100px;
    background: #C5C5F1;
    font-weight: bold;
    color: white;
    border: 0 none;
    border-radius: 25px;
    cursor: pointer;
    padding: 10px 5px;
    margin: 10px 5px;
}

#msform .action-button-previous:hover, #msform .action-button-previous:focus {
    box-shadow: 0 0 0 2px white, 0 0 0 3px #C5C5F1;
}

/*headings*/
.fs-title {
    font-size: 18px;
    text-transform: uppercase;
    color: #2C3E50;
    margin-bottom: 10px;
    letter-spacing: 2px;
    font-weight: bold;
}

.fs-subtitle {
    font-weight: normal;
    font-size: 13px;
    color: #666;
    margin-bottom: 20px;
}

/*progressbar*/
#progressbar {
    margin-bottom: 30px;
    overflow: hidden;
    /*CSS counters to number the steps*/
    counter-reset: step;
}

#progressbar li {
    list-style-type: none;
    color: white;
    text-transform: uppercase;
    font-size: 9px;
    width: 33.33%;
    float: left;
    position: relative;
    letter-spacing: 1px;
}

#progressbar li:before {
    content: counter(step);
    counter-increment: step;
    width: 24px;
    height: 24px;
    line-height: 26px;
    display: block;
    font-size: 12px;
    color: #333;
    background: white;
    border-radius: 25px;
    margin: 0 auto 10px auto;
}

/*progressbar connectors*/
#progressbar li:after {
    content: '';
    width: 100%;
    height: 2px;
    background: white;
    position: absolute;
    left: -50%;
    top: 9px;
    z-index: -1; /*put it behind the numbers*/
}

#progressbar li:first-child:after {
    /*connector not needed before the first step*/
    content: none;
}

/*marking active/completed steps green*/
/*The number of the step and the connector before it = green*/
#progressbar li.active:before, #progressbar li.active:after {
    background: #ee0979;
    color: white;
}

/* Not relevant to this form */
.dme_link {
    margin-top: 30px;
    text-align: center;
}
.dme_link a {
    background: #FFF;
    font-weight: bold;
    color: #ee0979;
    border: 0 none;
    border-radius: 25px;
    cursor: pointer;
    padding: 5px 25px;
    font-size: 12px;
}

.dme_link a:hover, .dme_link a:focus {
    background: #C5C5F1;
    text-decoration: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<!-- MultiStep Form -->
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <form id="msform">
            <!-- progressbar -->
            <ul id="progressbar">
                <li class="active">Personal Details</li>
                <li>Social Profiles</li>
                <li>Account Setup</li>
            </ul>
            <!-- fieldsets -->
            <fieldset>
                <h2 class="fs-title">Personal Details</h2>
                <h3 class="fs-subtitle">Tell us something more about you</h3>
                <input type="text" name="fname" placeholder="First Name"/>
                <input type="text" name="lname" placeholder="Last Name"/>
                <input type="text" name="phone" placeholder="Phone"/>
                <input type="button" name="next" class="next action-button" value="Next"/>
            </fieldset>
            <fieldset>
                <h2 class="fs-title">Social Profiles</h2>
                <h3 class="fs-subtitle">Your presence on the social network</h3>
                <input type="text" name="twitter" placeholder="Twitter"/>
                <input type="text" name="facebook" placeholder="Facebook"/>
                <input type="text" name="gplus" placeholder="Google Plus"/>
                <input type="button" name="previous" class="previous action-button-previous" value="Previous"/>
                <input type="button" name="next" class="next action-button" value="Next"/>
            </fieldset>
            <fieldset>
                <h2 class="fs-title">Create your account</h2>
                <h3 class="fs-subtitle">Fill in your credentials</h3>
                <input type="text" name="email" placeholder="Email"/>
                <input type="password" name="pass" placeholder="Password"/>
                <input type="password" name="cpass" placeholder="Confirm Password"/>
                <input type="button" name="previous" class="previous action-button-previous" value="Previous"/>
                <input type="submit" name="submit" class="submit action-button" value="Submit"/>
            </fieldset>
        </form>
        <!-- link to designify.me code snippets -->
        <div class="dme_link">
            <p><a href="http://designify.me/code-snippets-js/" target="_blank">More Code Snippets</a></p>
        </div>
        <!-- /.link to designify.me code snippets -->
    </div>
</div>
<!-- /.MultiStep Form -->


问:
Can't get an object's class name in Python
I'm using isinstance to check argument types, but I can't find the class name of a regex pattern object:

```<code>>>> import re
>>> x = re.compile('test')
>>> x.__class__.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __class__
</code>```

...

```<code>>>> type(x)
<type '_sre.SRE_Pattern'>
>>> isinstance(x, _sre.SRE_Pattern)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_sre' is not defined
>>>
>>>
>>> isinstance(x, '_sre.SRE_Pattern')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
>>>
</code>```

Any ideas?

答:
You could do this:

```<code>import re

pattern_type = type(re.compile("foo"))

if isinstance(your_object, pattern_type):
   print "It's a pattern object!"
</code>```

The idiomatic way would be to try to use it as a pattern object, and then handle the resulting exception if it is not.

ContentLicense: CC BY-SA 2.5

Body:
I'm using isinstance to check argument types, but I can't find the class name of a regex pattern object:

>>> import re
>>> x = re.compile('test')
>>> x.__class__.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __class__

...

>>> type(x)
<type '_sre.SRE_Pattern'>
>>> isinstance(x, _sre.SRE_Pattern)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_sre' is not defined
>>>
>>>
>>> isinstance(x, '_sre.SRE_Pattern')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
>>>

Any ideas?

Body:
You could do this:

import re

pattern_type = type(re.compile("foo"))

if isinstance(your_object, pattern_type):
   print "It's a pattern object!"

The idiomatic way would be to try to use it as a pattern object, and then handle the resulting exception if it is not.


问:
How to print Chinese characters in text file
I am reading the data From text file and Printing in HTML file using java and Html code, But junk characters printing in HTML file

report.reportGenerator("result.txt", reportHTMLFile, testCaseSheetMasterMap, environmentUrl, "01/01/01", "02/02/02");

StringBuilder htmlStringBuilder = new StringBuilder();

        // append html header and title
        //<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
        htmlStringBuilder.append(
                " <meta charset=\"UTF-8\"><title>CitiGR Automation Report</title>");
        // append body
        htmlStringBuilder.append("");
        htmlStringBuilder.append("

" + pageTitle + "

");
        htmlStringBuilder.append("
Environment URL : "+environmentUrl+"");
        htmlStringBuilder.append("

Start Run Time: "+startRunTime);
        htmlStringBuilder.append("
End  Run Time  : "+endRunTime+"
");

        /* append 1st table */
        htmlStringBuilder.append(
                "
<col width=\"50\"><col width=\"200\"><col width=\"200\"><col width=\"100\"><col width=\"100\"><col width=\"100\"><col width=\"100\">");
        // append row - table header
        htmlStringBuilder.append(
                "
"
                + "Si.No.	"
                + "TestCase Name	"
                + "Total no. of scripts executed	"
                + "Pass	"
                + "Fail	"
                + "Pass %	"
                + "Fail %	"
                + "
");

        int count=1;
        for (int i = 0; i < eachTestCaseMenuList.size(); ) {
            htmlStringBuilder.append(""
                    + "
"
                    + ""+count+"	"
                    + ""+ eachTestCaseMenuList.get(i) + "	"
                    + ""+ eachTestCaseMenuList.get(i+1) + "	"
                    + "" + eachTestCaseMenuList.get(i+2)+ "	"
                    + "" + eachTestCaseMenuList.get(i+3) + "	"
                    + "" + eachTestCaseMenuList.get(i+4)+ "	"
                    + "" + eachTestCaseMenuList.get(i+5) + "	"
                    + "
");
            i+=6;
            count++;
        }

        htmlStringBuilder.append(
                "
"
                + "	"
                + "Total	"
                + ""+totalTestCaseCount+"	"
                + ""+totalPassCount+"	"
                + ""+totalFailCount+"	"
                + ""+totalPassPercent+" %	"
                + ""+totalFailPercent+" %	"
                + "
");
```

答:
Short:

```<code><meta charset="utf-8" />
</code>```

Long:

```<code><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</code>```

Body:
Short:

<meta charset="utf-8" />

Long:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


问:
getting React elements offsetTop
in react when I get the offsetTop of the element in the componentDidMount is different than the offsetTop value of the same element when called in componentDidUpdate(). Why is that? I thought componentDidMount is called after render so the DOM elements are placed in the page so the offsetTop value should be correct.</p>

```<code>class Index extends React.Component {
    ...
    render() {
        return (
            <div className="site-wrapper">
                <TopHeader />
                <IntroSection />
            </div>
        );
    }
}

class TopHeader extends React.Component {
    ...
    componentDidMount() {
        var rect = ReactDOM.findDOMNode(this).offsetTop;
        console.log(rect);
    }
}

class IntroSection extends React.Component {
    ...
    componentDidMount() {
        var rect = ReactDOM.findDOMNode(this).offsetTop;
        console.log(rect);
    }
}
</code>```

答:
componentDidMount is called once and only one . However, componentDidUpdate is called for each update that component received , even through state or props.

Then , we recommend to persist the offsetTop in the component state for both lifecycle methods .

Title: getting React elements offsetTop

Body:
in react when I get the offsetTop of the element in the componentDidMount is different than the offsetTop value of the same element when called in componentDidUpdate(). Why is that? I thought componentDidMount is called after render so the DOM elements are placed in the page so the offsetTop value should be correct.

class Index extends React.Component {
    ...
    render() {
        return (

                <TopHeader />
                <IntroSection />

        );
    }
}

class TopHeader extends React.Component {
    ...
    componentDidMount() {
        var rect = ReactDOM.findDOMNode(this).offsetTop;
        console.log(rect);
    }
}

class IntroSection extends React.Component {
    ...
    componentDidMount() {
        var rect = ReactDOM.findDOMNode(this).offsetTop;
        console.log(rect);
    }
}


Title: Multiply the values for each row in two different dataframes

Body:
I'm building genetic algorithm to feature selection in python. I have extracted features from my datas, then I divided into two dataframe, 'train' and 'test' dataframe.
How can I multiple the values for each row in 'population' dataframe (each individu) and 'train' dataframe?

'train' dataframe:

   feature0   feature1   feature2   feature3   feature4   feature5
0  18.279579  -3.921346  13.611829  -7.250185 -11.773605 -18.265003
1  17.899545 -15.503942  -0.741729  -0.053619  -6.734652   4.398419
4  16.432750 -22.490190  -4.611659 -15.247781 -13.941488  -2.433374
5  15.905368  -4.812785  18.291712   3.742221   3.631887  -1.074326
6  16.991823 -15.946251   8.299577   8.057511   8.057510  -1.482333

'population' dataframe:

      0     1     2     3     4     5
0     1     1     0     0     0     1
1     0     1     0     1     0     0
2     0     0     0     0     0     1
3     0     0     1     0     1     1

Multiplying each row in 'population' to all rows in 'train'.
It will results:

1) From population row 1:

   feature0   feature1   feature2   feature3   feature4   feature5
0  18.279579  -3.921346          0          0          0 -18.265003
1  17.899545 -15.503942          0          0          0   4.398419
4  16.432750 -22.490190          0          0          0  -2.433374
5  15.905368  -4.812785          0          0          0  -1.074326
6  16.991823 -15.946251          0          0          0  -1.482333

2) From population row 2:

   feature0   feature1   feature2   feature3   feature4   feature5
0          0  -3.921346          0  -7.250185          0          0
1          0 -15.503942          0  -0.053619          0          0
4          0 -22.490190          0 -15.247781          0          0
5          0  -4.812785          0   3.742221          0          0
6          0 -15.946251          0   8.057511          0          0

And so on...

Body:
If need loop (slow if large data):

for i, x in population.iterrows():
    print (train * x.values)

    feature0   feature1  feature2  feature3  feature4   feature5
0  18.279579  -3.921346       0.0      -0.0      -0.0 -18.265003
1  17.899545 -15.503942      -0.0      -0.0      -0.0   4.398419
4  16.432750 -22.490190      -0.0      -0.0      -0.0  -2.433374
5  15.905368  -4.812785       0.0       0.0       0.0  -1.074326
6  16.991823 -15.946251       0.0       0.0       0.0  -1.482333
   feature0   feature1  feature2   feature3  feature4  feature5
0       0.0  -3.921346       0.0  -7.250185      -0.0      -0.0
1       0.0 -15.503942      -0.0  -0.053619      -0.0       0.0
4       0.0 -22.490190      -0.0 -15.247781      -0.0      -0.0
5       0.0  -4.812785       0.0   3.742221       0.0      -0.0
6       0.0 -15.946251       0.0   8.057511       0.0      -0.0
   feature0  feature1  feature2  feature3  feature4   feature5
0       0.0      -0.0       0.0      -0.0      -0.0 -18.265003
1       0.0      -0.0      -0.0      -0.0      -0.0   4.398419
4       0.0      -0.0      -0.0      -0.0      -0.0  -2.433374
5       0.0      -0.0       0.0       0.0       0.0  -1.074326
6       0.0      -0.0       0.0       0.0       0.0  -1.482333
   feature0  feature1   feature2  feature3   feature4   feature5
0       0.0      -0.0  13.611829      -0.0 -11.773605 -18.265003
1       0.0      -0.0  -0.741729      -0.0  -6.734652   4.398419
4       0.0      -0.0  -4.611659      -0.0 -13.941488  -2.433374
5       0.0      -0.0  18.291712       0.0   3.631887  -1.074326
6       0.0      -0.0   8.299577       0.0   8.057510  -1.482333

Or each row separately:

print (train * population.values[0])

    feature0   feature1  feature2  feature3  feature4   feature5
0  18.279579  -3.921346       0.0      -0.0      -0.0 -18.265003
1  17.899545 -15.503942      -0.0      -0.0      -0.0   4.398419
4  16.432750 -22.490190      -0.0      -0.0      -0.0  -2.433374
5  15.905368  -4.812785       0.0       0.0       0.0  -1.074326
6  16.991823 -15.946251       0.0       0.0       0.0  -1.482333

Or for MultiIndex DataFrame:

d = pd.concat([train * population.values[i] for i in range(population.shape[0])],
               keys=population.index.tolist())
print (d)

      feature0   feature1   feature2   feature3   feature4   feature5
0 0  18.279579  -3.921346   0.000000  -0.000000  -0.000000 -18.265003
  1  17.899545 -15.503942  -0.000000  -0.000000  -0.000000   4.398419
  4  16.432750 -22.490190  -0.000000  -0.000000  -0.000000  -2.433374
  5  15.905368  -4.812785   0.000000   0.000000   0.000000  -1.074326
  6  16.991823 -15.946251   0.000000   0.000000   0.000000  -1.482333
1 0   0.000000  -3.921346   0.000000  -7.250185  -0.000000  -0.000000
  1   0.000000 -15.503942  -0.000000  -0.053619  -0.000000   0.000000
  4   0.000000 -22.490190  -0.000000 -15.247781  -0.000000  -0.000000
  5   0.000000  -4.812785   0.000000   3.742221   0.000000  -0.000000
  6   0.000000 -15.946251   0.000000   8.057511   0.000000  -0.000000
2 0   0.000000  -0.000000   0.000000  -0.000000  -0.000000 -18.265003
  1   0.000000  -0.000000  -0.000000  -0.000000  -0.000000   4.398419
  4   0.000000  -0.000000  -0.000000  -0.000000  -0.000000  -2.433374
  5   0.000000  -0.000000   0.000000   0.000000   0.000000  -1.074326
  6   0.000000  -0.000000   0.000000   0.000000   0.000000  -1.482333
3 0   0.000000  -0.000000  13.611829  -0.000000 -11.773605 -18.265003
  1   0.000000  -0.000000  -0.741729  -0.000000  -6.734652   4.398419
  4   0.000000  -0.000000  -4.611659  -0.000000 -13.941488  -2.433374
  5   0.000000  -0.000000  18.291712   0.000000   3.631887  -1.074326
  6   0.000000  -0.000000   8.299577   0.000000   8.057510  -1.482333

And select by xs:

print (d.xs(0))

    feature0   feature1  feature2  feature3  feature4   feature5
0  18.279579  -3.921346       0.0      -0.0      -0.0 -18.265003
1  17.899545 -15.503942      -0.0      -0.0      -0.0   4.398419
4  16.432750 -22.490190      -0.0      -0.0      -0.0  -2.433374
5  15.905368  -4.812785       0.0       0.0       0.0  -1.074326
6  16.991823 -15.946251       0.0       0.0       0.0  -1.482333


问:
How to close one of several opened projects in PyCharm?
I have opened 2 projects in one PyCharm window. Projects are dependent.

When I close and then open one of the projects, the other one opens too. Even after I removed the dependency.

How to detach them now? How to close one of the projects?

答:
From Deleting a project from view:

If you want to close a project that has been added to the currently
  opened one (primary project), follow these steps:

In the Project Tool Window, right-click the project to be deleted.

On the context menu of the selection, choose Remove from Project View, or just press Delete:

You might find the entire Opening Multiple Projects of interest.


问:
Warning the selected directory is not a valid tomcat home
I installed Tomcat with home brew brew install tomcat. On Selecting Tomcat server to add a server to the application server I get this

Warning the selected directory is not a valid tomcat home.

However, running catalina start starts the tomcat server on my terminal.

答:
If you are using IDEA on Linux platform, use the command:

chmod 755 -R apache-tomcat-<<Your-tomcat-version>>

Then try to restart your service again.

ContentLicense: CC BY-SA 4.0


问:
Accessing Bluetooth dongle from inside Docker?
Is it possible to use a bluetooth (BLE in my case) dongle inside of a docker container?

On my host machine:

```<code>$ hcitool dev
    Devices:
       hci0   5C:F3:70:64:F0:11
</code>```

Inside of Docker it doesn't find anything. I'm running Docker as:

```<code>sudo docker run --privileged -i -t ubuntu /bin/bash
</code>```

I don't know enough about the bluetooth subsystem in Linux to understand what is different between the host and docker.

The hci0 device does show up in both systems:

```<code>$ ls -l /sys/class/bluetooth
lrwxrwxrwx  1 root root 0 Mar  5 01:23 hci0 -> ../../devices/pci0000:00/0000:00:11.0/0000:02:00.0/usb2/2-2/2-2.3/2-2.3:1.0/bluetooth/hci0
</code>```

Anyone try to use bluetooth inside of Docker?

答:
With help from Docker Community, I have Successfully Started DBus/Bluetooth Services inside docker container and scan bluetooth devices by adding --cap-add=SYS_ADMIN, --cap-add=NET_ADMIN and --net=host flags/permission

docker run --cap-add=SYS_ADMIN --cap-add=NET_ADMIN --net=host -it debian:jessie

Now just looking to start bluetooth service by "Not sharing the Host Networking Namespace" (customising --net=host to private network)

If somebody got any Clue, that would be helpful. Thanks.

Body:
Is it possible to use a bluetooth (BLE in my case) dongle inside of a docker container?

On my host machine:

$ hcitool dev
    Devices:
       hci0   5C:F3:70:64:F0:11

Inside of Docker it doesn't find anything. I'm running Docker as:

sudo docker run --privileged -i -t ubuntu /bin/bash

I don't know enough about the bluetooth subsystem in Linux to understand what is different between the host and docker.

The hci0 device does show up in both systems:

$ ls -l /sys/class/bluetooth
lrwxrwxrwx  1 root root 0 Mar  5 01:23 hci0 -> ../../devices/pci0000:00/0000:00:11.0/0000:02:00.0/usb2/2-2/2-2.3/2-2.3:1.0/bluetooth/hci0

Anyone try to use bluetooth inside of Docker?


问:
Android: Throw OutOfMemory Exception during getting bitmap from file object
I am trying to load bitmap image from file in some devices my code is working perfectly but on the other device it gives OutOfMemory exception.</p>

```<code>String filePath  = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA));

fileName.add(filePath);

File file = new File(filePath);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
bitmapArray.add(myBitmap);
</code>```

答:
You can find out the size of the bitmap:

```<code>BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
</code>```

and then compress it to the desired size by setting sampleSize:

```<code>options = new BitmapFactory.Options();
options.inSampleSize = desired_scale_value;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
</code>```

And don`t forget to load bitmaps in non ui thread.

Body:
I am trying to load bitmap image from file in some devices my code is working perfectly but on the other device it gives OutOfMemory exception.

String filePath  = mediaCursor.getString(mediaCursor.getColumnIndex(MediaStore.Images.Thumbnails.DATA));

fileName.add(filePath);

File file = new File(filePath);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
bitmapArray.add(myBitmap);

Body:
You can find out the size of the bitmap:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;

and then compress it to the desired size by setting sampleSize:

options = new BitmapFactory.Options();
options.inSampleSize = desired_scale_value;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

And don`t forget to load bitmaps in non ui thread.


问:
python unicode convert to Japanese character
I am trying to convert u'\u30c9\u30e9\u30b4\u30f3' to japanese character using python

here is my sample code

```<code>s = u'\u30c9\u30e9\u30b4\u30f3'.encode('utf-8')
print str(s)
</code>```

I got this error
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

答: You get s in bytes. To get the Japanese characters, use print(s.decode('utf-8')).

Body:
I am trying to convert u'\u30c9\u30e9\u30b4\u30f3' to japanese character using python

here is my sample code

s = u'\u30c9\u30e9\u30b4\u30f3'.encode('utf-8')
print str(s)

I got this error
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)


问:
How to avoid time conflict or overlap for CalDAV?
I am studying CalDAV protocol.

I have some question for time conflict or overlap for CalDAV.

Let me explain by instance for some scenario.
I made an event PM1 ~ PM6 in calendar. And then I try to made another event PM2~7 in same calendar. It is time conflict or overlap.

How does CalDav server resolve this conflict? Does server make error when second event make?

I did search out RFC 6638. But I could not find solution.
Please help my question.

Thanks for reading.

答:
It is up to the CalDAV client to decide how to behave when overlap is involved.
If the client decides to write an event that overlaps another the server will write the overlapping event.

When scheduling is involved (userA wants to invite userB to a meeting but would like to avoid picking a time slot that is already busy in userB's calendar) the CalDAV client can query the FREEBUSY status for a user (see RFC 4791). There's also availability which allows a CalDAV client to retrieve a user's availability (think business hours).


Body:
Once you set the columns of population to match train you can use *:

In [11]: population.columns = train.columns

In [12]: train * population.iloc[0]
Out[12]:
    feature0   feature1  feature2  feature3  feature4   feature5
0  18.279579  -3.921346       0.0      -0.0      -0.0 -18.265003
1  17.899545 -15.503942      -0.0      -0.0      -0.0   4.398419
4  16.432750 -22.490190      -0.0      -0.0      -0.0  -2.433374
5  15.905368  -4.812785       0.0       0.0       0.0  -1.074326
6  16.991823 -15.946251       0.0       0.0       0.0  -1.482333

You can make a MultiIndex (as recommended by @jezrael) very efficiently using np.tile and np.repeat:

In [11]: res = population.iloc[np.repeat(np.arange(len(population)), len(train))]

In [12]: res = res.set_index(np.tile(train.index, len(population)), append=True)

In [13]: res
Out[13]:
     feature0  feature1  feature2  feature3  feature4  feature5
0 0         1         1         0         0         0         1
  1         1         1         0         0         0         1
  4         1         1         0         0         0         1
  5         1         1         0         0         0         1
  6         1         1         0         0         0         1
1 0         0         1         0         1         0         0
  1         0         1         0         1         0         0
  4         0         1         0         1         0         0
  5         0         1         0         1         0         0
  6         0         1         0         1         0         0
2 0         0         0         0         0         0         1
  1         0         0         0         0         0         1
  4         0         0         0         0         0         1
  5         0         0         0         0         0         1
  6         0         0         0         0         0         1
3 0         0         0         1         0         1         1
  1         0         0         1         0         1         1
  4         0         0         1         0         1         1
  5         0         0         1         0         1         1
  6         0         0         1         0         1         1

In [14]: res.mul(train, level=1)
Out[14]:
      feature0   feature1   feature2   feature3   feature4   feature5
0 0  18.279579  -3.921346   0.000000  -0.000000  -0.000000 -18.265003
  1  17.899545 -15.503942  -0.000000  -0.000000  -0.000000   4.398419
  4  16.432750 -22.490190  -0.000000  -0.000000  -0.000000  -2.433374
  5  15.905368  -4.812785   0.000000   0.000000   0.000000  -1.074326
  6  16.991823 -15.946251   0.000000   0.000000   0.000000  -1.482333
1 0   0.000000  -3.921346   0.000000  -7.250185  -0.000000  -0.000000
  1   0.000000 -15.503942  -0.000000  -0.053619  -0.000000   0.000000
  4   0.000000 -22.490190  -0.000000 -15.247781  -0.000000  -0.000000
  5   0.000000  -4.812785   0.000000   3.742221   0.000000  -0.000000
  6   0.000000 -15.946251   0.000000   8.057511   0.000000  -0.000000
2 0   0.000000  -0.000000   0.000000  -0.000000  -0.000000 -18.265003
  1   0.000000  -0.000000  -0.000000  -0.000000  -0.000000   4.398419
  4   0.000000  -0.000000  -0.000000  -0.000000  -0.000000  -2.433374
  5   0.000000  -0.000000   0.000000   0.000000   0.000000  -1.074326
  6   0.000000  -0.000000   0.000000   0.000000   0.000000  -1.482333
3 0   0.000000  -0.000000  13.611829  -0.000000 -11.773605 -18.265003
  1   0.000000  -0.000000  -0.741729  -0.000000  -6.734652   4.398419
  4   0.000000  -0.000000  -4.611659  -0.000000 -13.941488  -2.433374
  5   0.000000  -0.000000  18.291712   0.000000   3.631887  -1.074326
  6   0.000000  -0.000000   8.299577   0.000000   8.057510  -1.482333


问:
Which function does R call to print output to console (e. g. for sessionInfo)?
I was trying to store the pretty-printed (formatted) output of sessionInfo in a character variable and have found a solution using pretty.si <-capture.output(sessionInfo()) which results in a vector of character strings (one element per line).

Just out of curiosity:

Which function is called by R to get the pretty-printed output (e. g. I couldn't find a S3 print.sessionInfo function)?

If I look into the implementation of sessionInfo it just returns the unformatted result as list of lists or vectors:

```<code>> sessionInfo
function (package = NULL)
{
    z <- list()
    z$R.version <- R.Version()
    z$platform <- z$R.version$platform
    # ... omitted code ...
    class(z) <- "sessionInfo"
    z
}
</code>```

Edit 1: BTW - To create a pretty-printed string from sessionInfo() you can use:

```<code>si <- capture.output(print(sessionInfo()))
</code>```

答:
It does actually have an S3 method, it's just not exported from the package namespace which would be the utils package.

If you look through the output of the methods search you will see an asterix next to the sessionInfo method, which the documentation says is:

The S3 method name is followed by an asterisk * if the method
  definition is not exported from the package namespace in which the
  method is defined.

```<code>> x = methods("print")
> x[x == "print.sessionInfo"]
[1] "print.sessionInfo"
</code>```

therefore to see the code of the method you can do

```<code>utils:::print.sessionInfo
</code>```

Body:
I was trying to store the pretty-printed (formatted) output of sessionInfo in a character variable and have found a solution using pretty.si <-capture.output(sessionInfo()) which results in a vector of character strings (one element per line).

Just out of curiosity:

Which function is called by R to get the pretty-printed output (e. g. I couldn't find a S3 print.sessionInfo function)?

If I look into the implementation of sessionInfo it just returns the unformatted result as list of lists or vectors:

> sessionInfo
function (package = NULL)
{
    z <- list()
    z$R.version <- R.Version()
    z$platform <- z$R.version$platform
    # ... omitted code ...
    class(z) <- "sessionInfo"
    z
}

Edit 1: BTW - To create a pretty-printed string from sessionInfo() you can use:

si <- capture.output(print(sessionInfo()))

Body:
It does actually have an S3 method, it's just not exported from the package namespace which would be the utils package.

If you look through the output of the methods search you will see an asterix next to the sessionInfo method, which the documentation says is:

The S3 method name is followed by an asterisk * if the method
  definition is not exported from the package namespace in which the
  method is defined.

> x = methods("print")
> x[x == "print.sessionInfo"]
[1] "print.sessionInfo"

therefore to see the code of the method you can do

utils:::print.sessionInfo


问:
PHP Automated Deployment and Testing
I asked a question here on automated deployment of automatically deploying java code.

Our back-end Java API is accessed by a PHP web app. It would be nice to be able to automatically deploy this web app (along with static files like CSS, JS and images) to our web server while performing automatic testing on PHP code. Is there something similar to this for PHP?

I also wonder if as part of this automated testing you can check that each actual page loads without a fatal error. I am sure I read about a google project which allows you to write page tests e.g. click on link a, go to page b etc etc.

Thanks

答:
Maybe this question handling deployment strategies can help you.

Additionally, but maybe gone too far, tools like cruise control may help you to apply continuous integration, too.

PHPUnit with ant was my way to go for automated testing, which could be a vaild option for you, too since you're obviously using some java already :)

Title: PHP Automated Deployment and Testing


问:
IoT project with raspberry-pi3 and Bluemix. Error : TwilioRestClient has been removed from this version of the library
I'm doing a Internet of Thing(IoT) project, and I follow a sample from below sources. But I fail at last step when I push to start this app.
https://www.ibm.com/blogs/bluemix/2015/04/tutorial-using-a-raspberry-pi-python-iot-twilio-bluemix/

1. I am using 'cf push to start the app', it works until crash.
2. I am using 'cf logs python-iot-hackathon2 --recent' to see logs, and there are two errors

3. There is a python code that given from tutorial source, i think i should edit the code from line7~12, but I do not know how. If there is another problem, please teach me how to do it. Thanks.

ex. There are two error, if you can not see clearly.
1.
Err: You must give at least one requirement to install (see "pip help install")

2.
Err: Traceback (most recent call last):
Err: File "server.py". line12, in
Err: twilioClient = TwilioRestClient(twilio Account, twilio Token)
ERR: File "/home/vcap/deps/0/python/lib/python2.7/site-packages/twilio/base/obsolete.py", line 20. in new_func
Err:   .format(func.name)
Err: twilio.base.obsolete.obsoleteException:
TwilioRestClient has been removed from this version of the library. Please refer to current documentation for guidance.

答:
For: 1. Err: You must give at least one requirement to install (see "pip help install")

You need to run this on the Raspberry PI:

sudo pip install twilio

If you don't have pip installed then run:

sudo apt-get install python3-pip

and then again: sudo pip install twilio

for 2. Err: Traceback (most recent call last): Err: File "server.py". line12

Basically the twilio client definition needs to be similar to:

from twilio.rest import Client

client = Client(account_sid, auth_token)

so from the trace, line 12 in server.py  should be similar to

from twilio.rest import Client //this should be also changed

twilioClient = Client(account_sid, auth_token) //this is line 12


问:
distinct, max and group by query in sql
I have a dataset like:

```<code>list1     list2
a          e
a          e
b          w
a          e
a          r
b          c
</code>```

I want to find most frequent item in list2 grouped by list1.

```<code>list1     list2    max
  a         e       3
  b         w       1
</code>```

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

```<code>SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2
</code>```

答:
Try with this query:

Q1:

```<code>SELECT list1, count(list2) AS value_count FROM table GROUP BY list1;
</code>```

This will give you all list1 existance;

Q2:

```<code>`SELECT list1, max(list2), count(list2) AS value_count FROM table GROUP BY list1,list2`;
</code>```

This will give you all list1existance only with max(list2).

Title: distinct, max and group by query in sql

Body:
I have a dataset like:

list1     list2
a          e
a          e
b          w
a          e
a          r
b          c

I want to find most frequent item in list2 grouped by list1.

list1     list2    max
  a         e       3
  b         w       1

How can I get rid of the equal number of elements like b,w,1 and b,c,1 ?
I want to have one of them at random.

I tried something like this

SELECT clf1 as clf2, first(value_count) as max_value
FROM (SELECT list1 as clf1, list2, count(list2) AS value_count FROM table GROUP BY list2,clf1 order by value_count desc)
GROUP BY clf2

Body:
Try with this query:

Q1:

SELECT list1, count(list2) AS value_count FROM table GROUP BY list1;

This will give you all list1 existance;

Q2:

`SELECT list1, max(list2), count(list2) AS value_count FROM table GROUP BY list1,list2`;

This will give you all list1existance only with max(list2).


问:
AngularJS view showing old data quickly before showing the new data when switching between views
I have a single page angularJS / nodejs / express app. When first loading the app, it pulls data via API from database and displays in a table in the 'home' route. 5 minutes later, it updates the data by doing the API call again then $scope.$apply().

After the update if I navigate away from the 'home' route to a different view within the app, then back again, you can see the old data for a fraction of a second then the new data pops into place again.

This will happen repeatedly as I navigate away and back to the route.

It seem like the browser is saving the old data, then updating it every time I go back.

Why is this happening and how can I make the $scope.apply changes permanent?

答: The solution was to load the data into an object in a factory, and update the data object in the factory instead of in the controller.  This keeps the data up to date when changing views. </p>


问:
Unable to run serverspec test on GCP packer instance
I am struggling to run serverspec test on GCP packer instance from local machine.
I have created a packer json config file as follows to create an image on GCP:

```<code>{
"variables": {
    "project": "gcp-project",
    "image_family": "centos-7",
    "username": "centos",
    "zone": "us-central1-c",
    "version": "latest"
},

"builders": [
    {
        "type": "googlecompute",
        "account_file": "account.json",
        "project_id": "{{user `project`}}",
        "zone": "{{user `zone`}}",
        "source_image":"centos-7-v20171025",
        "image_name": "sftp-{{user `image_family`}}-{{user `version`}}-{{timestamp}}",
        "image_family": "{{user `image_family`}}",
        "image_description": "sftp - from packer",
        "ssh_username": "{{user `username`}}",
        "machine_type": "g1-small"
    }
],

"provisioners": [
    {
        "type": "shell-local",
        "command": "rake spec TARGET_HOST=remotehost"
    }
]
</code>```

}

and i am executing rake spec TARGET_HOST=(ip of packer instance) to run serverspec test from local machine and spec_helper.rb is configured with ssh login as follows:

```<code>host = ENV['TARGET_HOST']
options = Net::SSH::Config.for(host)
options[:user] = 'centos'
set :host,        options[:host_name] || host
set :ssh_options, options
</code>```

and Rakefile is configured to run test from specific folder.

after running packer build command packer build -var-file=variables.json sftp.json| tee build.log

it fails with

```<code>Net::SSH::AuthenticationFailed:
Authentication failed for user centos@1.2.3.4
</code>```

Packer build log

```<code>==> googlecompute: Checking image does not exist...
==> googlecompute: Creating temporary SSH key for instance...
==> googlecompute: Using image: centos-7-v20171025
==> googlecompute: Creating instance...
    googlecompute: Loading zone: us-central1-c
    googlecompute: Loading machine type: g1-small
    googlecompute: Loading network: default
    googlecompute: Requesting instance creation...
    googlecompute: Waiting for creation operation to complete...
    googlecompute: Instance has been created!
==> googlecompute: Waiting for the instance to become running...
    googlecompute: IP: 1.2.3.4
==> googlecompute: Waiting for SSH to become available...
==> googlecompute: Connected to SSH!
==> googlecompute: Executing local command: rake spec TARGET_HOST=1.2.3.4
    googlecompute: An error occurred while loading ./spec/1.2.3.4/sftp_spec.rb.
    googlecompute: On host '1.2.3.4'
    googlecompute: Failure/Error:
    googlecompute:   describe service('sshd'), :if => os[:family] == 'redhat' do
    googlecompute:     it { should be_enabled }
    googlecompute:     it { should be_running }
    googlecompute:   end
    googlecompute: Net::SSH::AuthenticationFailed:
    googlecompute:   Authentication failed for user centos@1.2.3.4
</code>```

Due to this error I am unable to run serverspec test from local machine using ssh on remote packer instance.

any answer will be appreciated. thanks very much.

答:
It seems like you are missing the password for centos user.

Add this to spec_helper.rb:

```<code>options[:password] = ENV['LOGIN_PASSWORD']
</code>```

And ajust your shell-local to:

```<code>{
    "type": "shell-local",
    "command": "LOGIN_PASSWORD='{{ user `sftp_password` }}' rake spec TARGET_HOST=remotehost"
}
</code>```

Body:
I am struggling to run serverspec test on GCP packer instance from local machine.
I have created a packer json config file as follows to create an image on GCP:

{
"variables": {
    "project": "gcp-project",
    "image_family": "centos-7",
    "username": "centos",
    "zone": "us-central1-c",
    "version": "latest"
},

"builders": [
    {
        "type": "googlecompute",
        "account_file": "account.json",
        "project_id": "{{user `project`}}",
        "zone": "{{user `zone`}}",
        "source_image":"centos-7-v20171025",
        "image_name": "sftp-{{user `image_family`}}-{{user `version`}}-{{timestamp}}",
        "image_family": "{{user `image_family`}}",
        "image_description": "sftp - from packer",
        "ssh_username": "{{user `username`}}",
        "machine_type": "g1-small"
    }
],

"provisioners": [
    {
        "type": "shell-local",
        "command": "rake spec TARGET_HOST=remotehost"
    }
]

}

and i am executing rake spec TARGET_HOST=(ip of packer instance) to run serverspec test from local machine and spec_helper.rb is configured with ssh login as follows:

host = ENV['TARGET_HOST']
options = Net::SSH::Config.for(host)
options[:user] = 'centos'
set :host,        options[:host_name] || host
set :ssh_options, options

and Rakefile is configured to run test from specific folder.

after running packer build command packer build -var-file=variables.json sftp.json| tee build.log

it fails with

Net::SSH::AuthenticationFailed:
Authentication failed for user centos@1.2.3.4

Packer build log

==> googlecompute: Checking image does not exist...
==> googlecompute: Creating temporary SSH key for instance...
==> googlecompute: Using image: centos-7-v20171025
==> googlecompute: Creating instance...
    googlecompute: Loading zone: us-central1-c
    googlecompute: Loading machine type: g1-small
    googlecompute: Loading network: default
    googlecompute: Requesting instance creation...
    googlecompute: Waiting for creation operation to complete...
    googlecompute: Instance has been created!
==> googlecompute: Waiting for the instance to become running...
    googlecompute: IP: 1.2.3.4
==> googlecompute: Waiting for SSH to become available...
==> googlecompute: Connected to SSH!
==> googlecompute: Executing local command: rake spec TARGET_HOST=1.2.3.4
    googlecompute: An error occurred while loading ./spec/1.2.3.4/sftp_spec.rb.
    googlecompute: On host '1.2.3.4'
    googlecompute: Failure/Error:
    googlecompute:   describe service('sshd'), :if => os[:family] == 'redhat' do
    googlecompute:     it { should be_enabled }
    googlecompute:     it { should be_running }
    googlecompute:   end
    googlecompute: Net::SSH::AuthenticationFailed:
    googlecompute:   Authentication failed for user centos@1.2.3.4

Due to this error I am unable to run serverspec test from local machine using ssh on remote packer instance.

any answer will be appreciated. thanks very much.

Body:
It seems like you are missing the password for centos user.

Add this to spec_helper.rb:

options[:password] = ENV['LOGIN_PASSWORD']

And ajust your shell-local to:

{
    "type": "shell-local",
    "command": "LOGIN_PASSWORD='{{ user `sftp_password` }}' rake spec TARGET_HOST=remotehost"
}


问:
sbt fails to start due to org.webjars.npm#graceful-readlink;1.0.0
I'm having troubles starting sbt on java-play 2.6 project with following errors:

sbt.ResolveException:

unresolved dependency: org.webjars.npm#graceful-readlink;1.0.0: not found

unresolved dependency: org.webjars.npm#minimatch;[2,3),[3,4): not found

Dependencies to these libraries come from plugin "sbt-reactjs" % "0.6.8"

Already tried deleting, reinstalling things (like : re-install sbt, delete node modules, cleaning ivy, sbt caches), and still getting frustrated with this error.

Environment: Mac OS X, ProductVersion:  10.13.1

Any ideas will be very much appreciated :)
Thanks in advance.

答:
One way to overcomes the issue is:

decrease sbt version to 0.13.15

adding dependency overrides to plugins.sbt

dependencyOverrides += "org.webjars.npm" % "minimatch" % "3.0.4"
dependencyOverrides += "org.webjars.npm" % "graceful-readlink" % "1.0.1"
```


问:
How to convert a date format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?
How to CONVERT a date in format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?

I am trying to convert the below list into YYYYMMDD integers

```<code>WITH  all_dates  as (SELECT
    CAST(date_column AS DATE) date_column
FROM
    (VALUES
        (SEQUENCE(FROM_ISO8601_DATE('2017-07-01'),
                  FROM_ISO8601_DATE('2017-11-15'),
                  INTERVAL '1' DAY)
        )
    ) AS t1(date_array)
CROSS JOIN
    UNNEST(date_array) AS t2(date_column)
    )
</code>```

I tried something like this but it doesn't work

```<code>   SELECT
   CAST(
      CAST(year(date_column) AS VARCHAR(4)) +
      right('0' + CAST(month(date_column) AS VARCHAR(2)), 2) +
      right('0' + CAST(day(date_column) AS VARCHAR(2)), 2)
   AS DATETIME)
   FROM all_dates
</code>```

答:
Also you can use date_format function:

```<code>hive> select cast(date_format('2017-07-01','yyyyMMdd') as int);
OK
20170701
</code>```

Body:
How to CONVERT a date in format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?

I am trying to convert the below list into YYYYMMDD integers

WITH  all_dates  as (SELECT
    CAST(date_column AS DATE) date_column
FROM
    (VALUES
        (SEQUENCE(FROM_ISO8601_DATE('2017-07-01'),
                  FROM_ISO8601_DATE('2017-11-15'),
                  INTERVAL '1' DAY)
        )
    ) AS t1(date_array)
CROSS JOIN
    UNNEST(date_array) AS t2(date_column)
    )

I tried something like this but it doesn't work

   SELECT
   CAST(
      CAST(year(date_column) AS VARCHAR(4)) +
      right('0' + CAST(month(date_column) AS VARCHAR(2)), 2) +
      right('0' + CAST(day(date_column) AS VARCHAR(2)), 2)
   AS DATETIME)
   FROM all_dates

Body:
Also you can use date_format function:

hive> select cast(date_format('2017-07-01','yyyyMMdd') as int);
OK
20170701


问:
How to connect Spring MVC to a remote MongoDB, to use the MongoOperations interface?
I have setup MongoDB on a local and a remote server, IP: 10.11.12.13.
Connecting using the command-line works when I do the following:

```<code>mongo 10.11.12.13:27017 -u "root" -p "123456" --authenticationDatabase "admin"
</code>```

Furthermore, connecting to localhost using the Spring MVC, works too, and below is my configuration XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->
    <!-- For the autowired Classes -->
    <context:component-scan base-package="com.example">
        <!-- Exclude the Web controllers from the Spring root configuration file -->
        <context:exclude-filter type="regex"
            expression="com.example.controller" />
    </context:component-scan>

    <tx:annotation-driven />

    <!-- Enable @Aspect, @Before, @After -->
    <aop:aspectj-autoproxy proxy-target-class="true" />

    <mongo:mongo id="mongo" host="localhost" port="27017" />
    <mongo:db-factory dbname="MockDB" mongo-ref="mongo" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>

</beans>
</code>```

This is the pom.xml

```<code>    <properties>
        <java.version>1.7</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- Spring -->
        <org.springframework-version>3.2.6.RELEASE</org.springframework-version>
        <org.springsecurity-version>3.2.0.RELEASE</org.springsecurity-version>
        <!-- Hibernate / JPA -->
        <hibernate.version>4.1.8.Final</hibernate.version>
        <mysql.version>5.1.27</mysql.version>
        <!-- Logging -->
        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>
        <!-- Test -->
        <junit.version>4.11</junit.version>
        <apache-dbcp.version>1.4</apache-dbcp.version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <mockito-version>1.10.19</mockito-version>
        <assertj-version>1.5.0</assertj-version>
        <!-- MongoDB -->
        <jackson.version>1.9.10</jackson.version>
        <mongo.version>1.3.3.RELEASE</mongo.version>
    </properties>

    <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.12.0</version>
    <scope>test</scope>
</dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <!-- Spring Aspect Oriented support -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${apache-dbcp.version}</version>
        </dependency>

        <!-- Test Artifacts -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${assertj-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>${mongo.version}</version>
        </dependency>

        <!-- Logging -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
            <scope>runtime</scope>
        </dependency>
        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- Validation -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.2</version>
</dependency>
</code>```

As mentioned, I am using MongoOperations Java interface to manage MongoDB.

I would like to be able to connect to a remote MongoDB just the way I am connecting using a command-line, so I can manage it with MongoOperations.
However, whatever I tried did not work, and I am stuck.  What am I supposed to do/change/add so I can connect to a remote MongoDB ?

答:
lets Try this may be it will resolve your problem

```<code> <mongo:mongo host="${mongoDBHost}" port="${mongoDBPort}" id="mongo" />

    <bean id="mongoCredientials" class="org.springframework.data.authentication.UserCredentials">
        <constructor-arg name="username" value="${mongoDBUserName}"/>
        <constructor-arg name="password" value="${mongoDBPassword}"/>
    </bean>

    <bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
        <constructor-arg name="mongo" ref="mongo"/>
        <constructor-arg name="databaseName" value="${mongoDBName}"/>
        <constructor-arg name="credentials" ref="mongoCredientials"/>
    </bean>

    <mongo:mapping-converter id="mappingConverter" db-factory-ref="mongoDbFactory" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
        <constructor-arg name="mongoConverter" ref="mappingConverter"/>
    </bean>
</code>```

reference links:
1  2 3

Body:
I have setup MongoDB on a local and a remote server, IP: 10.11.12.13.
Connecting using the command-line works when I do the following:

mongo 10.11.12.13:27017 -u "root" -p "123456" --authenticationDatabase "admin"

Furthermore, connecting to localhost using the Spring MVC, works too, and below is my configuration XML:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.example">

        <context:exclude-filter type="regex"
            expression="com.example.controller" />
    </context:component-scan>

    <tx:annotation-driven />

    <aop:aspectj-autoproxy proxy-target-class="true" />

    <mongo:mongo id="mongo" host="localhost" port="27017" />
    <mongo:db-factory dbname="MockDB" mongo-ref="mongo" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>

</beans>

This is the pom.xml

    <properties>
        <java.version>1.7</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <org.springframework-version>3.2.6.RELEASE</org.springframework-version>
        <org.springsecurity-version>3.2.0.RELEASE</org.springsecurity-version>

        <hibernate.version>4.1.8.Final</hibernate.version>
        <mysql.version>5.1.27</mysql.version>

        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>

        <junit.version>4.11</junit.version>
        <apache-dbcp.version>1.4</apache-dbcp.version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <mockito-version>1.10.19</mockito-version>
        <assertj-version>1.5.0</assertj-version>

        <jackson.version>1.9.10</jackson.version>
        <mongo.version>1.3.3.RELEASE</mongo.version>
    </properties>

    <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.12.0</version>
    <scope>test</scope>
</dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${org.springsecurity-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${apache-dbcp.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>${mockito-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.assertj</groupId>
            <artifactId>assertj-core</artifactId>
            <version>${assertj-version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>${mongo.version}</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.2</version>
</dependency>

As mentioned, I am using MongoOperations Java interface to manage MongoDB.

I would like to be able to connect to a remote MongoDB just the way I am connecting using a command-line, so I can manage it with MongoOperations.
However, whatever I tried did not work, and I am stuck.  What am I supposed to do/change/add so I can connect to a remote MongoDB ?

Body:
lets Try this may be it will resolve your problem

 <mongo:mongo host="${mongoDBHost}" port="${mongoDBPort}" id="mongo" />

    <bean id="mongoCredientials" class="org.springframework.data.authentication.UserCredentials">
        <constructor-arg name="username" value="${mongoDBUserName}"/>
        <constructor-arg name="password" value="${mongoDBPassword}"/>
    </bean>

    <bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
        <constructor-arg name="mongo" ref="mongo"/>
        <constructor-arg name="databaseName" value="${mongoDBName}"/>
        <constructor-arg name="credentials" ref="mongoCredientials"/>
    </bean>

    <mongo:mapping-converter id="mappingConverter" db-factory-ref="mongoDbFactory" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
        <constructor-arg name="mongoConverter" ref="mappingConverter"/>
    </bean>

reference links:
1  2 3


问:
How to link static css files in jinja2 using webapp2 server?
I am using my own webapp2 server, and jinja2 template engine for html and css.
i have tried to link css files in my html page but i couldn't link the css static files, can any body help me please how to link css files in jinja2 using own webapp2 server.</p>

答: I have found the solution of my question, i have added the webapp2_static library and it works for me </p>


问:
How to exclude package from grails log4j appender
I have an appender configured in Config.groovy like this:

```<code>all myLog:['grails.app.controller', 'grails.app.service', 'grails.app.domain', 'grails.app.task'], additivity: false
</code>```

Now there is a special package inside the above packages which I don't want to log, e.g. grails.app.service.some.service.

How can I exclude this package from the myLog Appender? I already found this StackOverflow question and answer, but I don't know how to "translate" this into my grails configuration.

答:
I usually define the log level in Grails differently, something like:

```<code>  info 'com.opensymphony.oscache'
  warn 'org.codehaus.groovy.grails.web.servlet',  //  controllers
       'org.codehaus.groovy.grails.web.pages' //  GSP
  error 'groovyx.net.http.ParserRegistry'
  debug 'org.jgroups.protocols.pbcast.GMS'
</code>```

And to disable the log in a specific package or even a class I do:

```<code>  off 'com.example.excluded.package'
</code>```

The good thing about this is that you can have full control of the log level per package or even per class if necessary.

Hope this helps!

Body:
I have an appender configured in Config.groovy like this:

all myLog:['grails.app.controller', 'grails.app.service', 'grails.app.domain', 'grails.app.task'], additivity: false

Now there is a special package inside the above packages which I don't want to log, e.g. grails.app.service.some.service.

How can I exclude this package from the myLog Appender? I already found this StackOverflow question and answer, but I don't know how to "translate" this into my grails configuration.

Body:
I usually define the log level in Grails differently, something like:

  info 'com.opensymphony.oscache'
  warn 'org.codehaus.groovy.grails.web.servlet',  //  controllers
       'org.codehaus.groovy.grails.web.pages' //  GSP
  error 'groovyx.net.http.ParserRegistry'
  debug 'org.jgroups.protocols.pbcast.GMS'

And to disable the log in a specific package or even a class I do:

  off 'com.example.excluded.package'

The good thing about this is that you can have full control of the log level per package or even per class if necessary.

Hope this helps!


问:
Selenium Explicit wait
Can any one let me know how and where to implement Explicit Wait in POM frameowrk?

I mean, where should i implement explicit wait code? In POM classes or in Test Case classes?

since now, i have implemented the EW code line in POM class and within the constructor body, below code

```<code>public RegistrationPage (WebDriver driver)
    {
        PageFactory.initElements(driver, this);
        new WebDriverWait(driver, 30).until(ExpectedConditions.visibilityOf(GenderRadioButton));
    }
</code>```

This worked fine for me, but not 100% sure whether or not this is a correct place to implement Explicit wait, need some insight on this plz

--- Ram

答:
You could try with this:</p>

```<code>public RegistrationPage (WebDriver driver, int timeOutSeconds)
{
    driver.manage().timeouts().implicitlyWait(timeOutSeconds, TimeUnit.SECONDS);
    PageFactory.initElements(driver, this);
    new FluentWait<WebDriver>(driver)
            .withTimeout(timeOutSeconds, TimeUnit.SECONDS)
            .pollingEvery(RETRY_TIME, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class)
            .until(ExpectedConditions
                    .visibilityOf(By.xpath(xpath)))
   driver.manage().timeouts().implicitlyWait(timeOutSeconds, CLASS_VARIABLE_IMPLICIT_TIMEOUT);
}
</code>```

Title: Selenium Explicit wait

Body:
Can any one let me know how and where to implement Explicit Wait in POM frameowrk?

I mean, where should i implement explicit wait code? In POM classes or in Test Case classes?

since now, i have implemented the EW code line in POM class and within the constructor body, below code

public RegistrationPage (WebDriver driver)
    {
        PageFactory.initElements(driver, this);
        new WebDriverWait(driver, 30).until(ExpectedConditions.visibilityOf(GenderRadioButton));
    }

This worked fine for me, but not 100% sure whether or not this is a correct place to implement Explicit wait, need some insight on this plz

--- Ram

Body:
You could try with this:

public RegistrationPage (WebDriver driver, int timeOutSeconds)
{
    driver.manage().timeouts().implicitlyWait(timeOutSeconds, TimeUnit.SECONDS);
    PageFactory.initElements(driver, this);
    new FluentWait<WebDriver>(driver)
            .withTimeout(timeOutSeconds, TimeUnit.SECONDS)
            .pollingEvery(RETRY_TIME, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class)
            .until(ExpectedConditions
                    .visibilityOf(By.xpath(xpath)))
   driver.manage().timeouts().implicitlyWait(timeOutSeconds, CLASS_VARIABLE_IMPLICIT_TIMEOUT);
}