问:
How to calculate tax in salary
I am working on a payroll project in which I want to calculate overtime, allowance and tax to salary. I want to add overtime and allowance to salary and subtract tax from salary.

The following script works with overtime and allowance but I'm facing problems with calculating tax.

When I enter a tax percentage it should calculate the tax amount from the salary to the tax field and calculate the total. When I enter the tax directly it should calculate the percentage to the taxPercentage field and calculate the total.

$(document).on('change keyup blur', '.add', function(e) {
  add();
});

function add() {
  salary = $('#salary').val();
  allowance = $('#allowance').val() || 0;
  over = $('#over').val() || 0;
  prevTotal = $('#total').val() || 9000;

  if (allowance > 0 || over > 0) {
    total = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
    $('#total').val(total);
  } else {
    $('#total').val(prevTotal);
  }
}

$(document).on('change keyup blur', '.tax', function(e) {
  subtracttax();
});

function subtracttax() {
  salary = $('#salary').val();
  taxPercentage = $('#taxPercentage').val() || 0;
  tax = $('#tax').val() || 0;
  prevTotal = $('#total').val() || 9000;

  if (taxPercentage > 0) {
    total = parseFloat(salary) * parseFloat(taxPercentage) / 100;
    $('#tax').val(total);
    $('#total').val(prevTotal - total);
  } else {
    $('#total').val(prevTotal);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div>
  <label> salary </label>
  <input type="text" id="salary" value="9000" />
</div>
<br>
<div>
  <label> over Time </label>
  <input type="text" class="add" id="over" />
</div>
<br>
<div>
  <label> allowance </label>
  <input type="text" class="add" id="allowance" />
</div>
<br>
<div>
  <label> Tax Percentage</label>
  <input type="text" class="tax" id="taxPercentage" />
</div>
<br>
<div>
  <label> Total Tax</label>
  <input type="text" class="tax" id="tax" />
</div>
<br>
<div>
  <label> Total salary</label>
  <input type="text" id="total" />
</div></code>```

答:
change this line in subtracttax function

```<code>prevTotal = $('#total').val() || 9000;
</code>```

to

```<code>prevTotal = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
</code>```

Problem is you are overriding the total value once the tax value is entered. Instead you should calculate totals each time you make changes.

Title: How to calculate tax in salary

Body:
I am working on a payroll project in which I want to calculate overtime, allowance and tax to salary. I want to add overtime and allowance to salary and subtract tax from salary.

The following script works with overtime and allowance but I'm facing problems with calculating tax.

When I enter a tax percentage it should calculate the tax amount from the salary to the tax field and calculate the total. When I enter the tax directly it should calculate the percentage to the taxPercentage field and calculate the total.

$(document).on('change keyup blur', '.add', function(e) {
  add();
});

function add() {
  salary = $('#salary').val();
  allowance = $('#allowance').val() || 0;
  over = $('#over').val() || 0;
  prevTotal = $('#total').val() || 9000;

  if (allowance > 0 || over > 0) {
    total = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);
    $('#total').val(total);
  } else {
    $('#total').val(prevTotal);
  }
}

$(document).on('change keyup blur', '.tax', function(e) {
  subtracttax();
});

function subtracttax() {
  salary = $('#salary').val();
  taxPercentage = $('#taxPercentage').val() || 0;
  tax = $('#tax').val() || 0;
  prevTotal = $('#total').val() || 9000;

  if (taxPercentage > 0) {
    total = parseFloat(salary) * parseFloat(taxPercentage) / 100;
    $('#tax').val(total);
    $('#total').val(prevTotal - total);
  } else {
    $('#total').val(prevTotal);
  }
}

   salary
  <input type="text" id="salary" value="9000" />

   over Time
  <input type="text" class="add" id="over" />

   allowance
  <input type="text" class="add" id="allowance" />

   Tax Percentage
  <input type="text" class="tax" id="taxPercentage" />

   Total Tax
  <input type="text" class="tax" id="tax" />

   Total salary
  <input type="text" id="total" />

Body:
change this line in subtracttax function

prevTotal = $('#total').val() || 9000;

to

prevTotal = parseFloat(salary) + parseFloat(allowance) + parseFloat(over);

Problem is you are overriding the total value once the tax value is entered. Instead you should calculate totals each time you make changes.


来源: stackexchange

问:
Closest distance of a column
I need to find the two closest distance of each row based on all the values of the column.

I tried to do cross join and  used the lead function to find the distance. I am totally not sure how to write it. Please suggest.

```<code>select a.id,lead(a.value,b.value) as distance from cluster  a , cluster b
</code>```

Input table:

```<code>ID  Values
1   12.1
2   11
3   14
4   10
5   9
6   15
7   16
8   8

ID  Values  Closest_Value
1   12.1    11,10
2   11       9,10
3   14      15,16
4   10       9,11
5   9        8,10
6   15      14,16
7   16      14,15
8   8        9,10
</code>```

答:
One method uses a cross join and aggregation:

```<code>select id, value,
       listagg(other_value, ',') within group (order by diff) as near_values
from (select c.id, c.value, c2.value as other_value
             abs(c2.value = c.value) as diff,
             row_number() over (partition by c.id order by abs(c2.value = c.value)) as seqnum
      from cluster c join
           cluster c2
           on c.id <> c2.id
     ) c
where seqnum <= 2
group by id, value;
</code>```

The above is not particularly efficient for larger amounts of data.  An alternative is to use lead()  and lag() to get the values, unpivot, and aggregate:

```<code>with vals as (
      select c.id, c.value,
             (case when n.n = 1 then prev_value_2
                   when n.n = 2 then prev_value
                   when n.n = 3 then next_value
                   when n.n = 4 then next_value_2
              end) as other_value
      from (select c.*,
                   lag(value, 2) over (order by value) as prev_value_2,
                   lag(value) over (order by value) as prev_value,
                   lead(value) over (order by value) as next_value,
                   lead(value, 2) over (order by value) as next_value_2,
            from clusters c
           ) c cross join
           (select rownum as n
            from clusters
            where rownum <= 4
           ) n  -- just a list of 4 numbers
       )
select v.id, v.value,
       list_agg(other_value, ',') within group (order by diff)
from (select v.*,
             abs(other_value - value) as diff
             row_number() over (partition by id order by abs(other_value - value)) as seqnum
      from vals v
     ) v
where seqnum <= 2
group by id, value;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Closest distance of a column

Body:
I need to find the two closest distance of each row based on all the values of the column.

I tried to do cross join and  used the lead function to find the distance. I am totally not sure how to write it. Please suggest.

select a.id,lead(a.value,b.value) as distance from cluster  a , cluster b

Input table:

ID  Values
1   12.1
2   11
3   14
4   10
5   9
6   15
7   16
8   8

ID  Values  Closest_Value
1   12.1    11,10
2   11       9,10
3   14      15,16
4   10       9,11
5   9        8,10
6   15      14,16
7   16      14,15
8   8        9,10

Body:
One method uses a cross join and aggregation:

select id, value,
       listagg(other_value, ',') within group (order by diff) as near_values
from (select c.id, c.value, c2.value as other_value
             abs(c2.value = c.value) as diff,
             row_number() over (partition by c.id order by abs(c2.value = c.value)) as seqnum
      from cluster c join
           cluster c2
           on c.id <> c2.id
     ) c
where seqnum <= 2
group by id, value;

The above is not particularly efficient for larger amounts of data.  An alternative is to use lead()  and lag() to get the values, unpivot, and aggregate:

with vals as (
      select c.id, c.value,
             (case when n.n = 1 then prev_value_2
                   when n.n = 2 then prev_value
                   when n.n = 3 then next_value
                   when n.n = 4 then next_value_2
              end) as other_value
      from (select c.*,
                   lag(value, 2) over (order by value) as prev_value_2,
                   lag(value) over (order by value) as prev_value,
                   lead(value) over (order by value) as next_value,
                   lead(value, 2) over (order by value) as next_value_2,
            from clusters c
           ) c cross join
           (select rownum as n
            from clusters
            where rownum <= 4
           ) n  -- just a list of 4 numbers
       )
select v.id, v.value,
       list_agg(other_value, ',') within group (order by diff)
from (select v.*,
             abs(other_value - value) as diff
             row_number() over (partition by id order by abs(other_value - value)) as seqnum
      from vals v
     ) v
where seqnum <= 2
group by id, value;


问:
How to implement search features in ASP.NET MVC applications
I can imagine many ways of implemeting search features in an ASP.NET MVC application but since I can't find much documentation I was wondering if you have any common pattern, technology or common approach to implement search features in a ASP.NET MVC application (similar to stackoverflow). Some technologies that I have in mind are:

SQL Server full-text search

External search engine (like Search Server 2008)

Lucene.NET

...but what is the best approach to integrate them with ASP.NET MVC?

Ideas?

答: I believe in one of his blog posts Jeff Atwood talks about how he used sitemaps in order to let google handle most of the searching capabilities on stack overflow. Why write your own searching algorithms when people are likely just going to use google anyway?</p>

OwnerDisplayName: Sacha

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Sacha

OwnerDisplayName: kgrad


问:
Python: truncate a file to 100 lines or less
I'm pretty new to Python - just wondering if there was a library function or easy way to truncate a file to the first 100 lines or less? </p>

答:
```<code>with open("my.file", "r+") as f:
    [f.readline() for x in range(100)]
    f.truncate()
</code>```

EDIT A 5 % speed increase can be had by instead using the xrange iterator and not storing the entire list:

```<code>with open("my.file", "r+") as f:
    for x in xrange(100):
        f.readline()
    f.truncate()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
with open("my.file", "r+") as f:
    [f.readline() for x in range(100)]
    f.truncate()

EDIT A 5 % speed increase can be had by instead using the xrange iterator and not storing the entire list:

with open("my.file", "r+") as f:
    for x in xrange(100):
        f.readline()
    f.truncate()


问:
Is there a way in an ADO Build Pipeline to only build one of the artifacts?
I have an ADO build pipeline that builds three artifacts.  However, while I am developing, I only want one of the artifacts to be built since that is the artifact on which I am working and it takes longer for all of them to build and I don't want to wait.  Can I disable the other artifacts from building?</p>

答:
As I know, you could not use UI to disable some of artifacts which build from one build pipeline. Because we does not provide this feature in VSTS now.

But as workaround, you can use Copy File task in your release to achieve this.

Specify the artifact what you want to work with in release pipeline, and copy it from File A(the source file where these build artifacts is) to File B(any file you want). And then, you can do other thing with this specific build.

Hope this could help -)


问:
Select from a 3-dimensional array with a 2-dimensional array
I have two arrays:

a: a 3-dimensional source array (N x M x 2)

b: a 2-dimensional index array (N x M) containing 0 and 1s.

I want to use the indices in b to select the corresponding elements of a in its third dimension. The resulting array should have the dimensions N x M. Here is the example as code:

```<code>import numpy as np

a = np.array( # dims: 3x3x2
    [[[ 0,  1],
     [ 2,  3],
     [ 4,  5]],
    [[ 6,  7],
     [ 8,  9],
     [10, 11]],
    [[12, 13],
     [14, 15],
     [16, 17]]]
)
b = np.array( # dims: 3x3
    [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
)

# select the elements in a according to b
# to achieve this result:
desired = np.array(
  [[ 1,  3,  5],
   [ 7,  9, 11],
   [13, 15, 17]]
)
</code>```

At first, I thought this must have a simple solution but I could not find one at all. Since I would like to port it to tensorflow, I would appreciate if somebody knows a numpy-type solution for this.

Edit: The third dimension of a might contain more than two elements. Hence, b might also contain indices different from 0 and 1 - it is not a boolean mask.

Body:
I have two arrays:

a: a 3-dimensional source array (N x M x 2)

b: a 2-dimensional index array (N x M) containing 0 and 1s.

I want to use the indices in b to select the corresponding elements of a in its third dimension. The resulting array should have the dimensions N x M. Here is the example as code:

import numpy as np

a = np.array( # dims: 3x3x2
    [[[ 0,  1],
     [ 2,  3],
     [ 4,  5]],
    [[ 6,  7],
     [ 8,  9],
     [10, 11]],
    [[12, 13],
     [14, 15],
     [16, 17]]]
)
b = np.array( # dims: 3x3
    [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
)

# select the elements in a according to b
# to achieve this result:
desired = np.array(
  [[ 1,  3,  5],
   [ 7,  9, 11],
   [13, 15, 17]]
)

At first, I thought this must have a simple solution but I could not find one at all. Since I would like to port it to tensorflow, I would appreciate if somebody knows a numpy-type solution for this.

Edit: The third dimension of a might contain more than two elements. Hence, b might also contain indices different from 0 and 1 - it is not a boolean mask.

Body:
We can use np.where for this:

np.where(b, a[:, :, 1], a[:, :, 0])

Output:

array([[ 1,  3,  5],
       [ 7,  9, 11],
       [13, 15, 17]])


问:
How to send constantly updates using .Net Core SignalR?
I am new to SignalR and I would like to build such app -- every second a hub sends current time to all connected clients.

I found tutorial, but it is for .Net Framework (not Core): https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-high-frequency-realtime-with-signalr So on one hand I don't know how to translate it to .Net Core SignalR, on the other hand I don't know how to write it from scratch (the limiting condition is the fact a hub is a volatile entity, so I cannot have state in it).

I need something static (I guess) with state -- let's say Broadcaster, when I create some cyclic action which in turn will send updates to clients. If such approach is OK, how to initialize this Broadcaster?

Currently I added such static class:

```<code>public static class CrazyBroadcaster
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        var scope = serviceProvider.CreateScope();
        var hub = scope.ServiceProvider.GetRequiredService<IHubContext<ChatHub>>();
        var sub = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(_ => hub.Clients.All.SendAsync("Bar", DateTimeOffset.UtcNow));
    }
}
</code>```

Yes, I know it is leaky. I call this method at the end of Startup.Configure, probably tons of violations here, but so far it is my best shot.

答:
The missing piece was hosted service, i.e. the code that runs in the background -- https://learn.microsoft.com/en-US/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2.

So my crazy class is now transformed into:

```<code>public sealed class HostedBroadcaster : IHostedService, IDisposable
{
    private readonly IHubContext<ChatHub> hubContext;
    private IDisposable subscription;

    public HostedBroadcaster(IHubContext<ChatHub> hubContext)
    {
        this.hubContext = hubContext;
    }

    public void Dispose()
    {
        this.subscription?.Dispose();
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        this.subscription = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(_ => hubContext.Clients.All.SendAsync("Bar", DateTimeOffset.UtcNow));
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        this.subscription?.Dispose();
        return Task.CompletedTask;
    }
}
</code>```

Body:
I am new to SignalR and I would like to build such app -- every second a hub sends current time to all connected clients.

I found tutorial, but it is for .Net Framework (not Core): https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-high-frequency-realtime-with-signalr So on one hand I don't know how to translate it to .Net Core SignalR, on the other hand I don't know how to write it from scratch (the limiting condition is the fact a hub is a volatile entity, so I cannot have state in it).

I need something static (I guess) with state -- let's say Broadcaster, when I create some cyclic action which in turn will send updates to clients. If such approach is OK, how to initialize this Broadcaster?

Currently I added such static class:

public static class CrazyBroadcaster
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        var scope = serviceProvider.CreateScope();
        var hub = scope.ServiceProvider.GetRequiredService<IHubContext<ChatHub>>();
        var sub = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(_ => hub.Clients.All.SendAsync("Bar", DateTimeOffset.UtcNow));
    }
}

Yes, I know it is leaky. I call this method at the end of Startup.Configure, probably tons of violations here, but so far it is my best shot.

Body:
The missing piece was hosted service, i.e. the code that runs in the background -- https://learn.microsoft.com/en-US/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2.

So my crazy class is now transformed into:

public sealed class HostedBroadcaster : IHostedService, IDisposable
{
    private readonly IHubContext<ChatHub> hubContext;
    private IDisposable subscription;

    public HostedBroadcaster(IHubContext<ChatHub> hubContext)
    {
        this.hubContext = hubContext;
    }

    public void Dispose()
    {
        this.subscription?.Dispose();
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        this.subscription = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(_ => hubContext.Clients.All.SendAsync("Bar", DateTimeOffset.UtcNow));
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        this.subscription?.Dispose();
        return Task.CompletedTask;
    }
}


问:
Why is there still a conflict between prototype and jquery?
I've already read about how to load prototype and jquery together but these techniques are not solving the problem.

I load jquery then this file (http://music.glumbo.com/izzyFeedback.js) and then prototype.

I've wrapped parts that use $ in izzyFeedback.js in

```<code>(function($) {

})(jQuery);
</code>```

but this does not work. If I comment out the prototype load then it works correctly.

答:
Did you put jQuery.noConflict(); before the (function($) { })(jQuery) wrapper?

There are some other techniques in the docs http://api.jquery.com/jQuery.noConflict/

I've had previous success using var j = jQuery.noConflict(); and replacing all instances of $ and jQuery with j.

Body:
I've already read about how to load prototype and jquery together but these techniques are not solving the problem.

I load jquery then this file (http://music.glumbo.com/izzyFeedback.js) and then prototype.

I've wrapped parts that use $ in izzyFeedback.js in

(function($) {

})(jQuery);

but this does not work. If I comment out the prototype load then it works correctly.


问:
Overflowing a child element outside the parent element
I have a simple card which contains an image .menu-card__header-image. On hover, I wish to lift that image up by some pixels. However, when I do lift the image, the image is not visible outside the parent container .menu-card.

.menu-card {
  font-family: sans-serif;
  color: red;
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  overflow: visible;
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  overflow: hidden;
  text-align: center;
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card:first-child {
  margin-bottom: 50px;
}
.menu-card:last-child {
  margin-top: 50px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-card">
  <div class="menu-card__header">
    <img src="http://lorempixel.com/250/635" alt="" class="menu-card__header-image" height="400px" />
  </div>
  <h2 class="menu-card__title">
    Lorem Ipsum
  </h2>
  <p class="menu-card__description">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex
  </p>
</div></code>```

Here is the relevant pen:  https://codepen.io/saifalfalah/pen/gJKNBE?editors=1100

How do I make the image be visible outside the parent container on hover without changing the markup (preferably)?

答:
One option without changing the markup is to animate the clip-path property as well to change to clip-path: polygon(0 -80px, 100% -80px, 100% calc(100% - 6vw), 0 100%) on hover - see demo below:

body {
  margin-top: 100px; /* for illustration */
}

.menu-card {
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  /*overflow: hidden;*/
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  /*overflow: visible;*/
}
.menu-card:hover .menu-card__header { /* added */
   clip-path: polygon(0 -80px, 100% -80px, 100% calc(100% - 6vw), 0 100%);
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  /*overflow: hidden;*/
  text-align: center;
  transition: clip-path 0.5s ease-in-out; /* added */
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu-card">
  <div class="menu-card__header">
    <img src="http://lorempixel.com/250/635" alt="" class="menu-card__header-image" height="400px" />
  </div>
  <h2 class="menu-card__title">
    Lorem Ipsum
  </h2>
  <p class="menu-card__description">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex
  </p>
</div></code>```

Body:
I have a simple card which contains an image .menu-card__header-image. On hover, I wish to lift that image up by some pixels. However, when I do lift the image, the image is not visible outside the parent container .menu-card.

.menu-card {
  font-family: sans-serif;
  color: red;
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  overflow: hidden;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  overflow: visible;
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  overflow: hidden;
  text-align: center;
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card:first-child {
  margin-bottom: 50px;
}
.menu-card:last-child {
  margin-top: 50px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}

    Lorem Ipsum

    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex

Here is the relevant pen:  https://codepen.io/saifalfalah/pen/gJKNBE?editors=1100

How do I make the image be visible outside the parent container on hover without changing the markup (preferably)?

Body:
One option without changing the markup is to animate the clip-path property as well to change to clip-path: polygon(0 -80px, 100% -80px, 100% calc(100% - 6vw), 0 100%) on hover - see demo below:

body {
  margin-top: 100px; /* for illustration */
}

.menu-card {
  margin-left: auto;
  margin-right: auto;
  width: 80%;
  /*overflow: hidden;*/
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  padding-bottom: 20px;
  max-width: 400px;
}
.menu-card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
  /*overflow: visible;*/
}
.menu-card:hover .menu-card__header { /* added */
   clip-path: polygon(0 -80px, 100% -80px, 100% calc(100% - 6vw), 0 100%);
}
.menu-card__header {
  background-color: orange;
  clip-path: polygon(0 0, 100% 0, 100% calc(100% - 6vw), 0 100%);
  max-height: 300px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
  /*overflow: hidden;*/
  text-align: center;
  transition: clip-path 0.5s ease-in-out; /* added */
}
.menu-card__header-image {
  margin-left: auto;
  margin-right: auto;
  z-index: 33;
  position: relative;
  bottom: 0px;
  transition: bottom 0.5s ease-in-out;
}
.menu-card:hover .menu-card__header-image {
  bottom: 80px;
}
.menu-card__title {
  padding: 0 12px;
}
.menu-card__description {
  padding: 0 12px;
}

.menu-card__title {
  text-align: center;
}

<div class="menu-card">
  <div class="menu-card__header">
    <img src="http://lorempixel.com/250/635" alt="" class="menu-card__header-image" height="400px" />
  </div>
  <h2 class="menu-card__title">
    Lorem Ipsum
  </h2>
  <p class="menu-card__description">
    Lorem ipsum, dolor sit amet consectetur adipisicing elit. Corrupti, architecto. Repudiandae dolorum incidunt sint ex
  </p>
</div>


问:
Filter rows over partitions
Suppose I have the following table:

```<code>    +-------+------------+
    | nGroup |   Status   |
    +-------+------------+
    |     1 | DONE       |
    |     1 | UNKNOWN    |
    |     1 | DONE       |
    |     2 | INPROGRESS |
    |     2 | INPROGRESS |
    |     2 | DONE       |
    |     3 | INPROGRESS |
    |     3 | DONE       |
    |     3 | DONE       |
    +-------+------------+
</code>```

If a nGroup has one Status to INPROGRESS, then return only the lines of that group containing the status INPROGRESS.

If all the Status of a nGroup are different from INPROGRESS, then return all the status available for that group.

So for this example, I would get the following output:

```<code>+-------+------------+
| nGroup |   Status   |
+-------+------------+
|     1 | DONE       |
|     1 | UNKNOWN    |
|     1 | DONE       |
|     2 | INPROGRESS |
|     2 | INPROGRESS |
|     3 | INPROGRESS |
+-------+------------+
</code>```

I tried the following query :

```<code>SELECT *
FROM dbo.myTable T1
WHERE Status IN (
  CASE WHEN EXISTS( SELECT 1 FROM myTable T2 WHERE T2.STATUS = 'INPROGRESS' AND T1.nGroup = T2.nGroup) THEN 'INPROGRESS'
  ELSE (SELECT Status FROM myTable T2 WHERE T1.nGroup = T2.nGroup)
  END
)
</code>```

But I get the following error when running it :

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

答:
This will do it:</p>

```<code>select m.*
from myTable m
where
  m.Status = 'INPROGRESS'
  OR NOT EXISTS (
    select 1 from myTable where nGroup = m.nGroup and Status = 'INPROGRESS'
  )
</code>```

Title: Filter rows over partitions

Body:
Suppose I have the following table:

    +-------+------------+
    | nGroup |   Status   |
    +-------+------------+
    |     1 | DONE       |
    |     1 | UNKNOWN    |
    |     1 | DONE       |
    |     2 | INPROGRESS |
    |     2 | INPROGRESS |
    |     2 | DONE       |
    |     3 | INPROGRESS |
    |     3 | DONE       |
    |     3 | DONE       |
    +-------+------------+

If a nGroup has one Status to INPROGRESS, then return only the lines of that group containing the status INPROGRESS.

If all the Status of a nGroup are different from INPROGRESS, then return all the status available for that group.

So for this example, I would get the following output:

+-------+------------+
| nGroup |   Status   |
+-------+------------+
|     1 | DONE       |
|     1 | UNKNOWN    |
|     1 | DONE       |
|     2 | INPROGRESS |
|     2 | INPROGRESS |
|     3 | INPROGRESS |
+-------+------------+

I tried the following query :

SELECT *
FROM dbo.myTable T1
WHERE Status IN (
  CASE WHEN EXISTS( SELECT 1 FROM myTable T2 WHERE T2.STATUS = 'INPROGRESS' AND T1.nGroup = T2.nGroup) THEN 'INPROGRESS'
  ELSE (SELECT Status FROM myTable T2 WHERE T1.nGroup = T2.nGroup)
  END
)

But I get the following error when running it :

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression.

Body:
This will do it:

select m.*
from myTable m
where
  m.Status = 'INPROGRESS'
  OR NOT EXISTS (
    select 1 from myTable where nGroup = m.nGroup and Status = 'INPROGRESS'
  )


问:
Why timer invoke its block so quickly sometimes
I create a timer and invoke its block every 5 second. Then I make application to enter background and enter foreground after a while. But it could invoke the block quickly sometimes.

```<code>let _ = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { (timer) in
        print("--------")
   }
</code>```

When I enter foreground the interval of first printing and second printing may less than a second sometimes. Is time interval invalid in this case?

答: When application entered background, the app would be suspended soon, program stopped running. When app switched back to foreground, the buffered/delayed timer event would be fired, then you saw many prints quickly. </p>

Body:
I create a timer and invoke its block every 5 second. Then I make application to enter background and enter foreground after a while. But it could invoke the block quickly sometimes.

let _ = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { (timer) in
        print("--------")
   }

When I enter foreground the interval of first printing and second printing may less than a second sometimes. Is time interval invalid in this case?


问:
Getting linux to buffer /dev/random
I need a reasonable supply of high-quality random data for an application I'm writing. Linux provides the /dev/random file for this purpose which is ideal; however, because my server is a single-service virtual machine, it has very limited sources of entropy, meaning /dev/random quickly becomes exhausted.

I've noticed that if I read from /dev/random, I will only get 16 or so random bytes before the device blocks while it waits for more entropy:

```<code>[duke@poopz ~]# hexdump /dev/random
0000000 f4d3 8e1e 447a e0e3 d937 a595 1df9 d6c5
<process blocks...>
</code>```

If I terminate this process, go away for an hour and repeat the command, again only 16 or so bytes of random data are produced.

However - if instead I leave the command running for the same amount of time, much, much more random data are collected. I assume from this that over the course of a given timeperiod, the system produces plenty of entropy, but Linux only utilises it if you are actually reading from /dev/random, and discards it if you are not. If this is the case, my question is:

Is it possible to configure Linux to buffer /dev/random so that reading from it yields much larger bursts of high-quality random data?

It wouldn't be difficult for me to buffer /dev/random as part of my program but I feel doing this at a system level would be more elegant. I also wonder if having Linux buffer its random data in memory would have security implications.

答: Have you got, or can you buy, a Linux-compatible hardware random number generator? That could be a solution to your underlying problem. See http://www.linuxcertified.com/hw_random.html</p>

Title: Getting linux to buffer /dev/random

Body:
I need a reasonable supply of high-quality random data for an application I'm writing. Linux provides the /dev/random file for this purpose which is ideal; however, because my server is a single-service virtual machine, it has very limited sources of entropy, meaning /dev/random quickly becomes exhausted.

I've noticed that if I read from /dev/random, I will only get 16 or so random bytes before the device blocks while it waits for more entropy:

[duke@poopz ~]# hexdump /dev/random
0000000 f4d3 8e1e 447a e0e3 d937 a595 1df9 d6c5
<process blocks...>

If I terminate this process, go away for an hour and repeat the command, again only 16 or so bytes of random data are produced.

However - if instead I leave the command running for the same amount of time, much, much more random data are collected. I assume from this that over the course of a given timeperiod, the system produces plenty of entropy, but Linux only utilises it if you are actually reading from /dev/random, and discards it if you are not. If this is the case, my question is:

Is it possible to configure Linux to buffer /dev/random so that reading from it yields much larger bursts of high-quality random data?

It wouldn't be difficult for me to buffer /dev/random as part of my program but I feel doing this at a system level would be more elegant. I also wonder if having Linux buffer its random data in memory would have security implications.


问:
Find all matches in column range and copy all value within range
First time user here.
I'm also a beginner trying to write a program in VBA for Excel 2010 and here's what I need to do.

I have a workbook containing two sheets, Sheet1 called "Process"
(have column A with titled "Item") and Sheet2 called "Master" (have column A with titled "Item" and column B with titled "Operation")

I need to compare these two columns A, if there's any data that match, I'd like to copy ALL data from column B "Operation" from sheet "Master" and place it into column B in sheet "Process".

The code from Mr. Mohit Bansal it's working perfectly, but after i try to put the code into real condition of worksheet, i'm facing new problem that if any same data in Column A "Item", it's only copy for first data.

Any help for figuring out how to get past this would be greatly appreciated.

Herewith i edit based on real condition of worksheet.

Sheet1 "Process"

```<code>-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |           |
|20Y        |           |
|20Y        |           |
|20YF0Blank |           |
|20YF0      |           |
|20YF0      |           |
|20YFGAfter |           |
|20YFG      |           |
|20YFG      |           |
|20YStandard|           |
|20Y        |           |
|20Y        |           |
|20Y        |           |
|20YF0Blank |           |
|20YF0      |           |
|20YF0      |           |
|20YFGAfter |           |
|20YFG      |           |
|20YFG      |           |
</code>```

Sheet2 "Master"

```<code>-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|21YF0      |QT2        |
|21YF0      |SB2        |
|21YF0      |MG2        |
|21YFG      |FG8        |
|21YFG      |SCR2       |
</code>```

Actual Result =

Sheet1 "Process"

```<code>-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|20YStandard|           |
|20Y        |Not copied |
|20Y        |Not copied |
|20Y        |Not copied |
|20YF0Blank |           |
|20YF0      |Not copied |
|20YF0      |Not copied |
|20YFGAfter |           |
|20YFG      |Not copied |
|20YFG      |Not copied |
</code>```

```<code>Sub Button2_Click()

pr = Worksheets("Process").Range("A2:B1000").Value

ma = Worksheets("Master").Range("A2:B8008").Value

Range("B:B").ClearContents

For i = LBound(pr, 1) To UBound(pr, 1)

    For j = LBound(ma, 1) To UBound(ma, 1)

        If ma(j, 1) = pr(i, 1) Then

            Worksheets("Process").Range("B" & i + 1).Value = ma(j, 2)
            ma(j, 1) = "---"

            Exit For

        End If
Next j
Next i
End Sub
</code>```

Expected Result =

Sheet1 "Process"

```<code>-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
</code>```

答:
You could use a Find FindNext

```<code>Sub Button2_Click()
    Dim firstAddress As String
    Dim finalrow As Long, i As Long
    Dim shtCS As Worksheet, shtFD As Worksheet, rw As Range
    Dim c

    Set shtCS = Worksheets("Process")
    Set shtFD = Worksheets("Master")

    finalrow = shtFD.Range("A" & Rows.Count).End(xlUp).Row

    With shtFD.Columns(1)
        For i = 2 To finalrow
            Set c = .Find(shtCS.Cells(i, 1).Value2)

            If Not c Is Nothing Then
                firstAddress = c.Address
                Do
                    shtCS.Cells(i, 2).Value2 = c.Offset(0, 1).Value2
                    i = i + 1
                    Set c = .FindNext(c)
                Loop Until c.Address = firstAddress
            End If
        Next i
    End With
End Sub
</code>```

Body:
First time user here.
I'm also a beginner trying to write a program in VBA for Excel 2010 and here's what I need to do.

I have a workbook containing two sheets, Sheet1 called "Process"
(have column A with titled "Item") and Sheet2 called "Master" (have column A with titled "Item" and column B with titled "Operation")

I need to compare these two columns A, if there's any data that match, I'd like to copy ALL data from column B "Operation" from sheet "Master" and place it into column B in sheet "Process".

The code from Mr. Mohit Bansal it's working perfectly, but after i try to put the code into real condition of worksheet, i'm facing new problem that if any same data in Column A "Item", it's only copy for first data.

Any help for figuring out how to get past this would be greatly appreciated.

Herewith i edit based on real condition of worksheet.

Sheet1 "Process"

-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |           |
|20Y        |           |
|20Y        |           |
|20YF0Blank |           |
|20YF0      |           |
|20YF0      |           |
|20YFGAfter |           |
|20YFG      |           |
|20YFG      |           |
|20YStandard|           |
|20Y        |           |
|20Y        |           |
|20Y        |           |
|20YF0Blank |           |
|20YF0      |           |
|20YF0      |           |
|20YFGAfter |           |
|20YFG      |           |
|20YFG      |           |

Sheet2 "Master"

-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|21YF0      |QT2        |
|21YF0      |SB2        |
|21YF0      |MG2        |
|21YFG      |FG8        |
|21YFG      |SCR2       |

Actual Result =

Sheet1 "Process"

-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|20YStandard|           |
|20Y        |Not copied |
|20Y        |Not copied |
|20Y        |Not copied |
|20YF0Blank |           |
|20YF0      |Not copied |
|20YF0      |Not copied |
|20YFGAfter |           |
|20YFG      |Not copied |
|20YFG      |Not copied |

Sub Button2_Click()

pr = Worksheets("Process").Range("A2:B1000").Value

ma = Worksheets("Master").Range("A2:B8008").Value

Range("B:B").ClearContents

For i = LBound(pr, 1) To UBound(pr, 1)

    For j = LBound(ma, 1) To UBound(ma, 1)

        If ma(j, 1) = pr(i, 1) Then

            Worksheets("Process").Range("B" & i + 1).Value = ma(j, 2)
            ma(j, 1) = "---"

            Exit For

        End If
Next j
Next i
End Sub

Expected Result =

Sheet1 "Process"

-------------------------
|Column A   |Column B   |
|"Item"     |"Operation"|
-------------------------
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |
|20YStandard|           |
|20Y        |MLM1       |
|20Y        |IQTM1      |
|20Y        |HBM1       |
|20YF0Blank |           |
|20YF0      |QT1        |
|20YF0      |SB1        |
|20YFGAfter |           |
|20YFG      |FG7        |
|20YFG      |SCR1       |

Body:
You could use a Find FindNext

Sub Button2_Click()
    Dim firstAddress As String
    Dim finalrow As Long, i As Long
    Dim shtCS As Worksheet, shtFD As Worksheet, rw As Range
    Dim c

    Set shtCS = Worksheets("Process")
    Set shtFD = Worksheets("Master")

    finalrow = shtFD.Range("A" & Rows.Count).End(xlUp).Row

    With shtFD.Columns(1)
        For i = 2 To finalrow
            Set c = .Find(shtCS.Cells(i, 1).Value2)

            If Not c Is Nothing Then
                firstAddress = c.Address
                Do
                    shtCS.Cells(i, 2).Value2 = c.Offset(0, 1).Value2
                    i = i + 1
                    Set c = .FindNext(c)
                Loop Until c.Address = firstAddress
            End If
        Next i
    End With
End Sub


问:
Is there any way to get Yoast title inside a page using the Yoast variable? ( i.e. %%title%%)
I need to create a function so that I can use that inside any page which is outside the WordPress regular page. I mean wp_head() will not be placed there. I need it for a purpose.

The purpose is for AMP (ampproject.org) a page where I can't use any CSS or JavaScript. That's why I need this; I need to place a function at wp_title() so that the Yoast title be placed there.

I need something like this:

```<code>function yoastVariableToTitle($variable){
    return yoast_vaialble_to_show_title($variable);
}
</code>```

答:
The workaround I use in my plugin using functions from class-frontend.php (yoast's class). It works outside of the loop, just give it a post's id:</p>

```<code>function convert_yoast_title ($post_id) {
    $string =  WPSEO_Meta::get_value( 'title', $post_id );
    if ($string !== '') {
        $replacer = new WPSEO_Replace_Vars();

        return $replacer->replace( $string, get_post($post_id) );
    }
    return ''; // if not found - returns empty string
}
</code>```

Body:
I need to create a function so that I can use that inside any page which is outside the WordPress regular page. I mean wp_head() will not be placed there. I need it for a purpose.

The purpose is for AMP (ampproject.org) a page where I can't use any CSS or JavaScript. That's why I need this; I need to place a function at wp_title() so that the Yoast title be placed there.

I need something like this:

function yoastVariableToTitle($variable){
    return yoast_vaialble_to_show_title($variable);
}

Body:
The workaround I use in my plugin using functions from class-frontend.php (yoast's class). It works outside of the loop, just give it a post's id:

function convert_yoast_title ($post_id) {
    $string =  WPSEO_Meta::get_value( 'title', $post_id );
    if ($string !== '') {
        $replacer = new WPSEO_Replace_Vars();

        return $replacer->replace( $string, get_post($post_id) );
    }
    return ''; // if not found - returns empty string
}


问:
Having a slight problem moving my camera based on time passed using GLUT/OpenGL
Before anyone asks, this is for a university project and I have to use GLUT. I'm not tagging this as homework because this is not a requirement, nor will I have extra points for this.

With GLUT, for people unaware, you have:

glutIdleFunc(func): registers the render function and this means that when GLUT is not doing anything else, it will call this function. In other words, it will keep rendering as fast as possible.

glutTimerFunc(msecs, func, val): registers a function that will be called in msecs and the registering the same function recursively would allow for a fixed time based movement.

Now, I'm trying to avoid these functions for this purpose and most discussions/articles I found about GLUT, use them for time based movement. So I have come here once again... But if I'm not using any of those functions, how are the frames rendered? I just call glutPostRedisplay and a single frame will be rendered.

I have managed to implement time based movement in GLUT in a simple manner. May not be the best implementation, but it's not overly complex and works. Well, there's only a slight problem, that's why I'm here.

My camera movement is based on Newton's Second Law of Motion, where I calculate the displacement movement like this:

```<code>Vector3D displacement = (CurrentVelocity * elapsedTime) +
    (Acceleration * 0.5f * elapsedTime * elapsedTime);
</code>```

The elapsedTime comes from my timer implementation and I think that's where the problem lies. The problem is that displacement should be positive or negative depending on the movement direction but if CurrentVelocity is a really low value (ie: -0.1f), the displacement will be positive when it should be negative. The rest of the code will accelerate or deacelerate the camera, so the problem only happens when accelerating because that's when CurrentVelocity will be small and what happens is that the camera moves slightly to the right (positive) and then to the left (negative) when it gains enough momentum to give a negative displacement value.

Now, when there's no movement in the scene, nothing is being rendered at all. When I press on of the movement keys, I do this:

```<code>CameraDirection.z = CAMERA_WALK_BACKWARD;
SceneTimer.PostRedisplayWindow();
</code>```

That also comes from my timer class, I do that instead of calling glutPostRedisplay and the reason for that is this:

```<code>void Timer::PostRedisplayWindow(void) {
    currentTime = glutGet(GLUT_ELAPSED_TIME);
    glutPostRedisplay();
}
</code>```

I need to get the currentTime (which will become the previousTime when I need to calculate the elapsed time) and then I call glutPostRedisplay. A single frame will be rendered, which means the renderScene will be called:

```<code>void renderScene(void) {
    (...)

    glLoadIdentity();

    elapsedTime = SceneTimer.GetElapsedTimeInSeconds();

    SceneCamera.Move(CameraDirection, elapsedTime);
    SceneCamera.LookAt();

    drawCompleteScene();

    glutSwapBuffers();

    checkAnimationRedisplay();
}
</code>```

As you can see, the elapsed time is calculated and the camera is moved on that. Everything in the scene is drawn, swap buffers and then I have this extra function which will check if something needs to be animated, in this case, the camera needs:

```<code>void checkAnimationRedisplay(void) {
    if(SceneCamera.IsCameraMoving()) {
        glutPostRedisplay();
        return;
    }
}
</code>```

It will keep calling glutPostRedisplay until the camera has stopped moving. Meaning, renderScene will be called every time, the elapsed time is calculated and the camera is moved based on time, everything's working; besides, of course, the little glitch already mentioned, little but the one that made me create this long question (sorry about that).

All that's missing is the most important function of this question, the one that calculates the elapsed time, simple as this:

float Timer::GetElapsedTimeInSeconds(void) {
    static int previousTime = 0;
    static int elapsedTime = 0;

```<code>previousTime = currentTime;
currentTime = glutGet(GLUT_ELAPSED_TIME);
elapsedTime = currentTime - previousTime;

return elapsedTime / 1000.0f;
</code>```

}

There's probably something wrong with my timer code right? I mean, moving forward or right (positive values), there's no problems. The movement is smooth and time based. For instance, if I set a movement speed of 5m/s, it will actually take 5 seconds to move 25meters (I'm assuming 1m = 1.0f).

So, what I'm doing wrong with the timer so that the negative values start moving to the right for a split-second and only then to the left as it should?

答:
One answer that fixes my problem can be found here:
https://gamedev.stackexchange.com/questions/10902/having-a-slight-problem-moving-my-camera-based-on-time-passed-using-glut-opengl</p>

Body:
Before anyone asks, this is for a university project and I have to use GLUT. I'm not tagging this as homework because this is not a requirement, nor will I have extra points for this.

With GLUT, for people unaware, you have:

glutIdleFunc(func): registers the render function and this means that when GLUT is not doing anything else, it will call this function. In other words, it will keep rendering as fast as possible.

glutTimerFunc(msecs, func, val): registers a function that will be called in msecs and the registering the same function recursively would allow for a fixed time based movement.

Now, I'm trying to avoid these functions for this purpose and most discussions/articles I found about GLUT, use them for time based movement. So I have come here once again... But if I'm not using any of those functions, how are the frames rendered? I just call glutPostRedisplay and a single frame will be rendered.

I have managed to implement time based movement in GLUT in a simple manner. May not be the best implementation, but it's not overly complex and works. Well, there's only a slight problem, that's why I'm here.

My camera movement is based on Newton's Second Law of Motion, where I calculate the displacement movement like this:

Vector3D displacement = (CurrentVelocity * elapsedTime) +
    (Acceleration * 0.5f * elapsedTime * elapsedTime);

The elapsedTime comes from my timer implementation and I think that's where the problem lies. The problem is that displacement should be positive or negative depending on the movement direction but if CurrentVelocity is a really low value (ie: -0.1f), the displacement will be positive when it should be negative. The rest of the code will accelerate or deacelerate the camera, so the problem only happens when accelerating because that's when CurrentVelocity will be small and what happens is that the camera moves slightly to the right (positive) and then to the left (negative) when it gains enough momentum to give a negative displacement value.

Now, when there's no movement in the scene, nothing is being rendered at all. When I press on of the movement keys, I do this:

CameraDirection.z = CAMERA_WALK_BACKWARD;
SceneTimer.PostRedisplayWindow();

That also comes from my timer class, I do that instead of calling glutPostRedisplay and the reason for that is this:

void Timer::PostRedisplayWindow(void) {
    currentTime = glutGet(GLUT_ELAPSED_TIME);
    glutPostRedisplay();
}

I need to get the currentTime (which will become the previousTime when I need to calculate the elapsed time) and then I call glutPostRedisplay. A single frame will be rendered, which means the renderScene will be called:

void renderScene(void) {
    (...)

    glLoadIdentity();

    elapsedTime = SceneTimer.GetElapsedTimeInSeconds();

    SceneCamera.Move(CameraDirection, elapsedTime);
    SceneCamera.LookAt();

    drawCompleteScene();

    glutSwapBuffers();

    checkAnimationRedisplay();
}

As you can see, the elapsed time is calculated and the camera is moved on that. Everything in the scene is drawn, swap buffers and then I have this extra function which will check if something needs to be animated, in this case, the camera needs:

void checkAnimationRedisplay(void) {
    if(SceneCamera.IsCameraMoving()) {
        glutPostRedisplay();
        return;
    }
}

It will keep calling glutPostRedisplay until the camera has stopped moving. Meaning, renderScene will be called every time, the elapsed time is calculated and the camera is moved based on time, everything's working; besides, of course, the little glitch already mentioned, little but the one that made me create this long question (sorry about that).

All that's missing is the most important function of this question, the one that calculates the elapsed time, simple as this:

float Timer::GetElapsedTimeInSeconds(void) {
    static int previousTime = 0;
    static int elapsedTime = 0;

previousTime = currentTime;
currentTime = glutGet(GLUT_ELAPSED_TIME);
elapsedTime = currentTime - previousTime;

return elapsedTime / 1000.0f;

}

There's probably something wrong with my timer code right? I mean, moving forward or right (positive values), there's no problems. The movement is smooth and time based. For instance, if I set a movement speed of 5m/s, it will actually take 5 seconds to move 25meters (I'm assuming 1m = 1.0f).

So, what I'm doing wrong with the timer so that the negative values start moving to the right for a split-second and only then to the left as it should?


问:
Python - Average of three values in a while true loop
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)
```

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
See another version with the logic of just saving the distance with only 3 elements in a loop. The last value is 'pop' out so we only have 3 elements.

my mockup below;

distancedata=[0,0,0]
for i in range(20):
        if len(distancedata) >= 3:
            a=distancedata.pop(0)
        distancedata.append(float(i))
        print i,  distancedata,sum(distancedata) / len(distancedata)

The results here:

0 [0, 0, 0.0] 0.0
1 [0, 0.0, 1.0] 0.333333333333
2 [0.0, 1.0, 2.0] 1.0
3 [1.0, 2.0, 3.0] 2.0
4 [2.0, 3.0, 4.0] 3.0
5 [3.0, 4.0, 5.0] 4.0
6 [4.0, 5.0, 6.0] 5.0
7 [5.0, 6.0, 7.0] 6.0
8 [6.0, 7.0, 8.0] 7.0
9 [7.0, 8.0, 9.0] 8.0
10 [8.0, 9.0, 10.0] 9.0
11 [9.0, 10.0, 11.0] 10.0
12 [10.0, 11.0, 12.0] 11.0
13 [11.0, 12.0, 13.0] 12.0
14 [12.0, 13.0, 14.0] 13.0
15 [13.0, 14.0, 15.0] 14.0
16 [14.0, 15.0, 16.0] 15.0
17 [15.0, 16.0, 17.0] 16.0
18 [16.0, 17.0, 18.0] 17.0
19 [17.0, 18.0, 19.0] 18.0


问:
Junit test fail for the java.lang.NullPointerException
I work to test a class with the Junit and I get an NullPointerException.

The class I would like to test is provided below,

```<code>@Component
public class EmailageConnector {

    private static final Logger LOG = LoggerFactory.getLogger( EmailageConnector.class );

    private static final String BASIC_AUTHORIZATION = "Basic ";

    @Autowired
    private EmailageConfigHolder emailageConfigHolder;

    @Autowired
    private EntityServiceConnectable<EmailageResponseDto> connector;

    private String authorization;

    @PostConstruct
    void createAuthorization() {
        final String credentials = String.format( "%s%s%s", emailageConfigHolder.getAccountId(), ":", emailageConfigHolder.getApiKey() );
        authorization = BASIC_AUTHORIZATION + encodeBase64String( credentials.getBytes() );
    }

    // ========================================================================

    public ServiceResponse<EmailageResponseDto> call( final RequestInformation requestInfo, final EmailageRequestDto request ) {

        if( LOG.isDebugEnabled() ) {
            LOG.debug( "call emailage [ requestInfo: {} - request: {}]",
                       String.format( "%s", requestInfo ),
                       String.format( "%s", request ) );
        }

        return connector.call( request, createHeaders() );
    }

    // ========================================================================

    private HttpHeaders createHeaders() {
        final HttpHeaders headers = new HttpHeaders();

        headers.add( AUTHORIZATION, authorization );
        return headers;
    }

}
</code>```

This is my test class,

```<code>@RunWith( MockitoJUnitRunner.class )
public class EmailageConnectorTest {

    @InjectMocks
    private EmailageConnector connector;

    @Spy
    private EmailageConfigHolder configHolder;

    @Mock
    EntityServiceConnectable<EmailageResponseDto> serviceConnector;

    @Captor
    private ArgumentCaptor<UriParam<?>> captor;

    @Captor
    private ArgumentCaptor<HttpHeaders> headerCaptor;

    @Before
    public void setUp() {
        configHolder.setApiKey( "api-key-123456" );
        configHolder.setAccountId( "ratepay-group" );
        connector.createAuthorization();
    }

    @Test
    public void call() {

        RequestInformation requestInfo = new TestRequestInformation();

        when( serviceConnector.call( Mockito.any( HttpHeaders.class ), Mockito.any() ) )
                .thenReturn( ServiceResponseFactory.withError( "error", 500 ) );

        ServiceResponse<EmailageResponseDto> response = connector.call( requestInfo, createTestEmailageRequestDto() );

        assertEquals( Integer.valueOf( 500 ), response.getHttpStatus() );
        assertEquals( "error", response.getErrorMessage() );

        verify( serviceConnector ).call( headerCaptor.capture(), captor.capture() );

        assertEquals( 3, captor.getAllValues().size() );
        assertEquals( "api_id", captor.getAllValues().get( 0 ).getName() );
        assertEquals( "api-id-12345", captor.getAllValues().get( 0 ).getValue() );
        assertEquals( "token", captor.getAllValues().get( 1 ).getName() );
        assertEquals( "token-1234", captor.getAllValues().get( 1 ).getValue() );
        assertEquals( "include", captor.getAllValues().get( 2 ).getName() );
        assertEquals( "scores", String.valueOf( ( (SimpleQueryUriParam) captor.getAllValues().get( 2 ) ).getValue()[0] ) );
        assertEquals( GW_ID, headerCaptor.getValue().getFirst( HEADER_GATEWAY_REQUEST_ID ) );
        assertEquals( TRX_ID, headerCaptor.getValue().getFirst( HEADER_TRANSACTION_ID ) );
        assertEquals( "Basic cmF0ZXBheS1ncm91cDphcGkta2V5LTEyMzQ1Ng==", headerCaptor.getValue().getFirst( AUTHORIZATION ) );
    }

    private EmailageRequestDto createTestEmailageRequestDto() {

        EmailageRequestDto dto = new EmailageRequestBuilder().build();
        return dto;
    }
}
</code>```

The interface for the EntityServiceConnectable is provided below,

```<code>public interface EntityServiceConnectable<RESPONSE> extends ServiceConnectable<RESPONSE> {

    ServiceResponse<RESPONSE> call(Object var1, RequestInformation var2, UriParam... var3);

    ServiceResponse<RESPONSE> call(Object var1, HttpHeaders var2, UriParam... var3);

    ServiceResponse<RESPONSE> call(Object var1, UriParam... var2);
}
</code>```

The test is failing here,

```<code>ServiceResponse<EmailageResponseDto> response = connector.call( requestInfo, createTestEmailageRequestDto() );
</code>```

Here is the error stack for the test,

```<code>java.lang.NullPointerException
    at com.ratepay.ella.service.io.EmailageConnectorTest.call(EmailageConnectorTest.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

[MockitoHint] EmailageConnectorTest.call (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -> at com.ratepay.ella.service.io.EmailageConnectorTest.call(EmailageConnectorTest.java:79)
[MockitoHint]  ...args ok? -> at com.ratepay.ella.service.io.EmailageConnector.call(EmailageConnector.java:65)
</code>```

I debugged the setup and provided the screenshot below,

What do I miss here?

答:
Edit:

For JUnit5 and mockito refer to this answer:

How to use Mockito with JUnit5

I've updated the example below as well.

Edit2:
As the TO did not state which JUnit version or mockito version is being used,
I will try to edit the answer if still does not work.

Thanks to @helospark for poining this out.

Using the Runner or the Rule does not work with JUnit5, so probably Mockito Version 2 should be used.

With Mockito Version 1 , an explictly call to the init Method is required.

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

```

<hr>

<p>For Junit5 and the latest Mockito version (2.27) the test class should look like this:</p>

<pre class="lang-java prettyprint-override"><code>class InnerClass {
    public void doSomething(String fileName) {
    }
}

class SomeClass {

    InnerClass innerClass;

    public boolean doSomething(String fileName) {
        innerClass.doSomething(fileName);
        return true;
    }
}

@ExtendWith(MockitoExtension.class)
class SomeClassTest {

    @InjectMocks
    SomeClass someClass;

    @Mock
    InnerClass innerClass;

    @Test
    public void test() {
        someClass.doSomething("test");
        Mockito.verify(innerClass, Mockito.times(1)).doSomething(Mockito.any());
    }
}
</code>```

Body:
I work to test a class with the Junit and I get an NullPointerException.

The class I would like to test is provided below,

@Component
public class EmailageConnector {

    private static final Logger LOG = LoggerFactory.getLogger( EmailageConnector.class );

    private static final String BASIC_AUTHORIZATION = "Basic ";

    @Autowired
    private EmailageConfigHolder emailageConfigHolder;

    @Autowired
    private EntityServiceConnectable<EmailageResponseDto> connector;

    private String authorization;

    @PostConstruct
    void createAuthorization() {
        final String credentials = String.format( "%s%s%s", emailageConfigHolder.getAccountId(), ":", emailageConfigHolder.getApiKey() );
        authorization = BASIC_AUTHORIZATION + encodeBase64String( credentials.getBytes() );
    }

    // ========================================================================

    public ServiceResponse<EmailageResponseDto> call( final RequestInformation requestInfo, final EmailageRequestDto request ) {

        if( LOG.isDebugEnabled() ) {
            LOG.debug( "call emailage [ requestInfo: {} - request: {}]",
                       String.format( "%s", requestInfo ),
                       String.format( "%s", request ) );
        }

        return connector.call( request, createHeaders() );
    }

    // ========================================================================

    private HttpHeaders createHeaders() {
        final HttpHeaders headers = new HttpHeaders();

        headers.add( AUTHORIZATION, authorization );
        return headers;
    }

}

This is my test class,

@RunWith( MockitoJUnitRunner.class )
public class EmailageConnectorTest {

    @InjectMocks
    private EmailageConnector connector;

    @Spy
    private EmailageConfigHolder configHolder;

    @Mock
    EntityServiceConnectable<EmailageResponseDto> serviceConnector;

    @Captor
    private ArgumentCaptor<UriParam<?>> captor;

    @Captor
    private ArgumentCaptor<HttpHeaders> headerCaptor;

    @Before
    public void setUp() {
        configHolder.setApiKey( "api-key-123456" );
        configHolder.setAccountId( "ratepay-group" );
        connector.createAuthorization();
    }

    @Test
    public void call() {

        RequestInformation requestInfo = new TestRequestInformation();

        when( serviceConnector.call( Mockito.any( HttpHeaders.class ), Mockito.any() ) )
                .thenReturn( ServiceResponseFactory.withError( "error", 500 ) );

        ServiceResponse<EmailageResponseDto> response = connector.call( requestInfo, createTestEmailageRequestDto() );

        assertEquals( Integer.valueOf( 500 ), response.getHttpStatus() );
        assertEquals( "error", response.getErrorMessage() );

        verify( serviceConnector ).call( headerCaptor.capture(), captor.capture() );

        assertEquals( 3, captor.getAllValues().size() );
        assertEquals( "api_id", captor.getAllValues().get( 0 ).getName() );
        assertEquals( "api-id-12345", captor.getAllValues().get( 0 ).getValue() );
        assertEquals( "token", captor.getAllValues().get( 1 ).getName() );
        assertEquals( "token-1234", captor.getAllValues().get( 1 ).getValue() );
        assertEquals( "include", captor.getAllValues().get( 2 ).getName() );
        assertEquals( "scores", String.valueOf( ( (SimpleQueryUriParam) captor.getAllValues().get( 2 ) ).getValue()[0] ) );
        assertEquals( GW_ID, headerCaptor.getValue().getFirst( HEADER_GATEWAY_REQUEST_ID ) );
        assertEquals( TRX_ID, headerCaptor.getValue().getFirst( HEADER_TRANSACTION_ID ) );
        assertEquals( "Basic cmF0ZXBheS1ncm91cDphcGkta2V5LTEyMzQ1Ng==", headerCaptor.getValue().getFirst( AUTHORIZATION ) );
    }

    private EmailageRequestDto createTestEmailageRequestDto() {

        EmailageRequestDto dto = new EmailageRequestBuilder().build();
        return dto;
    }
}

The interface for the EntityServiceConnectable is provided below,

public interface EntityServiceConnectable<RESPONSE> extends ServiceConnectable<RESPONSE> {

    ServiceResponse<RESPONSE> call(Object var1, RequestInformation var2, UriParam... var3);

    ServiceResponse<RESPONSE> call(Object var1, HttpHeaders var2, UriParam... var3);

    ServiceResponse<RESPONSE> call(Object var1, UriParam... var2);
}

The test is failing here,

ServiceResponse<EmailageResponseDto> response = connector.call( requestInfo, createTestEmailageRequestDto() );

Here is the error stack for the test,

java.lang.NullPointerException
    at com.ratepay.ella.service.io.EmailageConnectorTest.call(EmailageConnectorTest.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

[MockitoHint] EmailageConnectorTest.call (see javadoc for MockitoHint):
[MockitoHint] 1. Unused... -> at com.ratepay.ella.service.io.EmailageConnectorTest.call(EmailageConnectorTest.java:79)
[MockitoHint]  ...args ok? -> at com.ratepay.ella.service.io.EmailageConnector.call(EmailageConnector.java:65)

I debugged the setup and provided the screenshot below,

What do I miss here?

Body:
Edit:

For JUnit5 and mockito refer to this answer:

How to use Mockito with JUnit5

I've updated the example below as well.

Edit2:
As the TO did not state which JUnit version or mockito version is being used,
I will try to edit the answer if still does not work.

Thanks to @helospark for poining this out.

Using the Runner or the Rule does not work with JUnit5, so probably Mockito Version 2 should be used.

With Mockito Version 1 , an explictly call to the init Method is required.

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

For Junit5 and the latest Mockito version (2.27) the test class should look like this:

class InnerClass {
    public void doSomething(String fileName) {
    }
}

class SomeClass {

    InnerClass innerClass;

    public boolean doSomething(String fileName) {
        innerClass.doSomething(fileName);
        return true;
    }
}

@ExtendWith(MockitoExtension.class)
class SomeClassTest {

    @InjectMocks
    SomeClass someClass;

    @Mock
    InnerClass innerClass;

    @Test
    public void test() {
        someClass.doSomething("test");
        Mockito.verify(innerClass, Mockito.times(1)).doSomething(Mockito.any());
    }
}


问:
How can I pass the context to the Component
I have a problem about the context like below.

This is the NetworkProvider.js provide the internet statue

```<code>import React from 'react';
import NetInfo from '@react-native-community/netinfo';

export const NetworkContext = React.createContext({
  isConnected: true
});

export class NetworkProvider extends React.PureComponent {
  state = {
    isConnected: true
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => this.setState({
    isConnected
  });

  render() {
    return (
      <NetworkContext.Provider value={ this.state }>
        { this.props.children }
      </NetworkContext.Provider>
      );
  }
}
</code>```

This is the ExampleComponent.js

```<code>import React from 'react';
import { View, Text } from 'react-native';

import { NetworkContext } from './network_provider';

export class ExampleComponent extends React.PureComponent {
  static contextType = NetworkContext;

  render() {
    return (
      <View>
        <Text>
          You are now
          { this.context.isConnected ? 'online' : 'offline' }
        </Text>
      </View>
      );
  }
}
</code>```

App.js

```<code> static contextType = NetworkContext;
  render() {
    return (
      <NetworkProvider>
        <ExampleComponent />

        <View>
          <Text>
            You are now
            { this.context.isConnected ? 'online' : 'offline' }
          </Text>
        </View>
      </NetworkProvider>

      );
  }
}
</code>```

ExampleComponent.js is correct if I change wifi on/off
but copy the code from the ExampleComponent.js  doesn't work it always online!
why amd how to modify it?
thank you!

答:
Since you are listening to connectionChange event this code will work only when the connection changes.

To listen to network connection once use this:

```<code>NetInfo.fetch().then(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});
</code>```

Body:
I have a problem about the context like below.

This is the NetworkProvider.js provide the internet statue

import React from 'react';
import NetInfo from '@react-native-community/netinfo';

export const NetworkContext = React.createContext({
  isConnected: true
});

export class NetworkProvider extends React.PureComponent {
  state = {
    isConnected: true
  };

  componentDidMount() {
    NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
  }

  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectivityChange);
  }

  handleConnectivityChange = isConnected => this.setState({
    isConnected
  });

  render() {
    return (
      <NetworkContext.Provider value={ this.state }>
        { this.props.children }
      </NetworkContext.Provider>
      );
  }
}

This is the ExampleComponent.js

import React from 'react';
import { View, Text } from 'react-native';

import { NetworkContext } from './network_provider';

export class ExampleComponent extends React.PureComponent {
  static contextType = NetworkContext;

  render() {
    return (
      <View>
        <Text>
          You are now
          { this.context.isConnected ? 'online' : 'offline' }
        </Text>
      </View>
      );
  }
}

App.js

 static contextType = NetworkContext;
  render() {
    return (
      <NetworkProvider>
        <ExampleComponent />

        <View>
          <Text>
            You are now
            { this.context.isConnected ? 'online' : 'offline' }
          </Text>
        </View>
      </NetworkProvider>

      );
  }
}

ExampleComponent.js is correct if I change wifi on/off
but copy the code from the ExampleComponent.js  doesn't work it always online!
why amd how to modify it?
thank you!

Body:
Since you are listening to connectionChange event this code will work only when the connection changes.

To listen to network connection once use this:

NetInfo.fetch().then(state => {
  console.log("Connection type", state.type);
  console.log("Is connected?", state.isConnected);
});


问:
json_decode help
I have been trying to use some API's from various services, At the moment im trying to retrieve data about a video on vimeo,

I have successfully got the file and read the contents, however, i do not know how to access each part of the file that is returned as a .json.

Basically, how do i access the data in the json file using PHP

Thanks

答:
If the file is just JSON, you can use json_decode:

```<code>$data = json_decode(file_get_contents("url here"), true);
</code>```

and then access the data like a normal array. Of course you have to know the structure of the data you get in order to access it correctly. You can always use loops to iterate over it as well.

If the data is delivered as JSONP, you have to process it before, to remove the padding. I created a function for that.

Update:

In one of the comments you posted a link to the JSON file:

```<code>$data->video
</code>```

does not work because

$data is an array. $data[0]->something will work

video does not exist as property of the object.

Do a print_r($data) to see the structure.

Title: json_decode help

Body:
If the file is just JSON, you can use json_decode:

$data = json_decode(file_get_contents("url here"), true);

and then access the data like a normal array. Of course you have to know the structure of the data you get in order to access it correctly. You can always use loops to iterate over it as well.

If the data is delivered as JSONP, you have to process it before, to remove the padding. I created a function for that.

Update:

In one of the comments you posted a link to the JSON file:

$data->video

does not work because

$data is an array. $data[0]->something will work

video does not exist as property of the object.

Do a print_r($data) to see the structure.


问:
How to create a Javascript Object with sorted keys in a for loop?
I have an array like this:

```<code>[
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
]
</code>```

I need to create an object from the array, with the state as a key, and sorted.

```<code>{
  "New South Wales": [
    {
      "name": "Name NSW",
      "state": "New South Wales"
    }
  ],
  "Victoria": [
    {
      "name": "Name VIC",
      "state": "Victoria"
    }
  ],
}
</code>```

Notice that the NSW state has to be first in the object, but it is not the first item in the array. So after using loop through the array to create an object, the result is that the Victoria state appears first. I know that I can sort the result object, with many more codes. But is there any ways to create an object, whereas the keys are sorted immediately? (please check my code below)

```<code>function () {
  let result = {}
  array.forEach((item) => {
    if (!result[item.state]) {
      result[item.state] = []
    }
    result[item.state].push(item)
  })
  return result
}
</code>```

Update
Please read my question again. I know that there are a lot of ways for sorting the keys, but it's not what I meant. I want the keys to be sorted right in the loop, not after the object is created.

答:
const array = [
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
];

const states = array => array.sort((a, b) => a.name  b.name ? 1 : 0).reduce((result, state) =>  { result[state.state] = state; return result; }, {});

console.log(states(array))```

Body:
I have an array like this:

[
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
]

I need to create an object from the array, with the state as a key, and sorted.

{
  "New South Wales": [
    {
      "name": "Name NSW",
      "state": "New South Wales"
    }
  ],
  "Victoria": [
    {
      "name": "Name VIC",
      "state": "Victoria"
    }
  ],
}

Notice that the NSW state has to be first in the object, but it is not the first item in the array. So after using loop through the array to create an object, the result is that the Victoria state appears first. I know that I can sort the result object, with many more codes. But is there any ways to create an object, whereas the keys are sorted immediately? (please check my code below)

function () {
  let result = {}
  array.forEach((item) => {
    if (!result[item.state]) {
      result[item.state] = []
    }
    result[item.state].push(item)
  })
  return result
}

Update
Please read my question again. I know that there are a lot of ways for sorting the keys, but it's not what I meant. I want the keys to be sorted right in the loop, not after the object is created.

Body:
const array = [
  {
    "name": "Name VIC",
    "state": "Victoria"
  },
  {
    "name": "Name NSW",
    "state": "New South Wales"
  }
];

const states = array => array.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0).reduce((result, state) =>  { result[state.state] = state; return result; }, {});

console.log(states(array))


问:
SimpleInjector: register collection through adapter
With SimpleInjector you can register a collection of types:

interface ILogger { }
class FileLogger : ILogger { }
class SqlLogger : ILogger { }

// usage
var container = new Container();
container.Collection.Register<ILogger>(typeof(FileLogger), typeof(SqlLogger));
container.GetAllInstances<ILogger>(); // returns both ILoggers
```

<p>With that in place, I want to wrap such <code>ILogger</code>s with an abstraction <code>MyLogger</code> that I can use throughout my application:</p>

<pre class="lang-cs prettyprint-override"><code>interface MyLogger {
}

class LoggerAdapter : MyLogger {
    public LoggerAdapter(ILogger logger) { }
}
</code>```

However I can't get the container to register the logger adapter as a collection over the registered collection of ILoggers:

var container = new Container();
container.Collection.Register<ILogger>(typeof(FileLogger), typeof(SqlLogger));
container.Collection.Register<MyLogger>(typeof(ILogger));
// ArgumentException: The supplied type ILogger does not inherit from MyLogger.
// Parameter name: serviceTypes
```

While the exception message is clear (ILogger doesn't inherit from LoggerAdapter), I feel SimpleInjector should be able to make LoggerAdapters from ILoggers, by just injecting those ILoggers into LoggerAdapters.

Is there a clean way to register a collection of such adapters?

答:
There are multiple solutions here. The first thing that comes to my mind is to change your adapter to accept a list of loggers instead:

class LoggerAdapter : MyLogger
{
    public LoggerAdapter(IEnumerable<ILogger> loggers) { }
}
```
<p>This is likely a more pleasant solution as this allows you to inject a single <code>MyLogger</code> into your consumers, instead having to inject a collection of <code>MyLogger</code> instances.</p>
<p>If you really need a list of <code>MyLogger</code> instances, you can register the collection manually as follows:</p>
<pre class="lang-cs prettyprint-override"><code>container.RegisterSingleton<IEnumerable<MyLogger>>(
    () => container.GetAllInstances<ILogger>()
        .Select(logger => new LoggerAdapter(logger)));
</code>```

Body:
With SimpleInjector you can register a collection of types:

interface ILogger { }
class FileLogger : ILogger { }
class SqlLogger : ILogger { }

// usage
var container = new Container();
container.Collection.Register<ILogger>(typeof(FileLogger), typeof(SqlLogger));
container.GetAllInstances<ILogger>(); // returns both ILoggers

With that in place, I want to wrap such ILoggers with an abstraction MyLogger that I can use throughout my application:

interface MyLogger {
}

class LoggerAdapter : MyLogger {
    public LoggerAdapter(ILogger logger) { }
}

However I can't get the container to register the logger adapter as a collection over the registered collection of ILoggers:

var container = new Container();
container.Collection.Register<ILogger>(typeof(FileLogger), typeof(SqlLogger));
container.Collection.Register<MyLogger>(typeof(ILogger));
// ArgumentException: The supplied type ILogger does not inherit from MyLogger.
// Parameter name: serviceTypes

While the exception message is clear (ILogger doesn't inherit from LoggerAdapter), I feel SimpleInjector should be able to make LoggerAdapters from ILoggers, by just injecting those ILoggers into LoggerAdapters.

Is there a clean way to register a collection of such adapters?

Body:
There are multiple solutions here. The first thing that comes to my mind is to change your adapter to accept a list of loggers instead:

class LoggerAdapter : MyLogger
{
    public LoggerAdapter(IEnumerable<ILogger> loggers) { }
}

This is likely a more pleasant solution as this allows you to inject a single MyLogger into your consumers, instead having to inject a collection of MyLogger instances.

If you really need a list of MyLogger instances, you can register the collection manually as follows:

container.RegisterSingleton<IEnumerable<MyLogger>>(
    () => container.GetAllInstances<ILogger>()
        .Select(logger => new LoggerAdapter(logger)));


问:
Using Years Only (Without Months or Days) with Google Timeline Charts
I want to show a timeline (with Google Charts) with years only.

However, the examples on Google Charts Timelines' webpage always comprise years, months and days (for instance, new Date(1789, 3, 30)).

I have tried reducing the new Date() to just a year (e.g. new Date(2019)), but Google Charts interprets it as seconds (2.019 seconds).

```<code><script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
  google.charts.load("current", {packages:["timeline"]});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {
    var container = document.getElementById('div_timeline');
    var chart = new google.visualization.Timeline(container);
    var dataTable = new google.visualization.DataTable();

    dataTable.addColumn({ type: 'string', id: 'Nr' });
    dataTable.addColumn({ type: 'string', id: 'Journal' });
    dataTable.addColumn({ type: 'date', id: 'Founded' });
    dataTable.addColumn({ type: 'date', id: 'Now' });

    dataTable.addRows([
      [ '1', 'Journal of Leisure Research', new Date(1969), new Date(2019) ],
      [ '2', 'Critical Sociology',        new Date(2009),  new Date(2019) ],
      [ '3', 'Geographical Analysis',  new Date(1909),  new Date(2019) ]
                      ]);

    chart.draw(dataTable,options);

  }
</script>
</code>```

With this code, Journal of Leisure Research is now 1.969 seconds to 2.019 seconds.

Instead, I want the chart to assign the years 1969 to 2019.

How can I do that? Thanks for your help!

答:
Simply set the date to January 1st:</p>

```<code> <html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['timeline']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var container = document.getElementById('timeline');
        var chart = new google.visualization.Timeline(container);
        var dataTable = new google.visualization.DataTable();

         dataTable.addColumn({ type: 'string', id: 'Nr' });
    dataTable.addColumn({ type: 'string', id: 'Journal' });
    dataTable.addColumn({ type: 'date', id: 'Founded' });
    dataTable.addColumn({ type: 'date', id: 'Now' });

         dataTable.addRows([
      [ '1', 'Journal of Leisure Research', new Date(1969,1,0), new Date(2019,1,0) ],
      [ '2', 'Critical Sociology',        new Date(2009,1,0),  new Date(2019,1,0) ],
      [ '3', 'Geographical Analysis',  new Date(1909,1,0),  new Date(2019,1,0) ]]);
        chart.draw(dataTable);
      }
    </script>
  </head>
  <body>
    <div id="timeline" style="height: 180px;"></div>
  </body>
</html>
</code>```

Body:
I want to show a timeline (with Google Charts) with years only.

However, the examples on Google Charts Timelines' webpage always comprise years, months and days (for instance, new Date(1789, 3, 30)).

I have tried reducing the new Date() to just a year (e.g. new Date(2019)), but Google Charts interprets it as seconds (2.019 seconds).

With this code, Journal of Leisure Research is now 1.969 seconds to 2.019 seconds.

Instead, I want the chart to assign the years 1969 to 2019.

How can I do that? Thanks for your help!

Body:
Simply set the date to January 1st:

 <html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['timeline']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var container = document.getElementById('timeline');
        var chart = new google.visualization.Timeline(container);
        var dataTable = new google.visualization.DataTable();

         dataTable.addColumn({ type: 'string', id: 'Nr' });
    dataTable.addColumn({ type: 'string', id: 'Journal' });
    dataTable.addColumn({ type: 'date', id: 'Founded' });
    dataTable.addColumn({ type: 'date', id: 'Now' });

         dataTable.addRows([
      [ '1', 'Journal of Leisure Research', new Date(1969,1,0), new Date(2019,1,0) ],
      [ '2', 'Critical Sociology',        new Date(2009,1,0),  new Date(2019,1,0) ],
      [ '3', 'Geographical Analysis',  new Date(1909,1,0),  new Date(2019,1,0) ]]);
        chart.draw(dataTable);
      }
    </script>
  </head>
  <body>
    <div id="timeline" style="height: 180px;"></div>
  </body>
</html>


问:
Can I tell jenkins agent to execute job under a configured user?
I'm training a MacBook to be a jenkins agent for automation testing. On the MacBook, I logged in as user bob and installed everything needed (npm, yarn, xcode etc). Then I connected to a remote master using Java Web Start.

Because I launched the java thing in user bob, I assume jenkins pipeline jobs will also be under bob, which seems true - whoami command in pipeline echos bob. However, all dependencies cannot be found. If I echo $PATH I see a completely different result compared to echo $PATH directly on the MacBook.

I googled a bit, the problem might be that Jenkins create a new shell on everyjob. Can I tell jenkins pipeline to not to do this? I want the pipeline to use everything I configured manually for bob.

EDIT:

The main problem is jenkins pipeline's user has a different PATH. I ended up using environment directives to specify which path to use.

```<code>environment {
    PATH = "/Users/bappo/.nvm/versions/node/v8.11.3/bin:$PATH"
  }
</code>```

答:
What where you trying to configure? If you have parameters/configuration for your pipeline I strongly recommend to use pipeline parameters. They can either configured manually (including default values) or from the jenkinsfile.

example

Body:
I'm training a MacBook to be a jenkins agent for automation testing. On the MacBook, I logged in as user bob and installed everything needed (npm, yarn, xcode etc). Then I connected to a remote master using Java Web Start.

Because I launched the java thing in user bob, I assume jenkins pipeline jobs will also be under bob, which seems true - whoami command in pipeline echos bob. However, all dependencies cannot be found. If I echo $PATH I see a completely different result compared to echo $PATH directly on the MacBook.

I googled a bit, the problem might be that Jenkins create a new shell on everyjob. Can I tell jenkins pipeline to not to do this? I want the pipeline to use everything I configured manually for bob.

EDIT:

The main problem is jenkins pipeline's user has a different PATH. I ended up using environment directives to specify which path to use.

environment {
    PATH = "/Users/bappo/.nvm/versions/node/v8.11.3/bin:$PATH"
  }


问:
CRT file does not contain a privatekey
Because of the validations done on the ssl certs, the cert cannot be a self-signed cert.   I have therefore used the following commands with openssl (for windows) to create a CA, and derived crt.   I have successfully done this several years ago, and I think I ran into this issue before, but I cannot remember how I solved it.   Nor can I find another post that solve the issue or reminds me what the solution was.

I am using the following commands:

```<code>openssl genrsa -des3 -out myCA.key 2048
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 1825 -out myCA.pem
openssl genrsa -out derived.key 2048
openssl req -new -key derived.key -out derived.csr
openssl x509 -req -in derived.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial -out derived.crt -days 1825 -sha256 -extfile derived.ext

[derived.ext file contents]
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = %%DOMAIN%%
</code>```

The CA cert (myCA.PEM file] installs fine into the trusted roots folder. The derived.crt installs fine into the personal store, and validates properly with the CA.  However, the derived.crt does not show a private key and cannot be used for SSL. Can anyone tell me what step I got wrong or am missing?

答:
I seem to have solved the issue finally.   Apparently a .crt file cannot contain a private key.   Using the following command, I merged the .crt and key into a .pfx file, which imported and now shows a private key:</p>

```<code>openssl pkcs12 -export -in derived.crt -inkey derived.key -out derived.pfx
</code>```

Title: CRT file does not contain a privatekey

Body:
Because of the validations done on the ssl certs, the cert cannot be a self-signed cert.   I have therefore used the following commands with openssl (for windows) to create a CA, and derived crt.   I have successfully done this several years ago, and I think I ran into this issue before, but I cannot remember how I solved it.   Nor can I find another post that solve the issue or reminds me what the solution was.

I am using the following commands:

openssl genrsa -des3 -out myCA.key 2048
openssl req -x509 -new -nodes -key myCA.key -sha256 -days 1825 -out myCA.pem
openssl genrsa -out derived.key 2048
openssl req -new -key derived.key -out derived.csr
openssl x509 -req -in derived.csr -CA myCA.pem -CAkey myCA.key -CAcreateserial -out derived.crt -days 1825 -sha256 -extfile derived.ext

[derived.ext file contents]
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = %%DOMAIN%%

The CA cert (myCA.PEM file] installs fine into the trusted roots folder. The derived.crt installs fine into the personal store, and validates properly with the CA.  However, the derived.crt does not show a private key and cannot be used for SSL. Can anyone tell me what step I got wrong or am missing?

Body:
I seem to have solved the issue finally.   Apparently a .crt file cannot contain a private key.   Using the following command, I merged the .crt and key into a .pfx file, which imported and now shows a private key:

openssl pkcs12 -export -in derived.crt -inkey derived.key -out derived.pfx