问:
Inserting images using jQuery .html
I have a counter that counts in dollars. Each number, as well as the dollar sign and comma, are all displayed on the page using images. I use display: flex; in my container div and flex: 1 1 auto; on the divs that hold the images. I use this CSS so that it all shrinks as more numbers are added.

Here is a jsfiddle to see the issue.
https://jsfiddle.net/0mvy8hqo/

Here is the CSS I am using

```<code>.i15-counter .i15-counter-inner { display: flex; }
.i15-counter .i15-counter-inner .i15-counter-number { flex: 1 1 auto; max-width: 110px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-dollar { flex: 1 1 auto; max-width: 76px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-comma { flex: 1 1 auto; max-width: 40px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-first {
  padding: 20px 0px 20px 20px;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-bottom-left-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-bottomleft: 5px;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}
.i15-counter .i15-counter-inner .i15-counter-last {
  padding: 20px 20px 20px 0px;
  -webkit-border-top-right-radius: 5px;
  -webkit-border-bottom-right-radius: 5px;
  -moz-border-radius-topright: 5px;
  -moz-border-radius-bottomright: 5px;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}
</code>```

I also use jQuery to update the counter every second based on some math I have set up in my code. This all works just fine. My only issue is that if the amount of images displayed on the page is enough that the images shrink then when I have my javascript replace the images with new images as the counter increases, the images start out at full size and then shrink to fit the container. So rather than it just looking like the number is changing, you have this expand/shrink effect that I would like to get rid of. This happens for about a minute then it stops. I am guessing the stopping has something to do with the browser's cache, but I am not sure.

Here is the Javascript I am using.

```<code>function number_format (number, decimals, dec_point, thousands_sep) {
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function updateCounters(id) {
  var current = parseInt(jQuery('.i15-counter-'+id+'-current').val());
  var next = parseInt(jQuery('.i15-counter-'+id+'-next').val());
  var rate = parseInt(jQuery('.i15-counter-'+id+'-rate').val());
  var image_url = jQuery('.i15-counter-'+id+'-image-url').val();

  var new_current = current + rate;

  if(new_current <= next) {
    var new_current_formatted = number_format(new_current, 0);
    var new_current_formatted_adddollar = '$' + new_current_formatted;
    var new_current_split = new_current_formatted_adddollar.split("");
    //console.log(new_current_formatted);
    var numbercount = 1;
    var numbertotal = new_current_split.length;
    var counter_html = "";

    jQuery.each( new_current_split, function( i, val ) {
      var number_ends = "";
      if(numbercount == 1) {
        number_ends += " i15-counter-first";
      }

      if(numbercount == numbertotal) {
        number_ends += " i15-counter-last";
      }

      var anumber_class = "i15-counter-number";
      if(val == "$") { val = "dollar"; anumber_class = "i15-counter-dollar"; }
      if(val == ",") { val = "comma"; anumber_class = "i15-counter-comma"; }

      counter_html += '<div class="' + anumber_class + number_ends + '"><img src="' + image_url + 'counter_' + val + '.png" /></div>';
      numbercount++;
    });

    jQuery('.i15-counter-container-'+id).html(counter_html);
    jQuery('.i15-counter-'+id+'-current').val(new_current);
  }
}

jQuery(document).ready( function($) {

  window.setInterval(function(){
    jQuery(".i15-counter").each(function() {
      updateCounters(jQuery(this).data('id'));
    });
  }, 1000);

})
</code>```

答:
This is a loading problem.

Either use preloading or (better) specify a width:

```<code>  var width = 110;
  if(val == "$") { val = "dollar"; anumber_class = "i15-counter-dollar"; width = 100; }
  if(val == ",") { val = "comma"; anumber_class = "i15-counter-comma"; width = 60; }
  counter_html += '<div class="' + anumber_class + number_ends + '">" +
      "<img src="' + image_url + 'counter_' + val + '.png" width=' + width + ' /></div>';
</code>```

Note: i have not measured your actual widths, only roughly estimated them.

Title: Inserting images using jQuery .html

Body:
I have a counter that counts in dollars. Each number, as well as the dollar sign and comma, are all displayed on the page using images. I use display: flex; in my container div and flex: 1 1 auto; on the divs that hold the images. I use this CSS so that it all shrinks as more numbers are added.

Here is a jsfiddle to see the issue.
https://jsfiddle.net/0mvy8hqo/

Here is the CSS I am using

.i15-counter .i15-counter-inner { display: flex; }
.i15-counter .i15-counter-inner .i15-counter-number { flex: 1 1 auto; max-width: 110px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-dollar { flex: 1 1 auto; max-width: 76px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-comma { flex: 1 1 auto; max-width: 40px; padding: 20px 0px; background-color: #333; }
.i15-counter .i15-counter-inner .i15-counter-first {
  padding: 20px 0px 20px 20px;
  -webkit-border-top-left-radius: 5px;
  -webkit-border-bottom-left-radius: 5px;
  -moz-border-radius-topleft: 5px;
  -moz-border-radius-bottomleft: 5px;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}
.i15-counter .i15-counter-inner .i15-counter-last {
  padding: 20px 20px 20px 0px;
  -webkit-border-top-right-radius: 5px;
  -webkit-border-bottom-right-radius: 5px;
  -moz-border-radius-topright: 5px;
  -moz-border-radius-bottomright: 5px;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

I also use jQuery to update the counter every second based on some math I have set up in my code. This all works just fine. My only issue is that if the amount of images displayed on the page is enough that the images shrink then when I have my javascript replace the images with new images as the counter increases, the images start out at full size and then shrink to fit the container. So rather than it just looking like the number is changing, you have this expand/shrink effect that I would like to get rid of. This happens for about a minute then it stops. I am guessing the stopping has something to do with the browser's cache, but I am not sure.

Here is the Javascript I am using.

function number_format (number, decimals, dec_point, thousands_sep) {
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}

function updateCounters(id) {
  var current = parseInt(jQuery('.i15-counter-'+id+'-current').val());
  var next = parseInt(jQuery('.i15-counter-'+id+'-next').val());
  var rate = parseInt(jQuery('.i15-counter-'+id+'-rate').val());
  var image_url = jQuery('.i15-counter-'+id+'-image-url').val();

  var new_current = current + rate;

  if(new_current <= next) {
    var new_current_formatted = number_format(new_current, 0);
    var new_current_formatted_adddollar = '$' + new_current_formatted;
    var new_current_split = new_current_formatted_adddollar.split("");
    //console.log(new_current_formatted);
    var numbercount = 1;
    var numbertotal = new_current_split.length;
    var counter_html = "";

    jQuery.each( new_current_split, function( i, val ) {
      var number_ends = "";
      if(numbercount == 1) {
        number_ends += " i15-counter-first";
      }

      if(numbercount == numbertotal) {
        number_ends += " i15-counter-last";
      }

      var anumber_class = "i15-counter-number";
      if(val == "$") { val = "dollar"; anumber_class = "i15-counter-dollar"; }
      if(val == ",") { val = "comma"; anumber_class = "i15-counter-comma"; }

      counter_html += '

';
      numbercount++;
    });

    jQuery('.i15-counter-container-'+id).html(counter_html);
    jQuery('.i15-counter-'+id+'-current').val(new_current);
  }
}

jQuery(document).ready( function($) {

  window.setInterval(function(){
    jQuery(".i15-counter").each(function() {
      updateCounters(jQuery(this).data('id'));
    });
  }, 1000);

})

Body:
This is a loading problem.

Either use preloading or (better) specify a width:

  var width = 110;
  if(val == "$") { val = "dollar"; anumber_class = "i15-counter-dollar"; width = 100; }
  if(val == ",") { val = "comma"; anumber_class = "i15-counter-comma"; width = 60; }
  counter_html += '<div class="' + anumber_class + number_ends + '">" +
      "<img src="' + image_url + 'counter_' + val + '.png" width=' + width + ' /></div>';

Note: i have not measured your actual widths, only roughly estimated them.


来源: stackexchange

问:
insert into an array if value is not found
I have an array built like this:

```<code>test[0].age = "15-24"; test[0].value= "5";

test[1].age = "45-54"; test[1].value= "10";
</code>```

etc

I have another array built like this:

```<code>ageRange[0] = "1-14";

ageRange[1] = "15-24";
</code>```

etc

The ageRange has all age ranges - and the test array only has some of them.

I want to rebuild the test array to include all ages of the ageRange array and if they aren't already in the array, assign them a value of 0. What is the best way of doing this? Also - they need to be sequentially added.

ContentLicense: CC BY-SA 3.0

Body:
I have an array built like this:

test[0].age = "15-24"; test[0].value= "5";

test[1].age = "45-54"; test[1].value= "10";

etc

I have another array built like this:

ageRange[0] = "1-14";

ageRange[1] = "15-24";

etc

The ageRange has all age ranges - and the test array only has some of them.

I want to rebuild the test array to include all ages of the ageRange array and if they aren't already in the array, assign them a value of 0. What is the best way of doing this? Also - they need to be sequentially added.

Body:
var AgeArray=["15-24","25-30","30-35","40-45","45-50","55-60"];

var NewArray=[{ age: "15-24", value: "5" }, { age: "25-30", value: "10" }, { age: "45-50", value: "15" }, { age: "55-60", value: "20" }];

$.each(AgeArray,function(i,val){

 var filtered = $(NewArray).filter(function(){
        return this.age == val;
    });
    if(filtered.length == 0)
{
var newobj={};newobj.age=val;newobj.value=0;NewArray.push(newobj)}

});

$('#result').text(JSON.stringify(NewArray));

Output

https://jsfiddle.net/wy18u0zu/2/

JSON.stringify(NewArray)

"[{"age":"15-24","value":"5"},{"age":"25-30","value":"10"},{"age":"45-50","value":"15"},{"age":"55-60","value":"20"},{"age":"30-35","value":0},{"age":"40-45","value":0}]"


问:
Ignore Issues in Blocks
Our Java files analyzed on SQ contain blocks of automatically generated code. Such a block starts with

```<code>// @UKA_GENERATION_START@
</code>```

and ends with

```<code>// @UKA_GENERATION_END@
</code>```

Code lines between them should be ignored by SQ.

Site http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus describes in the chapter 'Ignore Issues in Blocks' how it can be done. Parameter sonar.issue.ignore.block should be used.

In our environment we use Maven for project build and analysis. In the project's POM we set the following parameters:

```<code><sonar.issue.ignore.block>e1</sonar.issue.ignore.block>
<sonar.issue.ignore.block.e1.beginBlockRegexp>\/\/ @UKA_GENERATION_START@</sonar.issue.ignore.block.e1.beginBlockRegexp>
<sonar.issue.ignore.block.e1.endBlockRegexp>\/\/ @UKA_GENERATION_END@</sonar.issue.ignore.block.e1.endBlockRegexp>
</code>```

(Regular expressions matching above strings).

Unfortunately, SQ doesn't exclude code blocks between // @UKA_GENERATION_START@ and // @UKA_GENERATION_END@ from the analysis!
Do you have an idea, why?

答:
How about simplifying your regex by leaving out the // characters? The following configuration should work perfectly fine:

```<code>sonar.issue.ignore.block=e1
sonar.issue.ignore.block.e1.beginBlockRegexp=@UKA_GENERATION_START@
sonar.issue.ignore.block.e1.endBlockRegexp=@UKA_GENERATION_END@
</code>```

Configured as above, issues between the start and end tags will be ignored

```<code>// @UKA_GENERATION_START@

System.out.println("Hello world!");

// @UKA_GENERATION_END@
</code>```

Or in more detail... in the following example, lines 1 and 5 will raise a Sonar issue, while lines 2 - 4 will be ignored:

```<code>1:  System.out.println("Hello world!");
2:  System.out.println("Hello world!");   // @UKA_GENERATION_START@
3:  System.out.println("Hello world!");
4:  System.out.println("Hello world!");   // @UKA_GENERATION_END@
5:  System.out.println("Hello world!");
</code>```

Title: Ignore Issues in Blocks

Body:
Our Java files analyzed on SQ contain blocks of automatically generated code. Such a block starts with

// @UKA_GENERATION_START@

and ends with

// @UKA_GENERATION_END@

Code lines between them should be ignored by SQ.

Site http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus describes in the chapter 'Ignore Issues in Blocks' how it can be done. Parameter sonar.issue.ignore.block should be used.

In our environment we use Maven for project build and analysis. In the project's POM we set the following parameters:

<sonar.issue.ignore.block>e1</sonar.issue.ignore.block>
<sonar.issue.ignore.block.e1.beginBlockRegexp>\/\/ @UKA_GENERATION_START@</sonar.issue.ignore.block.e1.beginBlockRegexp>
<sonar.issue.ignore.block.e1.endBlockRegexp>\/\/ @UKA_GENERATION_END@</sonar.issue.ignore.block.e1.endBlockRegexp>

(Regular expressions matching above strings).

Unfortunately, SQ doesn't exclude code blocks between // @UKA_GENERATION_START@ and // @UKA_GENERATION_END@ from the analysis!
Do you have an idea, why?

Body:
How about simplifying your regex by leaving out the // characters? The following configuration should work perfectly fine:

sonar.issue.ignore.block=e1
sonar.issue.ignore.block.e1.beginBlockRegexp=@UKA_GENERATION_START@
sonar.issue.ignore.block.e1.endBlockRegexp=@UKA_GENERATION_END@

Configured as above, issues between the start and end tags will be ignored

// @UKA_GENERATION_START@

System.out.println("Hello world!");

// @UKA_GENERATION_END@

Or in more detail... in the following example, lines 1 and 5 will raise a Sonar issue, while lines 2 - 4 will be ignored:

1:  System.out.println("Hello world!");
2:  System.out.println("Hello world!");   // @UKA_GENERATION_START@
3:  System.out.println("Hello world!");
4:  System.out.println("Hello world!");   // @UKA_GENERATION_END@
5:  System.out.println("Hello world!");


问:
how to customize the ribbon load balancer in Zuul server
As I understand the default load balancer using in Zuul proxy server as  DynamicServerListLoadBalancer and it use ZoneAffinityServerListFilter rule to choose server. However, is there any way I can customize the loadbalancer used in zuul proxy server

I have tried to add following configuration to change to loadbalancer Rule:

```<code>eureka.client.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RoundRobinRule
</code>```

But seems it still stick with default configuration.

Any advice is highly appreciated.

答:
To change load balancing rule with configuration, you should define ribbon configuration like below.

```<code>your_ribbonclient_name.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RoundRobinRule
</code>```

your_ribbonclient_name shoud be replaced with the proper one for your configuration. In Zuul, ribbon client name is same with service id for each route.

You can also provide your own IRule bean for load balancing rule with @RibbonClient like the following.

```<code>@RibbonClient(name = "your_ribbonclient_name", configuration = YourConfigurationClass.class)
</code>```

You can find an example code here

If you want to apply your Ribbon config to whole ribbon clients in your server,
you can do that with @RibbonClients (not @RibbonClient).

```<code>@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class)
</code>```

You can find the example code here, and the related issues is here.

Body:
As I understand the default load balancer using in Zuul proxy server as  DynamicServerListLoadBalancer and it use ZoneAffinityServerListFilter rule to choose server. However, is there any way I can customize the loadbalancer used in zuul proxy server

I have tried to add following configuration to change to loadbalancer Rule:

eureka.client.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RoundRobinRule

But seems it still stick with default configuration.

Any advice is highly appreciated.

Body:
To change load balancing rule with configuration, you should define ribbon configuration like below.

your_ribbonclient_name.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RoundRobinRule

your_ribbonclient_name shoud be replaced with the proper one for your configuration. In Zuul, ribbon client name is same with service id for each route.

You can also provide your own IRule bean for load balancing rule with @RibbonClient like the following.

@RibbonClient(name = "your_ribbonclient_name", configuration = YourConfigurationClass.class)

You can find an example code here

If you want to apply your Ribbon config to whole ribbon clients in your server,
you can do that with @RibbonClients (not @RibbonClient).

@RibbonClients(defaultConfiguration = DefaultRibbonConfig.class)

You can find the example code here, and the related issues is here.


问:
Where clause inside whereHas being ignored in Eloquent
Im trying to make a query using whereHas with eloquent. The query is like this:

```<code>$projects = Project::whereHas('investments', function($q) {
                $q->where('status','=','paid');
            })
            ->with('investments')
            ->get();
</code>```

Im using Laravel 5.2 using a Postgres driver.

The Project model is:

```<code>public function investments()
{
    return $this->hasMany('App\Investment');
}
</code>```

The investments model has:

```<code>public function project() {
    return $this->belongsTo('App\Project');
}
</code>```

The projects table has fields id,fields...

The investments table has the fields id,project_id,status,created_at

My issue is that the query runs and returns a collection of the projects which have at least one investment, however the where clause inside the whereHas is ignored, because the resulting collection includes investments with status values different than paid.

Does anyone has any idea of what is going on?

答: Change the order. Use with() before the whereHas(). I had a similar problem few weeks ago. Btw, is the only real difference between the problem and the functional example that you made.</p>

Body:
Im trying to make a query using whereHas with eloquent. The query is like this:

$projects = Project::whereHas('investments', function($q) {
                $q->where('status','=','paid');
            })
            ->with('investments')
            ->get();

Im using Laravel 5.2 using a Postgres driver.

The Project model is:

public function investments()
{
    return $this->hasMany('App\Investment');
}

The investments model has:

public function project() {
    return $this->belongsTo('App\Project');
}

The projects table has fields id,fields...

The investments table has the fields id,project_id,status,created_at

My issue is that the query runs and returns a collection of the projects which have at least one investment, however the where clause inside the whereHas is ignored, because the resulting collection includes investments with status values different than paid.

Does anyone has any idea of what is going on?


问:
Docker installation issues on Windows 10 Home Edition
I am facing problem while installing the Docker on my machine. OS is Windows 10 Home Edition. I want to use Splash and that needs Docker.

答:
Docker Toolbox ( Old Link ):  https://www.docker.com/products/docker-toolbox

Now You can use Docker Toolbox from here: https://docs.docker.com/toolbox/overview/

Follow these steps to install Docker Toolbox: https://docs.docker.com/toolbox/toolbox_install_windows/#step-3-verify-your-installation

or:

https://docs.bitnami.com/containers/how-to/install-docker-in-windows/

Tutorial For Virtualization : https://www.tutorialspoint.com/windows10/windows10_virtualization.htm


问:
curved lines with css on divs and inputs
Is it possible to create something like this only with css?

I think with this is this possible but is it also possible with input fields?

答:
You can make something similar using border-radius property

Snippet

.container{
  border-radius:5%/100px 100px 100px 100px;
  width: 300px;
  height: 200px;
  border: 1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="container" /></code>```

Working Fiddle here. Change the border-radius percentage and check the UI change

Body:
You can make something similar using border-radius property

Snippet

.container{
  border-radius:5%/100px 100px 100px 100px;
  width: 300px;
  height: 200px;
  border: 1px solid;
}

<input class="container" />

Working Fiddle here. Change the border-radius percentage and check the UI change


问:
Using IMapper in Integration Tests
As the title says, I'm writing integration tests and do want to test and initialize the IMapper object as part of these tests.

I am using XUnit as the testing framework and Ninject to handle dependency injection.

I'm used to using the static AutoMapper methods and am shifting to use the IMapper interface, which is a parameter in one of my repository constructors.

I have a DependencyRegistrar class that inherits the NinjectModule base class.

My Load method is below:

```<code>public override void Load()
    {
        var automapperConfig = new MapperConfiguration(cfg => { cfg.AddProfile<AutoMapperProfile>(); });
        automapperConfig.AssertConfigurationIsValid();
        var mapper = automapperConfig.CreateMapper();

        Bind<IMapper>().ToConstant(mapper).InSingletonScope();
        Bind<IUserManager>().To<UserManager>().InTransientScope();
        Bind<IUserRepository>().To<UserRepository>().InTransientScope();
    }
</code>```

This module is loaded by the NinjectWebCommon class in the API project, but obviously doesn't get loaded during the integration tests.

```<code>ConfigurationSettingsEntity configurationSettings = new ConfigurationSettingsEntity(ConfigurationManager.AppSettings);
        var modules = new INinjectModule[] { new DependencyResolution.DependencyRegistrar(configurationSettings) };
        var kernel = new StandardKernel(modules);
</code>```

So, my question is, what's the best way to load the real mapper implementation so that I can pass that mapper into my repository's constructor when I build out the integration test?

```<code>UserRepository tester = new UserRepository(mapper);
</code>```

答:
It's definitely worth the effort to shift away from using the static Mapper - testing will be much easier going forward!

In my unit tests, I use code like the following:

```<code>var config = new MapperConfiguration(cfg => {
    cfg.AddProfile<MyProfile>();
});
IMapper mapper = config.CreateMapper();
</code>```

In each test suite, I manually specify the profiles needed for those tests.

Title: Using IMapper in Integration Tests

Body:
As the title says, I'm writing integration tests and do want to test and initialize the IMapper object as part of these tests.

I am using XUnit as the testing framework and Ninject to handle dependency injection.

I'm used to using the static AutoMapper methods and am shifting to use the IMapper interface, which is a parameter in one of my repository constructors.

I have a DependencyRegistrar class that inherits the NinjectModule base class.

My Load method is below:

public override void Load()
    {
        var automapperConfig = new MapperConfiguration(cfg => { cfg.AddProfile<AutoMapperProfile>(); });
        automapperConfig.AssertConfigurationIsValid();
        var mapper = automapperConfig.CreateMapper();

        Bind<IMapper>().ToConstant(mapper).InSingletonScope();
        Bind<IUserManager>().To<UserManager>().InTransientScope();
        Bind<IUserRepository>().To<UserRepository>().InTransientScope();
    }

This module is loaded by the NinjectWebCommon class in the API project, but obviously doesn't get loaded during the integration tests.

ConfigurationSettingsEntity configurationSettings = new ConfigurationSettingsEntity(ConfigurationManager.AppSettings);
        var modules = new INinjectModule[] { new DependencyResolution.DependencyRegistrar(configurationSettings) };
        var kernel = new StandardKernel(modules);

So, my question is, what's the best way to load the real mapper implementation so that I can pass that mapper into my repository's constructor when I build out the integration test?

UserRepository tester = new UserRepository(mapper);

Body:
It's definitely worth the effort to shift away from using the static Mapper - testing will be much easier going forward!

In my unit tests, I use code like the following:

var config = new MapperConfiguration(cfg => {
    cfg.AddProfile<MyProfile>();
});
IMapper mapper = config.CreateMapper();

In each test suite, I manually specify the profiles needed for those tests.


问:
Compare 2 arrays for difference with some values repeating
I have 2 arrays to compare and I am using array_diff to compute the difference of columns as follows:

```<code>//array1 is as static array I have created to validate the sheet columns
$array1 = array('Category','Subcategory','Unknown','Age','0-9','Unknown','Region','Zone');

// array2 is coming dynamically from excel sheet columns so user can change the names
$array2 = array('Category','Subcategory','Unknowns','Age','0-9','Unknown','Region');

$diff = array_diff($array1,$array2);
$columnNames = implode(',',$diff);
if(!$diff){
   return true;
}
else{
  echo 'Some columns are missing:'. $columnNames ;
}
</code>```

output: Zone

Expected output: Zone, Unknowns

The above code works fine if Unknown columns are unchanged. I know array_diff will only check the first array and compare the values present in next array. But, I want to compare these arrays and display user a message that some columns are missing and their names. So, here if one of the column is changed to Unknowns in excel sheet i.e array2 then it should show the error message Some columns are missing: Zone, Unknowns

答:
Try this code

```<code>array_merge(array_diff($array1,$array2),array_diff($array2,$array1))
</code>```

Reference : https://stackoverflow.com/a/16356205/4895810

Body:
I have 2 arrays to compare and I am using array_diff to compute the difference of columns as follows:

//array1 is as static array I have created to validate the sheet columns
$array1 = array('Category','Subcategory','Unknown','Age','0-9','Unknown','Region','Zone');

// array2 is coming dynamically from excel sheet columns so user can change the names
$array2 = array('Category','Subcategory','Unknowns','Age','0-9','Unknown','Region');

$diff = array_diff($array1,$array2);
$columnNames = implode(',',$diff);
if(!$diff){
   return true;
}
else{
  echo 'Some columns are missing:'. $columnNames ;
}

output: Zone

Expected output: Zone, Unknowns

The above code works fine if Unknown columns are unchanged. I know array_diff will only check the first array and compare the values present in next array. But, I want to compare these arrays and display user a message that some columns are missing and their names. So, here if one of the column is changed to Unknowns in excel sheet i.e array2 then it should show the error message Some columns are missing: Zone, Unknowns

Body:
Try this code

array_merge(array_diff($array1,$array2),array_diff($array2,$array1))

Reference : https://stackoverflow.com/a/16356205/4895810


问:
Working on rails, i have text fields and text areas to receive text, but it shows the validation error "Topic cannot be empty"
After typing in topic and details in the appropriate text field and area, it still shows "validation error" "Topic cannot be empty". what is the problem? I cannot seem to figure it out.

```<code>This is the task partial
_task.html.erb:

 <li id="task-<%= task.id %>">
      <%= link_to gravatar_for(task.user, size: 50), task.user %>
      <span class="task"><%= link_to task.user.name, task.user %></span>
      <span class="topiclabel">Title:</span>
      <span class="topic"style=color:black> <%= task.topic %></span>
      <span class="detailslabel">Details: </span>
      <span class="detail"><%= task.detail %></span>
      <span class="timestamp">
        Posted <%= time_ago_in_words(task.created_at) %> ago.
      </span>
</li>

Schema:

ActiveRecord::Schema.define(version: 20170526194708) do

  create_table "stages", force: :cascade do |t|
    t.text     "topic"
    t.datetime "duration"
    t.text     "detail"
    t.integer  "task_id"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["task_id"], name: "index_stages_on_task_id"
    t.index ["user_id", "created_at"], name: "index_stages_on_user_id_and_created_at"
    t.index ["user_id"], name: "index_stages_on_user_id"
  end

  create_table "tasks", force: :cascade do |t|
    t.text     "topic"
    t.integer  "member"
    t.text     "detail"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id", "created_at"], name: "index_tasks_on_user_id_and_created_at"
    t.index ["user_id"], name: "index_tasks_on_user_id"
  end

routes.rb:

 resources :tasks,          only: [:create, :destroy]

task.rb
class Task < ApplicationRecord
  belongs_to :user
  has_many :stages
  default_scope -> { order(created_at: :desc) }
   validates :user_id, presence: true
   validates :topic, presence: true, length: { maximum: 140 }
   validates :detail, presence: true, length: { maximum: 140 }

end
</code>```

Project_pages_controller.rb:

```<code>def home
    if logged_in?
      @task = current_user.tasks.build
end

_task_form.html.erb:

<%= form_for(@task) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_field :topic, placeholder: "Compose new task..." %>
    <%= f.text_area :detail, placeholder: "Write task details..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

This is the show page
</code>```

show.html.erb

```<code>  <div class="col-md-8">
    <% if @user.tasks.any? %>
      <% if @user.stages.any? %>
      <h3>Tasks (<%= @user.tasks.count %>)</h3>
      <ol class="tasks">
        <%= render @tasks %>
        <%= render @stages %>
      </ol>
      <%= will_paginate @tasks %>
       <% end %>
    <% end %>
  </div>
</code>```

This is my controller;

```<code>class TasksController < ApplicationController
    include TasksHelper
  before_action :logged_in_user, only: [:create, :destroy]

  def create
    @task = current_user.tasks.build(task_params)
    if @task.save
      flash[:success] = "Task created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'workshareapp_pages/home'
    end
  end

  def destroy
  end

  private

    def task_params
      params.require(:task).permit(:detail)
    end

end
</code>```

答:
validates :topic, presence: true, length: { maximum: 140 }
This clause validates the topic attribute in your record to be present and within 140 char length. This is used to validate record before save. You may remove it if you really dont need it here. Another option you can create a form model which is used specifically for this form.</p>

Body:
After typing in topic and details in the appropriate text field and area, it still shows "validation error" "Topic cannot be empty". what is the problem? I cannot seem to figure it out.

This is the task partial
_task.html.erb:

 <li id="task-<%= task.id %>">
      <%= link_to gravatar_for(task.user, size: 50), task.user %>
      <%= link_to task.user.name, task.user %>
      Title:
       <%= task.topic %>
      Details:
      <%= task.detail %>

        Posted <%= time_ago_in_words(task.created_at) %> ago.

Schema:

ActiveRecord::Schema.define(version: 20170526194708) do

  create_table "stages", force: :cascade do |t|
    t.text     "topic"
    t.datetime "duration"
    t.text     "detail"
    t.integer  "task_id"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["task_id"], name: "index_stages_on_task_id"
    t.index ["user_id", "created_at"], name: "index_stages_on_user_id_and_created_at"
    t.index ["user_id"], name: "index_stages_on_user_id"
  end

  create_table "tasks", force: :cascade do |t|
    t.text     "topic"
    t.integer  "member"
    t.text     "detail"
    t.integer  "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["user_id", "created_at"], name: "index_tasks_on_user_id_and_created_at"
    t.index ["user_id"], name: "index_tasks_on_user_id"
  end

routes.rb:

 resources :tasks,          only: [:create, :destroy]

task.rb
class Task < ApplicationRecord
  belongs_to :user
  has_many :stages
  default_scope -> { order(created_at: :desc) }
   validates :user_id, presence: true
   validates :topic, presence: true, length: { maximum: 140 }
   validates :detail, presence: true, length: { maximum: 140 }

end

Project_pages_controller.rb:

def home
    if logged_in?
      @task = current_user.tasks.build
end

_task_form.html.erb:

<%= form_for(@task) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

    <%= f.text_field :topic, placeholder: "Compose new task..." %>
    <%= f.text_area :detail, placeholder: "Write task details..." %>

  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

This is the show page

show.html.erb

    <% if @user.tasks.any? %>
      <% if @user.stages.any? %>

Tasks (<%= @user.tasks.count %>)

        <%= render @tasks %>
        <%= render @stages %>

      <%= will_paginate @tasks %>
       <% end %>
    <% end %>

This is my controller;

class TasksController < ApplicationController
    include TasksHelper
  before_action :logged_in_user, only: [:create, :destroy]

  def create
    @task = current_user.tasks.build(task_params)
    if @task.save
      flash[:success] = "Task created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'workshareapp_pages/home'
    end
  end

  def destroy
  end

  private

    def task_params
      params.require(:task).permit(:detail)
    end

end


问:
Git reset and than pull
In my scenario, I'm doing:

git reset <commit>

followed immediately by:

git pull --ff-only

From my understanding of git, this action should success, and just re-do (fast forward) the history that I reset.

However, I'm getting:
error: The following untracked working tree files would be overwritten by merge: on many of my files, and the operation fails.

Does anyone know why isn't it working as I could expect? Thanks!

答:
git reset <commit> is actually execute git reset --mixed <commit> (because it’s default).

There has --mixed, --soft and --hard options for you to choose:

--soft

Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all
  your changed files "Changes to be committed", as git status would put
  it.

--mixed

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has
  not been updated. This is the default action. If -N is specified,
  removed paths are marked as intent-to-add.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since  are discarded.

More option of git reset, you can refer git book.

For your situation, you can use git reset --hard <commit> instead.

Title: Git reset and than pull


问:
Loading a WPF Window without showing it
I create a global hot key to show a window by PInvoking RegisterHotKey(). But to do this I need that window's HWND, which doesn't exist until the window is loaded, that means shown for the first time. But I don't want to show the window before I can set the hot key. Is there a way to create a HWND for that window that is invisible to the user?

答:
I've created extension method for showing invisible window, next Show calls will behave OK.

```<code>public static class WindowHelper
{
    public static void ShowInvisible(this Window window)
    {
        // saving original settings
        bool needToShowInTaskbar = window.ShowInTaskbar;
        WindowState initialWindowState = window.WindowState;

        // making window invisible
        window.ShowInTaskbar = false;
        window.WindowState = WindowState.Minimized;

        // showing and hiding window
        window.Show();
        window.Hide();

        // restoring original settings
        window.ShowInTaskbar = needToShowInTaskbar;
        window.WindowState = initialWindowState;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Loading a WPF Window without showing it

Body:
I've created extension method for showing invisible window, next Show calls will behave OK.

public static class WindowHelper
{
    public static void ShowInvisible(this Window window)
    {
        // saving original settings
        bool needToShowInTaskbar = window.ShowInTaskbar;
        WindowState initialWindowState = window.WindowState;

        // making window invisible
        window.ShowInTaskbar = false;
        window.WindowState = WindowState.Minimized;

        // showing and hiding window
        window.Show();
        window.Hide();

        // restoring original settings
        window.ShowInTaskbar = needToShowInTaskbar;
        window.WindowState = initialWindowState;
    }
}


问:
PHP error during SELECT on prepared statement (fetch_assoc() function)
this is a common problem, but i already did my research and I couldn't find a solution. SO here I am.

The error i am getting is : Fatal error: Call to a member function fetch_assoc() on a non-object

Firstly I have the mysqlnd enabled. Secondly My query does not have an error. I am being able to run it in the phpmyadmin with no problems.

Here is the query thats is being run:

```<code>SELECT * FROM photos WHERE name LIKE '%ait%'
UNION
SELECT photos.* FROM photos, photo_tag, tags
WHERE photo_tag.photo_id = photos.id
AND photo_tag.tag_id = tags.id
AND tags.name IN('ait')
</code>```

And here is the code where the error happens (more specifically in the fetch_assoc() function):

```<code>$stmt = $this->conn->prepare($query);
if($stmt){
    $stmt->execute();
    while($row = $stmt->get_result()->fetch_assoc()){
        $photo = new Photo(null, null, null, null);
        $photo->id=$row["id"];
        $photo->userId=$row["user_id"];
        $photo->name = $row["name"];
        $photo->photoPath=$row["photo_path"];
        $result[] = $photo;
    }
    return $result;
}else{
    var_dump($this->db->error);
}
</code>```

If you guys could help me with this I would be very grateful.

答:
You should only call get_result() once, not every time through the loop.

```<code>$stmt->execute();
$stmt_result = $stmt->get_result();
while($row = $stmt_result->fetch_assoc()){
    $photo = new Photo(null, null, null, null);
    $photo->id=$row["id"];
    $photo->userId=$row["user_id"];
    $photo->name = $row["name"];
    $photo->photoPath=$row["photo_path"];
    $result[] = $photo;
}
</code>```

Body:
this is a common problem, but i already did my research and I couldn't find a solution. SO here I am.

The error i am getting is : Fatal error: Call to a member function fetch_assoc() on a non-object

Firstly I have the mysqlnd enabled. Secondly My query does not have an error. I am being able to run it in the phpmyadmin with no problems.

Here is the query thats is being run:

SELECT * FROM photos WHERE name LIKE '%ait%'
UNION
SELECT photos.* FROM photos, photo_tag, tags
WHERE photo_tag.photo_id = photos.id
AND photo_tag.tag_id = tags.id
AND tags.name IN('ait')

And here is the code where the error happens (more specifically in the fetch_assoc() function):

$stmt = $this->conn->prepare($query);
if($stmt){
    $stmt->execute();
    while($row = $stmt->get_result()->fetch_assoc()){
        $photo = new Photo(null, null, null, null);
        $photo->id=$row["id"];
        $photo->userId=$row["user_id"];
        $photo->name = $row["name"];
        $photo->photoPath=$row["photo_path"];
        $result[] = $photo;
    }
    return $result;
}else{
    var_dump($this->db->error);
}

If you guys could help me with this I would be very grateful.

Body:
You should only call get_result() once, not every time through the loop.

$stmt->execute();
$stmt_result = $stmt->get_result();
while($row = $stmt_result->fetch_assoc()){
    $photo = new Photo(null, null, null, null);
    $photo->id=$row["id"];
    $photo->userId=$row["user_id"];
    $photo->name = $row["name"];
    $photo->photoPath=$row["photo_path"];
    $result[] = $photo;
}


答:
Just try this using array_diff_assoc function in PHP:

```<code>     //array1 is as static array I have created to validate the sheet columns
 $array1 = array('Category','Subcategory','Unknown','Age','0-9','Unknown','Region','Zone');

 // array2 is coming dynamically from excel sheet columns so user can change the names
 $array2 = array('Category','Subcategory','Unknowns','Age','0-9','Unknown','Region');

 $diff = array_diff_assoc($array1,$array2);
 $columnNames = implode(',',$diff);

 echo $columnNames;
</code>```

For your reference go to this site http://php.net/manual/en/function.array-diff-assoc.php

Title: Compare 2 arrays for difference with some values repeating

Body:
Just try this using array_diff_assoc function in PHP:

     //array1 is as static array I have created to validate the sheet columns
 $array1 = array('Category','Subcategory','Unknown','Age','0-9','Unknown','Region','Zone');

 // array2 is coming dynamically from excel sheet columns so user can change the names
 $array2 = array('Category','Subcategory','Unknowns','Age','0-9','Unknown','Region');

 $diff = array_diff_assoc($array1,$array2);
 $columnNames = implode(',',$diff);

 echo $columnNames;

For your reference go to this site http://php.net/manual/en/function.array-diff-assoc.php


问:
Oracle Custom sorting is not working
I have an issue while sorting a column in a custom order in Oracle.

I need a particular row in the column to come first and then the remaining items should come down below in the alphabetic order. The column has a data starting with alphabets, numbers and special characters.. whenever i try to sort the column by ASC it is returning me starting with Special characters first following by number and then alphabets.

Eg result Set

```<code>ACCOUNT_NAME
-------------
First Row
Second Row
Third Row
Fourth Row
Fifth Row
$Specialchar Row
4Number Row
Alpha Row
</code>```

Expected result in the below order

```<code>ACCOUNT_NAME
-------------
First Row
Alpha Row
Fifth Row
Fourth Row
Second Row
Third Row
4Number Row
$Specialchar Row
</code>```

I have tried executing the below query but it doesn't seems to be work

```<code>SELECT ACCOUNT_NAME   FROM ACCOUNT
   ORDER BY decode(ACCOUNT_NAME,'First Row',1),
    regexp_substr(UPPER(ACCOUNT_NAME), '^[a-zA-Z]') ASC;
</code>```

答:
I think ASCII function will solve your issue. However it is easy to sort based on 1st char of the value.
E.g. 'AA' will come before '11',which will come before '$$'. However 'A$' will come before 'A4', which will come before 'AA' unless your extend the program to all characters. Extending this is quite tiresome.

So the code is as follows.

```<code>WITH data_set AS
     (SELECT '001' emp_id, 'aaa' emp_name, '005' mgr_id
        FROM DUAL
      UNION
      SELECT '005' emp_id, 'bbb' emp_name, '010' mgr_id
        FROM DUAL
      UNION
      SELECT '010' emp_id, 'ccc' emp_name, '050' mgr_id
        FROM DUAL
      UNION
      SELECT '020' emp_id, '4xy' emp_name, '050' mgr_id
        FROM DUAL
      UNION
      SELECT '050' emp_id, '$52' emp_name, '100' mgr_id
        FROM DUAL
      UNION
      SELECT '100' emp_id, '555' emp_name, '200' mgr_id
        FROM DUAL
      UNION
      SELECT '200' emp_id, '@$' emp_name, NULL mgr_id
        FROM DUAL)
SELECT   emp_name,
         CASE
            WHEN (ASCII (emp_name) BETWEEN 65 AND 90)
             OR (ASCII (emp_name) BETWEEN 97 AND 122)
               THEN 1
            WHEN ASCII (emp_name) BETWEEN 48 AND 57
               THEN 2
            ELSE 3
         END val
    FROM data_set
ORDER BY val;
</code>```

Title: Oracle Custom sorting is not working

Body:
I have an issue while sorting a column in a custom order in Oracle.

I need a particular row in the column to come first and then the remaining items should come down below in the alphabetic order. The column has a data starting with alphabets, numbers and special characters.. whenever i try to sort the column by ASC it is returning me starting with Special characters first following by number and then alphabets.

Eg result Set

ACCOUNT_NAME
-------------
First Row
Second Row
Third Row
Fourth Row
Fifth Row
$Specialchar Row
4Number Row
Alpha Row

Expected result in the below order

ACCOUNT_NAME
-------------
First Row
Alpha Row
Fifth Row
Fourth Row
Second Row
Third Row
4Number Row
$Specialchar Row

I have tried executing the below query but it doesn't seems to be work

SELECT ACCOUNT_NAME   FROM ACCOUNT
   ORDER BY decode(ACCOUNT_NAME,'First Row',1),
    regexp_substr(UPPER(ACCOUNT_NAME), '^[a-zA-Z]') ASC;

Body:
I think ASCII function will solve your issue. However it is easy to sort based on 1st char of the value.
E.g. 'AA' will come before '11',which will come before '$$'. However 'A$' will come before 'A4', which will come before 'AA' unless your extend the program to all characters. Extending this is quite tiresome.

So the code is as follows.

WITH data_set AS
     (SELECT '001' emp_id, 'aaa' emp_name, '005' mgr_id
        FROM DUAL
      UNION
      SELECT '005' emp_id, 'bbb' emp_name, '010' mgr_id
        FROM DUAL
      UNION
      SELECT '010' emp_id, 'ccc' emp_name, '050' mgr_id
        FROM DUAL
      UNION
      SELECT '020' emp_id, '4xy' emp_name, '050' mgr_id
        FROM DUAL
      UNION
      SELECT '050' emp_id, '$52' emp_name, '100' mgr_id
        FROM DUAL
      UNION
      SELECT '100' emp_id, '555' emp_name, '200' mgr_id
        FROM DUAL
      UNION
      SELECT '200' emp_id, '@$' emp_name, NULL mgr_id
        FROM DUAL)
SELECT   emp_name,
         CASE
            WHEN (ASCII (emp_name) BETWEEN 65 AND 90)
             OR (ASCII (emp_name) BETWEEN 97 AND 122)
               THEN 1
            WHEN ASCII (emp_name) BETWEEN 48 AND 57
               THEN 2
            ELSE 3
         END val
    FROM data_set
ORDER BY val;


问:
Intent to launch fingerprint enrollment screen
How to launch finger print enrollment settings screen(Add fingerprint screen) from my app?

After enrolling finger print, is there any way to navigate back to my application? (with startActivityForResult)

答:
Suggested answer won't work for example on Huawei P9. Fingerprint settings on this model is available from:
startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));.

Another thing is that when you launch system settings on your app task, enroll new fingerprint and return by back press you won't be able to encrypt any message on first authorization. The best thing is if user set app to background and enroll finger on his own, then restore app, encrypting will work. I have no idea what is the reason of such behaviour, so I suggest to just inform user about posibility of enroll finger.


问:
Moodle: Files uploaded via File API get corrupted when viewed
So I am developing a new course-format, in which a picture is associated with each activity in a course, and presented visually. I created the course format, overrode the renderer etc. That worked all fine. However, the images are supposed to be custom generated and since it has to work for all existing and future, I put some additional code into the general course module form, enabling an image upload.

After admittedly some struggle on my part to get the File API working, it now all works fine. Only in my course format, there is an additional heading, under which you can upload a single image. This gets saved to the database fine, it is not in draft and it is viewable in my dataroots filedir perfectly if I follow the contenthash in the database. It even gets loaded into the form as a default fine. However, if I try to work with the image, all tests run fine (.is_valid_img()etc) and I even get offered to download a file. However, when I do it is corrupted and my file viewer says: "Critical Error: Not a png file". Needless to say it is not displayed on my actual course site.

When I look at the file in filedir, it very clearly is a png. Please, I would be thankful for any help, since I have tried alot and am at my wits end.

答:
It sounds to me like you are getting some sort of output on the page before the PNG file is sent - that would be added to the start of the file and cause it not to work as a PNG file.

I would suggest you open the file in a hex editor and check the start of the file - it should look like https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header, so look for extra characters before that.

As for where the extra characters come from - they may be an obvious warning / error message (which should be easy to track down and fix). Alternatively, you may have some stray 'echo' statements (again, fairly easy to track down). The worst problems to find are extra characters before the opening 'php' tags of a file somewhere in your install or after the closing tag at the end of a file (which is why you should never use closing PHP tags). Finding these will come down to searching through all your customised code files to locate them.


问:
Retaining n most recent directories in a backup script
I have directory in /home/backup/ that stores yearly backups. Inside the backup folder, we have these directories:

```<code>/home/backup/2012
/home/backup/2013
/home/backup/2014
/home/backup/2015
/home/backup/2016
/home/backup/2017
</code>```

and every year I have to clean up the data, keeping only the last three years of backup.

In the above case, I have to delete:

```<code>/home/backup/2012
/home/backup/2013
/home/backup/2014
</code>```

What is the best way to find the directories to be deleted?  I have this but it doesn't work:

```<code>find /home/ecentrix/recording/ -maxdepth 1 -mindepth 1 -type d -ctime +1095 -exec rm -rf {} \;
</code>```

Do you guys have another idea to do that?

答:
Consider this:

```<code>find /home/backup/2* -maxdepth 1 | sort -r | awk "NR>3" | xargs rm -rf
</code>```

How this works

Produce a list of filenames starting with "2", only under /home/backup/

Alphabetically sort the list, in reverse order.

Use AWK to filter the number of rows in the list. NR specifies the number of reverse-sorted rows. You can change that 3 to be however many rows you want to be left. So if you only wanted the latest two years, change the 3 to a 2. If you wanted the latest 10 to be kept, make it "NR>10".

Append the resultant list to the command "rm -rf".

Run as dedicated user, for safety

The danger here is that I'm suggesting rm -rf. This is risky. If something goes wrong, you could delete things you want to keep. I mitigate this risk by only invoking these commands by a dedicated user that ONLY has permissions to delete backup files (and not beyond).

Merit

The merit of this approach is that when you throw it in a cron job and time advances, it'll continue to retain only the latest few directories. So this, I consider to be a general solution to your problem.

Demonstration

To test this, I created a test directory with all the same directories you have. I altered it just to see what would be executed at the end, so I've tried:

```<code>find test01/2* -maxdepth 1 | sort -r | awk "NR>4" | xargs echo rm -rf
</code>```

I used NR>4 rather than NR>3 (as you'd want) because NR>4 shows that we're selecting how many rows to remove from the list, and thus not delete.

Here's what I get:

The second-to-final command above changed the final stage not to echo what it would do, but actually do it.

I have a crude copy of a dump of this in a script as I use it on some servers of mine, you can view it here: https://github.com/docdawning/teenybackup

Required for success

This approach DEPENDS on the alphabetization of whatever the find command produces. In my case, I use ISO-8601 type dates, which lend themselves entirely to being inherently date-sorted when they're alphabetized. Your YYYY type dates totally qualify.

Additional Safety

I recommend that you change your backups to be stored as tar archives. Then you can change the rm -rf to a simple rm. This is a lot safer, though not fool-proof. Regardless, you really should run this as a dedicated otherwise unprivileged user (as you should do for any script calling a delete, in my opinion).

Be aware that if you start it with

```<code>find /home/backup
</code>```

Then the call to xargs will include /home/backup itself, which would be a disaster, because it'd get deleted too. So you must search within that path. Insteading calling it with the below would work:

```<code>find /home/backup/*
</code>```

The 2* I gave above is just a way of somewhat limiting the search operation.

Warranty

None; this is the Internet. Be careful. Test things heavily to convince yourself. Also, maybe get some offline backups too.

Finally - I previously posted this as an answer, but made the fatal mistake of representing the find command based out of /home/backup and not /home/backup/* or /home/backup/2*. This caused /home/backup to also be sent for deletion, which would be a disaster. It's a very small distinction that I've tried to be clear about above. I've deleted that previous answer and replaced it with this one.

Body:
I have directory in /home/backup/ that stores yearly backups. Inside the backup folder, we have these directories:

/home/backup/2012
/home/backup/2013
/home/backup/2014
/home/backup/2015
/home/backup/2016
/home/backup/2017

and every year I have to clean up the data, keeping only the last three years of backup.

In the above case, I have to delete:

/home/backup/2012
/home/backup/2013
/home/backup/2014

What is the best way to find the directories to be deleted?  I have this but it doesn't work:

find /home/ecentrix/recording/ -maxdepth 1 -mindepth 1 -type d -ctime +1095 -exec rm -rf {} \;

Do you guys have another idea to do that?

Body:
Consider this:

find /home/backup/2* -maxdepth 1 | sort -r | awk "NR>3" | xargs rm -rf

How this works

Produce a list of filenames starting with "2", only under /home/backup/

Alphabetically sort the list, in reverse order.

Use AWK to filter the number of rows in the list. NR specifies the number of reverse-sorted rows. You can change that 3 to be however many rows you want to be left. So if you only wanted the latest two years, change the 3 to a 2. If you wanted the latest 10 to be kept, make it "NR>10".

Append the resultant list to the command "rm -rf".

Run as dedicated user, for safety

The danger here is that I'm suggesting rm -rf. This is risky. If something goes wrong, you could delete things you want to keep. I mitigate this risk by only invoking these commands by a dedicated user that ONLY has permissions to delete backup files (and not beyond).

Merit

The merit of this approach is that when you throw it in a cron job and time advances, it'll continue to retain only the latest few directories. So this, I consider to be a general solution to your problem.

Demonstration

To test this, I created a test directory with all the same directories you have. I altered it just to see what would be executed at the end, so I've tried:

find test01/2* -maxdepth 1 | sort -r | awk "NR>4" | xargs echo rm -rf

I used NR>4 rather than NR>3 (as you'd want) because NR>4 shows that we're selecting how many rows to remove from the list, and thus not delete.

Here's what I get:

The second-to-final command above changed the final stage not to echo what it would do, but actually do it.

I have a crude copy of a dump of this in a script as I use it on some servers of mine, you can view it here: https://github.com/docdawning/teenybackup

Required for success

This approach DEPENDS on the alphabetization of whatever the find command produces. In my case, I use ISO-8601 type dates, which lend themselves entirely to being inherently date-sorted when they're alphabetized. Your YYYY type dates totally qualify.

Additional Safety

I recommend that you change your backups to be stored as tar archives. Then you can change the rm -rf to a simple rm. This is a lot safer, though not fool-proof. Regardless, you really should run this as a dedicated otherwise unprivileged user (as you should do for any script calling a delete, in my opinion).

Be aware that if you start it with

find /home/backup

Then the call to xargs will include /home/backup itself, which would be a disaster, because it'd get deleted too. So you must search within that path. Insteading calling it with the below would work:

find /home/backup/*

The 2* I gave above is just a way of somewhat limiting the search operation.

Warranty

None; this is the Internet. Be careful. Test things heavily to convince yourself. Also, maybe get some offline backups too.

Finally - I previously posted this as an answer, but made the fatal mistake of representing the find command based out of /home/backup and not /home/backup/* or /home/backup/2*. This caused /home/backup to also be sent for deletion, which would be a disaster. It's a very small distinction that I've tried to be clear about above. I've deleted that previous answer and replaced it with this one.


问:
Reactjs clientside and Server side both together
I am new in Reactjs. I create architecture using Reactjs.
When user comes for site and hit url then server.js (server side Rendering) file call. and in browser javascript enable then it's call client side call and if java script disable then run server side. show, How can I achieve this. i take refernce below url:

http://jmfurlott.com/tutorial-setting-up-a-simple-isomorphic-react-app/

Please help me.

答:
In SSR(Server side rendering) the first render is performed on the server and the rendered HTML is returned to the user unlike in CSR(Client Side Rendering) where a basic html is sent and then react populates the DOM on the client side. Check out this project. They are based on this SSR architecture.

https://github.com/reactGo/reactGo


问:
How to play .mp4 video as a background video in Android?
I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link.

https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s

ublic class MainActivity extends AppCompatActivity {

```<code>private VideoView bgVideo;

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

        bgVideo=(VideoView) findViewById(R.id.bg_videoview);

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

        bgVideo.setVideoURI(uri);
        bgVideo.start();

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }
}
</code>```

I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this.

```<code>06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32)
06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32
06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38)
06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38
06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.
</code>```

How can i fix it ?

答:
You need to start bgVideo.start inside onPrepare</p>

```<code>bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
                bgVideo.start();
            }
        });
</code>```

Body:
I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link.

https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s

ublic class MainActivity extends AppCompatActivity {

private VideoView bgVideo;

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

        bgVideo=(VideoView) findViewById(R.id.bg_videoview);

        Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo);

        bgVideo.setVideoURI(uri);
        bgVideo.start();

        bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }
}

I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this.

06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648)
06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648
06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32)
06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32
06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38)
06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38
06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames!  The application may be doing too much work on its main thread.

How can i fix it ?

Body:
You need to start bgVideo.start inside onPrepare

bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
                bgVideo.start();
            }
        });


问:
Java get First and Last duplicate elements of List

In my application i want to get first and repetitive elements from array
eg,

```<code>String[] strings = {"one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one"
                , "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two"
                , "three", "three", "three", "three", "three", "three", "three", "three", "three", "three", "three"
                , "four", "four", "four", "four", "four", "four", "four", "four", "four", "four"
                , "five", "five", "five", "five", "five", "five"
                , "six", "six", "six", "six", "six", "six", "six", "six", "six"
                , "seven", "seven", "seven", "seven", "seven", "seven", "seven", "seven"
                , "eight", "eight", "eight", "eight", "eight", "eight"
                , "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine"
                , "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten"};
</code>```

for the above list i want to get output like

one

one

two

two

three

three

four

four

five

five

six

six

seven

seven

eight

eight

nine

nine

ten

ten

答:
If you are using Java8, you can use Stream API like this.</p>

```<code>    Stream.of(strings)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue() > 1)
            .forEach(entry -> System.out.println(entry.getKey() + "\n" + entry.getKey()));
</code>```

Body:
In my application i want to get first and repetitive elements from array
eg,

String[] strings = {"one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one", "one"
                , "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two", "two"
                , "three", "three", "three", "three", "three", "three", "three", "three", "three", "three", "three"
                , "four", "four", "four", "four", "four", "four", "four", "four", "four", "four"
                , "five", "five", "five", "five", "five", "five"
                , "six", "six", "six", "six", "six", "six", "six", "six", "six"
                , "seven", "seven", "seven", "seven", "seven", "seven", "seven", "seven"
                , "eight", "eight", "eight", "eight", "eight", "eight"
                , "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine", "nine"
                , "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten", "ten"};

for the above list i want to get output like

one

one

two

two

three

three

four

four

five

five

six

six

seven

seven

eight

eight

nine

nine

ten

ten

Body:
If you are using Java8, you can use Stream API like this.

    Stream.of(strings)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue() > 1)
            .forEach(entry -> System.out.println(entry.getKey() + "\n" + entry.getKey()));


问:
How to find the TypeOf a VB6 control in VB.NET
I am writing a .NET DLL to iterate through all controls in the a VB6 Form passed byref.

So far it seems to work VB.NET code:

```<code>Public Sub AddFormRefLegacy(ByRef strAppName As String, ByRef objForm As Object)

        'update the forms caption
        objForm.Caption = FindValue(strAppName, objForm.Name, "", "0", objForm.Caption)

        'iterate through all the controls on the form
        For Each ctl As Object In objForm.Controls
           if TypeOf ctl is Label then
             'this doesn't pick up any labels
           end if
        Next
    End Sub
</code>```

Called from this VB6 code:

```<code>Dim libDD As New Lib.clsDataDictionary
libDD.AddFormRefLegacy "nnne", Me
</code>```

but the TypeOf operator does not work. Is there another way to find the type of control?

答: Have you tried using the TypeName function? Does it return anything useful for TypeName(ctl)?</p>

Body:
I am writing a .NET DLL to iterate through all controls in the a VB6 Form passed byref.

So far it seems to work VB.NET code:

Public Sub AddFormRefLegacy(ByRef strAppName As String, ByRef objForm As Object)

        'update the forms caption
        objForm.Caption = FindValue(strAppName, objForm.Name, "", "0", objForm.Caption)

        'iterate through all the controls on the form
        For Each ctl As Object In objForm.Controls
           if TypeOf ctl is Label then
             'this doesn't pick up any labels
           end if
        Next
    End Sub

Called from this VB6 code:

Dim libDD As New Lib.clsDataDictionary
libDD.AddFormRefLegacy "nnne", Me

but the TypeOf operator does not work. Is there another way to find the type of control?


问:
Groovy template engine with parameters matching a Java class name
I'm sure this is a simple one...

We use the Groovy template engine to format XML documents into human-readable form. The code scans the XML and creates a map with an entry for each item in the XML, and then this is passed to the Groovy template engine.

Problem occurs when the XML contains an attribute that matches a class name -
 something like this: <Date>some date</Date>. If the template file specifies Date is $Date (for example), instead of the actual date string, we're getting class java.util.Date. We've tried variations on $Date like ${Date} and ${Date.toString()}, etc with no luck.

We think the issue is that Groovy confuses Date the input variable, and the java.util.Date class, but I'm sure there's some sort of syntax that will make this work properly. Since we feed arbitrary user-defined XML through this, we really can't control things like the attribute names in the XML.

Here's a few lines of code to replicate the problem:

```<code>def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def tf = new File("Test.template")
def gte = new GStringTemplateEngine()
def tpl = gte.createTemplate(tf).make(map.withDefault{null})
println tpl.toString()
</code>```

The "Test.template" file contains:

```<code>Date is ${Date.toString()}.
Date is ${Date2.toString()}.
</code>```

The output we get is:

```<code>Date is class java.util.Date.
Date is Tue Jun 06 20:22:16 EDT 2017.
</code>```

答:
Yes, seems groovy takes class Date prior to binding variable named Date

So, why not to pass all xml attributes as one binding variable:

```<code>def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def gte = new groovy.text.GStringTemplateEngine()
def tpl = gte.createTemplate('''
Date  :: ${ctx.Date.toString()}
Date2 :: ${ctx.Date2.toString()}
''').make( [ctx:map].withDefault{null})

println tpl.toString()
</code>```

also it's possible to access variables through this kind of accessor delegate.'My strange Variable':

```<code>def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def gte = new groovy.text.GStringTemplateEngine()
def tpl = gte.createTemplate('''
Date  :: ${delegate.'Date'.toString()}
Date2 :: ${Date2.toString()}
''').make( map.withDefault{null})

println tpl.toString()
</code>```

Body:
I'm sure this is a simple one...

We use the Groovy template engine to format XML documents into human-readable form. The code scans the XML and creates a map with an entry for each item in the XML, and then this is passed to the Groovy template engine.

Problem occurs when the XML contains an attribute that matches a class name -
 something like this: <Date>some date</Date>. If the template file specifies Date is $Date (for example), instead of the actual date string, we're getting class java.util.Date. We've tried variations on $Date like ${Date} and ${Date.toString()}, etc with no luck.

We think the issue is that Groovy confuses Date the input variable, and the java.util.Date class, but I'm sure there's some sort of syntax that will make this work properly. Since we feed arbitrary user-defined XML through this, we really can't control things like the attribute names in the XML.

Here's a few lines of code to replicate the problem:

def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def tf = new File("Test.template")
def gte = new GStringTemplateEngine()
def tpl = gte.createTemplate(tf).make(map.withDefault{null})
println tpl.toString()

The "Test.template" file contains:

Date is ${Date.toString()}.
Date is ${Date2.toString()}.

The output we get is:

Date is class java.util.Date.
Date is Tue Jun 06 20:22:16 EDT 2017.

Body:
Yes, seems groovy takes class Date prior to binding variable named Date

So, why not to pass all xml attributes as one binding variable:

def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def gte = new groovy.text.GStringTemplateEngine()
def tpl = gte.createTemplate('''
Date  :: ${ctx.Date.toString()}
Date2 :: ${ctx.Date2.toString()}
''').make( [ctx:map].withDefault{null})

println tpl.toString()

also it's possible to access variables through this kind of accessor delegate.'My strange Variable':

def map = [:]
map.putAt("Date",  new Date())  // Fails
map.putAt("Date2", new Date())  // Works
def gte = new groovy.text.GStringTemplateEngine()
def tpl = gte.createTemplate('''
Date  :: ${delegate.'Date'.toString()}
Date2 :: ${Date2.toString()}
''').make( map.withDefault{null})

println tpl.toString()


问:
WCF - How to deserialize a byte parameter
I wrote a WCF restful service that accepts string and a byte parameter. The problem is that the web service works fine if the byte is blank, but if there is a value in the byte parameter then i get the following error message :

'There was an error deserializing the object of type System.Byte[]. End element 'Document' from namespace '' expected.

Here is my code

WCF Interface

```<code>[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "IDocument")]
string IndexDocument(byte[] Document, string DocumentType);
</code>```

WCF Interface implementation

```<code>public string IndexDocument(byte[] Document, string DocumentType)
{
}
</code>```

Client program

```<code> private class Documentt
        {
            public byte[] Document { get; set; }
            public string DocumentType { get; set; }
        }

static async Task RunAsync()
        {
            byte[] bytes = System.IO.File.ReadAllBytes(openFileDialog.FileName);

            var parameters = new Documentt()
            {
                Document = bytes,
                DocumentType = "AA"
            };

            using (HttpClient client = new HttpClient())
            {
                var request = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json");

                var response = client.PostAsync(new Uri("http://localhost:59005/ServiceCall.svc/IDocument"), request);
                var result = response.Result;

            }
        }
</code>```

What am i doing wrong here ? I wanted to make use of bytes because i wanted to write a cross platform(to be used by java, c++, c# etc) web services.

答:
that's because you are using datacontact as your deserilizer and Json.NET as your sterilizer.  remember they act differently with some kind of object like DateTime and Byte[].
please use this method in order to serialize your request:

```<code>public static string DataJsonSerializer<T>(T obj)
{
    var json = string.Empty;
    var JsonSerializer = new DataContractJsonSerializer(typeof(T));

    using (var mStrm = new MemoryStream())
    {
        JsonSerializer.WriteObject(mStrm, obj);
        mStrm.Position = 0;
        using (var sr = new StreamReader(mStrm))
            json = sr.ReadToEnd();
    }

    return json;
}
</code>```

your request should be like this:

```<code>var request = new StringContent(DataJsonSerializer(parameters), Encoding.UTF8, "application/json");
</code>```

Body:
I wrote a WCF restful service that accepts string and a byte parameter. The problem is that the web service works fine if the byte is blank, but if there is a value in the byte parameter then i get the following error message :

'There was an error deserializing the object of type System.Byte[]. End element 'Document' from namespace '' expected.

Here is my code

WCF Interface

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "IDocument")]
string IndexDocument(byte[] Document, string DocumentType);

WCF Interface implementation

public string IndexDocument(byte[] Document, string DocumentType)
{
}

Client program

 private class Documentt
        {
            public byte[] Document { get; set; }
            public string DocumentType { get; set; }
        }

static async Task RunAsync()
        {
            byte[] bytes = System.IO.File.ReadAllBytes(openFileDialog.FileName);

            var parameters = new Documentt()
            {
                Document = bytes,
                DocumentType = "AA"
            };

            using (HttpClient client = new HttpClient())
            {
                var request = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json");

                var response = client.PostAsync(new Uri("http://localhost:59005/ServiceCall.svc/IDocument"), request);
                var result = response.Result;

            }
        }

What am i doing wrong here ? I wanted to make use of bytes because i wanted to write a cross platform(to be used by java, c++, c# etc) web services.

Body:
that's because you are using datacontact as your deserilizer and Json.NET as your sterilizer.  remember they act differently with some kind of object like DateTime and Byte[].
please use this method in order to serialize your request:

public static string DataJsonSerializer<T>(T obj)
{
    var json = string.Empty;
    var JsonSerializer = new DataContractJsonSerializer(typeof(T));

    using (var mStrm = new MemoryStream())
    {
        JsonSerializer.WriteObject(mStrm, obj);
        mStrm.Position = 0;
        using (var sr = new StreamReader(mStrm))
            json = sr.ReadToEnd();
    }

    return json;
}

your request should be like this:

var request = new StringContent(DataJsonSerializer(parameters), Encoding.UTF8, "application/json");


问:
i am trying to split a full name to first middle and last name in pandas but i am stuck at replace
i am trying to break the name into two parts and keeping first name last name and finally replacing the common part in all of them such that first name is must then last name then if middle name remain it is added to column

```<code>df['owner1_first_name'] = df['owner1_name'].str.split().str[0].astype(str,
errors='ignore')
df['owner1_last_name'] =
df['owner1_name'].str.split().str[-1].str.replace(df['owner1_first_name'],
"").astype(str, errors='ignore')
['owner1_middle_name'] =
df['owner1_name'].str.replace(df['owner1_first_name'],
"").str.replace(df['owner1_last_name'], "").astype(str, errors='ignore')
</code>```

the problem is i am not able to use
    .str.replace(df['owner1_name'], "")

as  i am getting an error
    "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

is there any replacement sytax in pandas for what i am tryin to achieve

my desired output is

full name = THOMAS MARY D which is in column owner1_name

I want

```<code>owner1_first_name = THOMAS
owner1_middle_name = MARY
owner1_last_name = D
</code>```

答:
Just change your assignment and use another variable:</p>

```<code>split = df['owner1_name'].split()
df['owner1_first_name'] = split[0]
df['owner1_middle_name'] = split[-1]
df['owner1_last_name'] = split[1]
</code>```

Body:
i am trying to break the name into two parts and keeping first name last name and finally replacing the common part in all of them such that first name is must then last name then if middle name remain it is added to column

df['owner1_first_name'] = df['owner1_name'].str.split().str[0].astype(str,
errors='ignore')
df['owner1_last_name'] =
df['owner1_name'].str.split().str[-1].str.replace(df['owner1_first_name'],
"").astype(str, errors='ignore')
['owner1_middle_name'] =
df['owner1_name'].str.replace(df['owner1_first_name'],
"").str.replace(df['owner1_last_name'], "").astype(str, errors='ignore')

the problem is i am not able to use
    .str.replace(df['owner1_name'], "")

as  i am getting an error
    "TypeError: 'Series' objects are mutable, thus they cannot be hashed"

is there any replacement sytax in pandas for what i am tryin to achieve

my desired output is

full name = THOMAS MARY D which is in column owner1_name

I want

owner1_first_name = THOMAS
owner1_middle_name = MARY
owner1_last_name = D

Body:
Just change your assignment and use another variable:

split = df['owner1_name'].split()
df['owner1_first_name'] = split[0]
df['owner1_middle_name'] = split[-1]
df['owner1_last_name'] = split[1]


问:
How to find a number that isn't there?
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

```<code>SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)
</code>```

This doesn't work, "X" is unknown.

Thanks!
Bruce

答:
Here's one way of finding the start and end numbers of the gaps:</p>

```<code>WITH sample_data AS (SELECT 1 ID FROM dual UNION ALL
                     SELECT 2 ID FROM dual UNION ALL
                     SELECT 4 ID FROM dual UNION ALL
                     SELECT 5 ID FROM dual UNION ALL
                     SELECT 8 ID FROM dual UNION ALL
                     SELECT 10 ID FROM dual UNION ALL
                     SELECT 20 ID FROM dual UNION ALL
                     SELECT 22 ID FROM dual UNION ALL
                     SELECT 23 ID FROM dual UNION ALL
                     SELECT 27 ID FROM dual UNION ALL
                     SELECT 28 ID FROM dual)
-- end of mimicking data in a table called "sample_data"
-- see SQL below:
SELECT prev_id + 1 first_number_in_gap,
       ID - 1 last_number_in_gap
FROM   (SELECT ID,
               LAG(ID, 1, ID - 1) OVER (ORDER BY ID) prev_id
        FROM   sample_data)
WHERE  ID - prev_id > 1;

FIRST_NUMBER_IN_GAP LAST_NUMBER_IN_GAP
------------------- ------------------
                  3                  3
                  6                  7
                  9                  9
                 11                 19
                 21                 21
                 24                 26
</code>```

Title: How to find a number that isn't there?

Body:
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)

This doesn't work, "X" is unknown.

Thanks!
Bruce

Body:
Here's one way of finding the start and end numbers of the gaps:

WITH sample_data AS (SELECT 1 ID FROM dual UNION ALL
                     SELECT 2 ID FROM dual UNION ALL
                     SELECT 4 ID FROM dual UNION ALL
                     SELECT 5 ID FROM dual UNION ALL
                     SELECT 8 ID FROM dual UNION ALL
                     SELECT 10 ID FROM dual UNION ALL
                     SELECT 20 ID FROM dual UNION ALL
                     SELECT 22 ID FROM dual UNION ALL
                     SELECT 23 ID FROM dual UNION ALL
                     SELECT 27 ID FROM dual UNION ALL
                     SELECT 28 ID FROM dual)
-- end of mimicking data in a table called "sample_data"
-- see SQL below:
SELECT prev_id + 1 first_number_in_gap,
       ID - 1 last_number_in_gap
FROM   (SELECT ID,
               LAG(ID, 1, ID - 1) OVER (ORDER BY ID) prev_id
        FROM   sample_data)
WHERE  ID - prev_id > 1;

FIRST_NUMBER_IN_GAP LAST_NUMBER_IN_GAP
------------------- ------------------
                  3                  3
                  6                  7
                  9                  9
                 11                 19
                 21                 21
                 24                 26


问:
How can I avoid method swizzling pollution through class hierarchy?
```<code>@interface TestView: UIView
@end
</code>```

I want to replace TestView's(inherited from UIView) layoutSubviews method for some particular reason. But don't want to effect the origin UIView's lifecycle, just want it to work within class TestView.

I simply implement it like this:

```<code>@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}
</code>```

But something went wrong. It seems that UIWindow called customLayout too. I guess it's been polluted. How can I avoid that?

IDE: xCode 8.2.1

OS:  10.12.4

Here's the test code:

```<code>#import "ViewController.h"
#import <objc/runtime.h>

@interface TestView: UIView

@end

@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}

-(void) customLayout {
    [self customLayout];
}

-(instancetype) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = UIColor.grayColor;
    return self;
}

@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    TestView* view = [[TestView alloc] initWithFrame: CGRectMake(0, 0, 300, 300)];
    [self.view addSubview:view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
</code>```

Here's the runtime log:

```<code>2017-06-07 14:51:38.240 swizzleTest[37908:28470016] -[UIWindow customLayout]: unrecognized selector sent to instance 0x7fc3d7009d00
2017-06-07 14:51:38.242 swizzleTest[37908:28470016] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIWindow customLayout]: unrecognized selector sent to instance 0x7fc3d7009d00'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000111450d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010f00021e objc_exception_throw + 48
    2   CoreFoundation                      0x00000001114c0f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x00000001113d6005 ___forwarding___ + 1013
    4   CoreFoundation                      0x00000001113d5b88 _CF_forwarding_prep_0 + 120
    5   swizzleTest                         0x000000010ea2b3fb -[TestView customLayout] + 43
    6   UIKit                               0x000000010f594ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
    7   QuartzCore                          0x0000000114296bf8 -[CALayer layoutSublayers] + 146
    8   QuartzCore                          0x000000011428a440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
    9   QuartzCore                          0x000000011428a2be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    10  QuartzCore                          0x0000000114218318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
    11  QuartzCore                          0x00000001142453ff _ZN2CA11Transaction6commitEv + 475
    12  QuartzCore                          0x0000000114245d6f _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
    13  CoreFoundation                      0x00000001113f5267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    14  CoreFoundation                      0x00000001113f51d7 __CFRunLoopDoObservers + 391
    15  CoreFoundation                      0x00000001113d98a6 CFRunLoopRunSpecific + 454
    16  UIKit                               0x000000010f4c9aea -[UIApplication _run] + 434
    17  UIKit                               0x000000010f4cfc68 UIApplicationMain + 159
    18  swizzleTest                         0x000000010ea2b9af main + 111
    19  libdyld.dylib                       0x000000011240068d start + 1
    20  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

答:
After I override layoutSubviews explicitly in TestView class it works.
Otherwise, class_getInstanceMethod(TestView.class, @selector(layoutSubviews)); can only get -[UIView layoutSubviews] instead of -[TestView layoutSubviews].

Modified code is as follows:

```<code>@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}

-(void) customLayout {
    [self customLayout];
}

-(void) layoutSubviews {
    [super layoutSubviews];
}

-(instancetype) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = UIColor.grayColor;
    return self;
}

@end
</code>```

Body:
@interface TestView: UIView
@end

I want to replace TestView's(inherited from UIView) layoutSubviews method for some particular reason. But don't want to effect the origin UIView's lifecycle, just want it to work within class TestView.

I simply implement it like this:

@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}

But something went wrong. It seems that UIWindow called customLayout too. I guess it's been polluted. How can I avoid that?

IDE: xCode 8.2.1

OS:  10.12.4

Here's the test code:

#import "ViewController.h"
#import <objc/runtime.h>

@interface TestView: UIView

@end

@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}

-(void) customLayout {
    [self customLayout];
}

-(instancetype) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = UIColor.grayColor;
    return self;
}

@end

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    TestView* view = [[TestView alloc] initWithFrame: CGRectMake(0, 0, 300, 300)];
    [self.view addSubview:view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Here's the runtime log:

2017-06-07 14:51:38.240 swizzleTest[37908:28470016] -[UIWindow customLayout]: unrecognized selector sent to instance 0x7fc3d7009d00
2017-06-07 14:51:38.242 swizzleTest[37908:28470016] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIWindow customLayout]: unrecognized selector sent to instance 0x7fc3d7009d00'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000111450d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010f00021e objc_exception_throw + 48
    2   CoreFoundation                      0x00000001114c0f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x00000001113d6005 ___forwarding___ + 1013
    4   CoreFoundation                      0x00000001113d5b88 _CF_forwarding_prep_0 + 120
    5   swizzleTest                         0x000000010ea2b3fb -[TestView customLayout] + 43
    6   UIKit                               0x000000010f594ab8 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1237
    7   QuartzCore                          0x0000000114296bf8 -[CALayer layoutSublayers] + 146
    8   QuartzCore                          0x000000011428a440 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 366
    9   QuartzCore                          0x000000011428a2be _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    10  QuartzCore                          0x0000000114218318 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 280
    11  QuartzCore                          0x00000001142453ff _ZN2CA11Transaction6commitEv + 475
    12  QuartzCore                          0x0000000114245d6f _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 113
    13  CoreFoundation                      0x00000001113f5267 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23
    14  CoreFoundation                      0x00000001113f51d7 __CFRunLoopDoObservers + 391
    15  CoreFoundation                      0x00000001113d98a6 CFRunLoopRunSpecific + 454
    16  UIKit                               0x000000010f4c9aea -[UIApplication _run] + 434
    17  UIKit                               0x000000010f4cfc68 UIApplicationMain + 159
    18  swizzleTest                         0x000000010ea2b9af main + 111
    19  libdyld.dylib                       0x000000011240068d start + 1
    20  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Body:
After I override layoutSubviews explicitly in TestView class it works.
Otherwise, class_getInstanceMethod(TestView.class, @selector(layoutSubviews)); can only get -[UIView layoutSubviews] instead of -[TestView layoutSubviews].

Modified code is as follows:

@implementation TestView

+(void)load {
    Method a = class_getInstanceMethod(TestView.class, @selector(layoutSubviews));
    Method b = class_getInstanceMethod(TestView.class, @selector(customLayout));
    method_exchangeImplementations(a, b);
}

-(void) customLayout {
    [self customLayout];
}

-(void) layoutSubviews {
    [super layoutSubviews];
}

-(instancetype) initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    self.backgroundColor = UIColor.grayColor;
    return self;
}

@end