问:
Strong numbers in C#
I have to code a function that prints every "strong" integer, between 1 and n. These integers verify the sum of the factorials of each of its digits is equal to itself. For example:

 145 because 1! + 4! + 5! = 145.

So far what I did:

```<code>    public static long Fac(long n)
    {
        var i = 1;
        for (; n > 1; n--)
        {
            i *= (int) n;
        }
        return i;
    }
    public static bool IsStrong(int n)
    {

        var i = 1;
        var sum = 0;
        while (n > 0)
        {
            i = n % 10;
            sum += (int)Fac(i);
            n = n / 10;
        }

        if (sum == n)
            return true;
        else

            return false;

    }

    public static void Print_Strong(int n)
    {
        if (IsStrong(n))
            Console.Write("{0} is STRONG!  -W", n);
        else
            Console.Write("{0} is not strong. -w", n);
    }
</code>```

When I run it, it never leaves the loop .

答:
You have 3 problems in your code:

while (n >= 0) should be while (n > 0) otherwise you will never
leave the loop.

When the sum is equal to n you have to return true

sum == n will never be true because n will be 0 in the end

Here's a fix:

```<code>public static bool IsStrong(int n)
{
    long sum = 0;
    int n2 = n;

    while (n2 > 0)
    {
        sum += Fac(n2 % 10);
        n2 = n2 / 10;
    }

    return sum == n;
}
</code>```

Title: Strong numbers in C#

Body:
I have to code a function that prints every "strong" integer, between 1 and n. These integers verify the sum of the factorials of each of its digits is equal to itself. For example:

 145 because 1! + 4! + 5! = 145.

So far what I did:

    public static long Fac(long n)
    {
        var i = 1;
        for (; n > 1; n--)
        {
            i *= (int) n;
        }
        return i;
    }
    public static bool IsStrong(int n)
    {

        var i = 1;
        var sum = 0;
        while (n > 0)
        {
            i = n % 10;
            sum += (int)Fac(i);
            n = n / 10;
        }

        if (sum == n)
            return true;
        else

            return false;

    }

    public static void Print_Strong(int n)
    {
        if (IsStrong(n))
            Console.Write("{0} is STRONG!  -W", n);
        else
            Console.Write("{0} is not strong. -w", n);
    }

When I run it, it never leaves the loop .

Body:
You have 3 problems in your code:

while (n >= 0) should be while (n > 0) otherwise you will never
leave the loop.

When the sum is equal to n you have to return true

sum == n will never be true because n will be 0 in the end

Here's a fix:

public static bool IsStrong(int n)
{
    long sum = 0;
    int n2 = n;

    while (n2 > 0)
    {
        sum += Fac(n2 % 10);
        n2 = n2 / 10;
    }

    return sum == n;
}


来源: stackexchange

问:
Getting FB user's data from AWS "CognitoIdentityCredentials" using Facebook Login
Good day,

I've got an API setup, it's sitting behind AWS's APIGateway, secured with IAM, in this case it's a Cognito Federated ID pool.

I have the following code:

```<code>function doFacebookLogin() {
    FB.login(function (response) {
        fbAuthToken = response.authResponse.accessToken;

        doFetchProfile();
    }, {scope: 'public_profile,email', return_scopes: true});
}

function doFetchProfile() {
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'eu-west-1:*****************************',
        Logins: {
            'graph.facebook.com': fbAuthToken
        }
    });

    // Obtain AWS credentials
    AWS.config.credentials.get(function () {
        apigClient = apigClientFactory.newClient({
            accessKey: AWS.config.credentials.accessKeyId,
            secretKey: AWS.config.credentials.secretAccessKey,
            sessionToken: AWS.config.credentials.sessionToken,
            region: 'eu-west-1'
        });

        apigClient.userProfileGet({
            'x-fb-access-token': fbAuthToken
        }).then(function (data) {
            console.log(data);
        });
    });
}
</code>```

Right now, I'm sending the Facebook AccessToken in the header, because my server (sitting behind the AWS APIGateway) needs access to the user's facebook profile data.

I was hoping that by simply signing into the Cognito Federated ID pool, using the Facebook provider, would be enough to have AWS's APIGateway SDK pass the accessToken (in some form or another) along with every request.

It doesn't seem to be the case, I can't find a way to extract the Facebook data I need without sending the AccessToken in the header as per the example above.

Am I wrong in my understanding of what should happen?

Thanks for the help in advance :)

答:
If you're server behind API Gateway needs the Facebook access token to access some Facebook APIs, then yes you'll always need to pass the Facebook access token through in API GW.

The Cognito federated login allows you to exchange a Facebook token for AWS credentials for accessing AWS-protected services.

ContentLicense: CC BY-SA 3.0

Body:
Good day,

I've got an API setup, it's sitting behind AWS's APIGateway, secured with IAM, in this case it's a Cognito Federated ID pool.

I have the following code:

function doFacebookLogin() {
    FB.login(function (response) {
        fbAuthToken = response.authResponse.accessToken;

        doFetchProfile();
    }, {scope: 'public_profile,email', return_scopes: true});
}

function doFetchProfile() {
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        IdentityPoolId: 'eu-west-1:*****************************',
        Logins: {
            'graph.facebook.com': fbAuthToken
        }
    });

    // Obtain AWS credentials
    AWS.config.credentials.get(function () {
        apigClient = apigClientFactory.newClient({
            accessKey: AWS.config.credentials.accessKeyId,
            secretKey: AWS.config.credentials.secretAccessKey,
            sessionToken: AWS.config.credentials.sessionToken,
            region: 'eu-west-1'
        });

        apigClient.userProfileGet({
            'x-fb-access-token': fbAuthToken
        }).then(function (data) {
            console.log(data);
        });
    });
}

Right now, I'm sending the Facebook AccessToken in the header, because my server (sitting behind the AWS APIGateway) needs access to the user's facebook profile data.

I was hoping that by simply signing into the Cognito Federated ID pool, using the Facebook provider, would be enough to have AWS's APIGateway SDK pass the accessToken (in some form or another) along with every request.

It doesn't seem to be the case, I can't find a way to extract the Facebook data I need without sending the AccessToken in the header as per the example above.

Am I wrong in my understanding of what should happen?

Thanks for the help in advance :)


问:
MYSQL entries from one table that appear most often in another table
I have 2 tables, authors and books

authors contains the unique id authorId

books also contains this as a foreign key

I need to know the authors with the most number of books. If 2 or more authors are tied for the greatest number of books, I need to show both authors

I have been able to achieve this by first getting the maximum count

```<code>SELECT @maxCount := (MAX(counter)) FROM (SELECT count(*) AS counter FROM books GROUP BY authorId) AS counts;
</code>```

and then using it to get the Ids with that count as part of my author selection

```<code>SELECT *
FROM authors
WHERE authorId IN (
    SELECT authorId
    FROM books
    GROUP BY authorId
    HAVING COUNT(*) = @maxCount
);
</code>```

I've been told that I am not allowed to use variables and that what I've done is horribly inefficient if the tables grow very large.

Am I missing something obvious here? Is there a way to do this in a single statement without a variable (or temp table), and without having to select/group the entire books table twice?

答:
Symcbean solution is great... you can add Limit 1 to it, to get only one instance.

```<code>SELECT A.authorId, A.name, COUNT(*) AS num_books
FROM authors A
INER JOIN books B
ON A.authorId=B.AuthorId
GROUP BY A.authorId, A.name
ORDER BY COUNT(*) DESC
LIMIT 1
</code>```

But if you want to get all the authors who share the max number of books, your best bet is to store the max(count) in a variable, or temp table and use it in second query.

for example, you can store the info in the following temp table

```<code>CREATE TEMPORARY TABLE IF NOT EXISTS maxBooks AS (
    SELECT authorId, COUNT(*)  AS num_books
    FROM books
    GROUP BY authorId
    ORDER BY COUNT(*) DESC
    LIMIT 1
)
</code>```

now you can join it to your table to get counts which are equal to max count

Body:
I have 2 tables, authors and books

authors contains the unique id authorId

books also contains this as a foreign key

I need to know the authors with the most number of books. If 2 or more authors are tied for the greatest number of books, I need to show both authors

I have been able to achieve this by first getting the maximum count

SELECT @maxCount := (MAX(counter)) FROM (SELECT count(*) AS counter FROM books GROUP BY authorId) AS counts;

and then using it to get the Ids with that count as part of my author selection

SELECT *
FROM authors
WHERE authorId IN (
    SELECT authorId
    FROM books
    GROUP BY authorId
    HAVING COUNT(*) = @maxCount
);

I've been told that I am not allowed to use variables and that what I've done is horribly inefficient if the tables grow very large.

Am I missing something obvious here? Is there a way to do this in a single statement without a variable (or temp table), and without having to select/group the entire books table twice?

Body:
Symcbean solution is great... you can add Limit 1 to it, to get only one instance.

SELECT A.authorId, A.name, COUNT(*) AS num_books
FROM authors A
INER JOIN books B
ON A.authorId=B.AuthorId
GROUP BY A.authorId, A.name
ORDER BY COUNT(*) DESC
LIMIT 1

But if you want to get all the authors who share the max number of books, your best bet is to store the max(count) in a variable, or temp table and use it in second query.

for example, you can store the info in the following temp table

CREATE TEMPORARY TABLE IF NOT EXISTS maxBooks AS (
    SELECT authorId, COUNT(*)  AS num_books
    FROM books
    GROUP BY authorId
    ORDER BY COUNT(*) DESC
    LIMIT 1
)

now you can join it to your table to get counts which are equal to max count


问:
exchange two columns and remove the duplicates in a data frame using R
Here is an example to explain what I want to do. I have a data frame like:

```<code>X    Y
1    1
1    2
1    3
2    1
2    2
2    3
3    1
3    2
3    3
</code>```

I want to change it to another format:

```<code>X1    Y1    X2    Y2
1     1     1     1
1     2     2     1
1     3     3     1
......
</code>```

For two rows in the first table, say X=1, Y=2 and X=2, Y=1. They just exchange each other's values. So I want to put such rows in on row, as shown in the second table, and then remove the duplicates. So, the 'thin and long' table is turned to 'short and fat'. I know how to do it using two for loops. But in R, such operation takes for ever. So, can anyone help me with a quick way?

Here is a smallest example:

The original table is:

```<code>X    Y
1    2
2    1
</code>```

The transferred table that I want is like:

```<code>X1    Y1     X2    Y2
1     2      2     1
</code>```

So, the rows in the first table that just exchanges values are integrated into one row in the second table and the extra row in the first table is removed.

答:
```<code>library(tidyverse)
df <- tibble(x1 = 1, 1, 1, 2, 2, 2, 3, 3, 3,
            y1 = 1, 2, 3, 1, 2, 3, 1, 2, 3)
df <- df %>% mutate(x2 = y1, y2 = x1) %>% distinct()
</code>```

I think this does the trick.

ContentLicense: CC BY-SA 4.0

Body:
Here is an example to explain what I want to do. I have a data frame like:

X    Y
1    1
1    2
1    3
2    1
2    2
2    3
3    1
3    2
3    3

I want to change it to another format:

X1    Y1    X2    Y2
1     1     1     1
1     2     2     1
1     3     3     1
......

For two rows in the first table, say X=1, Y=2 and X=2, Y=1. They just exchange each other's values. So I want to put such rows in on row, as shown in the second table, and then remove the duplicates. So, the 'thin and long' table is turned to 'short and fat'. I know how to do it using two for loops. But in R, such operation takes for ever. So, can anyone help me with a quick way?

Here is a smallest example:

The original table is:

X    Y
1    2
2    1

The transferred table that I want is like:

X1    Y1     X2    Y2
1     2      2     1

So, the rows in the first table that just exchanges values are integrated into one row in the second table and the extra row in the first table is removed.

Body:
library(tidyverse)
df <- tibble(x1 = 1, 1, 1, 2, 2, 2, 3, 3, 3,
            y1 = 1, 2, 3, 1, 2, 3, 1, 2, 3)
df <- df %>% mutate(x2 = y1, y2 = x1) %>% distinct()

I think this does the trick.


问:
TFS 2017 Query Related Items In Build upon release
I've received a request to create a custom report email for our executives. When we do a major release they want a list of Features of that release. What i need to do is read the related Tasks to the release then traverse up parent nodes until i get to the features that are marked with a tag "Executive". My Issue is that I can't find any document on how get the "Work items linked to associated changes".
I've been able to just through to get the specific build
GET http://XXX.MYTFSSERVER.COM/tfs/Collection/Project/e5e632e2-ae70-41c9-9d72-6686d2375f14/_apis/build/Builds/69330

But I don't see any link to get the workitems associated to the build.

答: Releases already do this out-of-the-box. On the Work Items tab of a release, you can have it generate an email that contains all of the work items associated with that release relative to an earlier release.


问:
How to filter data from table with date in descending order using PHP
I need to fetch all data from table as per date field in descending order using PHP and Mysql. I am explaining my table below.

db_special:

```<code>id          name         date

1            Ram          12/04/2017 15:31:57 PM

2            Raj          12/03/2017 05:31:57 AM

3            Rahul        11/28/2017 12:30:54 PM
</code>```

Here is my query:

```<code>select *
from db_special
where
    STR_TO_DATE(date, '%m/%d/%Y')
    BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
</code>```

Here I implemented one logic to fetch last 7 days data and now I need to implement sorting as per the same date field in descending order using MySQL and PHP.

答:
Are you really using a VARCHAR/CHAR/CLOB field to store a date? That is very bad. It makes kittens cry. Please don't do it.

using PHP and Mysql

No. you don't retrieve data from a DBMS then sort it in PHP. That too is very bad (unless you're Facebook, in which case it is possibly a bit silly, but that is another story). You sort in the database.

Just add an ORDER BY clause at the end of your SELECT

Body:
I need to fetch all data from table as per date field in descending order using PHP and Mysql. I am explaining my table below.

db_special:

id          name         date

1            Ram          12/04/2017 15:31:57 PM

2            Raj          12/03/2017 05:31:57 AM

3            Rahul        11/28/2017 12:30:54 PM

Here is my query:

select *
from db_special
where
    STR_TO_DATE(date, '%m/%d/%Y')
    BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()

Here I implemented one logic to fetch last 7 days data and now I need to implement sorting as per the same date field in descending order using MySQL and PHP.


问:
Why can't I replace this function with a lambda
I'm writing a RNN in tensorflow and I want to stack a few LSTM cells on top of each other. According to the tensorflow tutorial I should do it like so:

```<code>    def lstm_cell():
        return tf.contrib.rnn.BasicLSTMCell(lstm_size)
    stacked_lstm = tf.contrib.rnn.MultiRNNCell(
        [lstm_cell() for _ in range(number_of_layers)])
</code>```

When I do this, things work as expected. But I wondered if I could replace the defining of the function with a simple lambda function...unfortunately that doesn't work. What I replaced the above code with was:

```<code>    stacked_lstm = tf.contrib.rnn.MultiRNNCell([lambda:tf.contrib.rnn.
        BasicLSTMCell(lstm_size) for _ in range(number_of_layers)])
</code>```

I thought this would work since my understanding of the "lambda" in python was specifically so that I could replace having to define a separate function for very simple functions like this. Is my understanding of lambda wrong? The error message I get when doing the bottom one is:

```<code>    AttributeError: 'function' object has no attribute 'zero_state'
</code>```

I would have thought that the two different methods of stacking LSTMs was equivalent, but apparently not?

答:
```<code>[lambda:tf.contrib.rnn.BasicLSTMCell(lstm_size) for _ in range(number_of_layers)]
</code>```

Here, lambda:tf.contrib.rnn.BasicLSTMCell(lstm_size) only defines a function and does not call it. Instead, you can directly access BasicLSTMCell() function:

```<code>[tf.contrib.rnn.BasicLSTMCell(lstm_size) for _ in range(number_of_layers)]
</code>```

You can then further shorten it by having MultiRNNCell and BasicLSTMCell imported this way:

```<code>from tensorflow.contrib.rnn import MultiRNNCell, BasicLSTMCell

lstm_stacks = [BasicLSTMCell(lstm_size) for _ in range(number_of_layers)]
stacked_lstm = MultiRNNCell(lstm_stacks)
</code>```

Body:
I'm writing a RNN in tensorflow and I want to stack a few LSTM cells on top of each other. According to the tensorflow tutorial I should do it like so:

    def lstm_cell():
        return tf.contrib.rnn.BasicLSTMCell(lstm_size)
    stacked_lstm = tf.contrib.rnn.MultiRNNCell(
        [lstm_cell() for _ in range(number_of_layers)])

When I do this, things work as expected. But I wondered if I could replace the defining of the function with a simple lambda function...unfortunately that doesn't work. What I replaced the above code with was:

    stacked_lstm = tf.contrib.rnn.MultiRNNCell([lambda:tf.contrib.rnn.
        BasicLSTMCell(lstm_size) for _ in range(number_of_layers)])

I thought this would work since my understanding of the "lambda" in python was specifically so that I could replace having to define a separate function for very simple functions like this. Is my understanding of lambda wrong? The error message I get when doing the bottom one is:

    AttributeError: 'function' object has no attribute 'zero_state'

I would have thought that the two different methods of stacking LSTMs was equivalent, but apparently not?

Body:
[lambda:tf.contrib.rnn.BasicLSTMCell(lstm_size) for _ in range(number_of_layers)]

Here, lambda:tf.contrib.rnn.BasicLSTMCell(lstm_size) only defines a function and does not call it. Instead, you can directly access BasicLSTMCell() function:

[tf.contrib.rnn.BasicLSTMCell(lstm_size) for _ in range(number_of_layers)]

You can then further shorten it by having MultiRNNCell and BasicLSTMCell imported this way:

from tensorflow.contrib.rnn import MultiRNNCell, BasicLSTMCell

lstm_stacks = [BasicLSTMCell(lstm_size) for _ in range(number_of_layers)]
stacked_lstm = MultiRNNCell(lstm_stacks)


问:
Setting WPF background Opacity programmatically
I'm working on application which creates a new wpf border component for each row in a database. This means I've got to style the border component in C# rather than XAML (as far as I'm aware). The styling is all good so far apart from trying to set the background opacity.

```<code>motherboards.Add(new Border());
Border moboBorder = motherboards[i];
moboBorder.Width = 150;
moboBorder.Height = 150;
moboBorder.BorderBrush = Brushes.Black;
moboBorder.Background = Brushes.White;
moboBorder.CornerRadius = new CornerRadius(10);
moboBorder.Margin = new Thickness(5);
moboBorder.BorderThickness = new Thickness(1);
</code>```

You can adjust the background opacity in XAML like so

```<code><Border BorderThickness="1" Height="100" Width="100">
    <Border.BorderBrush>
        <SolidColorBrush Color="Black" Opacity="0.7"/>
    </Border.BorderBrush>
</Border>
</code>```

But as I've said I'm creating the component in C# rather than XAML. I guess this is how you set the value in c#

```<code>moboBorder.Background.Opacity = //Value
</code>```

However, I can't figure out what kind of value it takes, not just a straight up number, nothing from brushes than I can see and nothing like = new Opacity()

I've tried googling around but everything is about setting the opacity for the whole element rather than just the background of it.

答:
The equivalent of the XAML

```<code><Border.BorderBrush>
    <SolidColorBrush Color="Black" Opacity="0.7"/>
</Border.BorderBrush>
</code>```

in code behind would be

```<code>moboBorder.Background = new SolidColorBrush
{
    Color = Colors.Black,
    Opacity = 0.7
};
</code>```

In contrast to the predefined Brushes in the Brushes class (which are frozen), the above SolidColorBrush can be changed at any time later, like

```<code>moboBorder.Background.Opacity = 0.5;
</code>```

Body:
I'm working on application which creates a new wpf border component for each row in a database. This means I've got to style the border component in C# rather than XAML (as far as I'm aware). The styling is all good so far apart from trying to set the background opacity.

motherboards.Add(new Border());
Border moboBorder = motherboards[i];
moboBorder.Width = 150;
moboBorder.Height = 150;
moboBorder.BorderBrush = Brushes.Black;
moboBorder.Background = Brushes.White;
moboBorder.CornerRadius = new CornerRadius(10);
moboBorder.Margin = new Thickness(5);
moboBorder.BorderThickness = new Thickness(1);

You can adjust the background opacity in XAML like so

<Border BorderThickness="1" Height="100" Width="100">
    <Border.BorderBrush>
        <SolidColorBrush Color="Black" Opacity="0.7"/>
    </Border.BorderBrush>
</Border>

But as I've said I'm creating the component in C# rather than XAML. I guess this is how you set the value in c#

moboBorder.Background.Opacity = //Value

However, I can't figure out what kind of value it takes, not just a straight up number, nothing from brushes than I can see and nothing like = new Opacity()

I've tried googling around but everything is about setting the opacity for the whole element rather than just the background of it.

Body:
The equivalent of the XAML

<Border.BorderBrush>
    <SolidColorBrush Color="Black" Opacity="0.7"/>
</Border.BorderBrush>

in code behind would be

moboBorder.Background = new SolidColorBrush
{
    Color = Colors.Black,
    Opacity = 0.7
};

In contrast to the predefined Brushes in the Brushes class (which are frozen), the above SolidColorBrush can be changed at any time later, like

moboBorder.Background.Opacity = 0.5;


问:
jQuery: Conflict with removeData() executing at inadequate times
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

```<code><div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
</code>```

Html of the modal:

```<code>@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label asp-for="DepartmentID" class="col-md-2 control-label"></label>
                <div class="col-md-10">
                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label">Distrito</label>
                <div class="col-md-10">
                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>
                </div>
            </div>
            {... more elements}
       </div>
</form>
</code>```

GET Method:

```<code>    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }
</code>```

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

```<code><script type="text/javascript">

    var wasclicked = 0;
    var $this = this;

    $(document).ready(function () {

        document.getElementById("modalbutton").onclick = function () {
            //is AddNew Store button is hitted, this var = 1
            wasclicked = 1;
        };

        $('#modal-action-store').on('hidden.bs.modal', function () {
            //global.wasclicked = 0;
            wasclicked = 0;
            $(this).removeData('bs.modal');
        });

        $('#modal-action-store').on('shown.bs.modal', function (e) {
            console.log($('#DistrictID').length);
            //if wasclicked equals 1 that means we are in the AddNew Store scenario.
            if (wasclicked == 1) {
                //a default value is sent to District dropdownlist
                var items = "<option value='0'>-- Seleccione Distrito --</option>";
                $('#DistrictID').html(items);
            };
        });
    });
</script>
</code>```

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

```<code>  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"
</code>```

And this line is lost:

```<code>var items = "<option value='0'>-- Seleccione Distrito --</option>";
</code>```

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

答:
modal() only accepts an options object or a string. To append elements to your modal, we can append them when the show.bs.modal is triggered:

$('#modal-action-store').on('show.bs.modal', function(e){
 var items = "<option value='0'>-- Seleccione Distrito --</option>";
    $('#DistrictID').html(items);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="btn-group" id="modalbutton">

            <i class="glyphicon glyphicon-plus"></i>  NEW STORE

</div>
<div class="modal" id="modal-action-store">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <select class="form-control" id="DistrictID" name="DistrictID">
        </select>
      </div>
    </div>
  </div>
</div></code>```

Body:
I have a modal window used to update or add a new object Store.

This modal is called remotely which information is loaded from a GET method constructed in ASP.NET.

Button that calls the modal:

              NEW STORE

Html of the modal:

@model Application.Models.ApplicationviewModels.StoreIndexData
@using Application.Models

<form asp-action="Create" role="form">
        @await Html.PartialAsync("_ModalHeader", new ModalHeader
    { Heading = String.Format("Actualización de Modelo: Tiendas") })

                    <select asp-for="DepartmentID" class="form-control"
                            asp-items="@(new SelectList(@ViewBag.ListofDepartment,"DepartmentID","DepartmentName"))"></select>

                Distrito

                    <select class="form-control" id="DistrictID" name="DistrictID" asp-for="DistrictID"
                            asp-items="@(new SelectList(@ViewBag.ListofDistrict,"DistrictID","DistrictName"))"></select>

            {... more elements}

</form>

GET Method:

    public IActionResult Create(int? id)
    {
        List<Department> DepartmentList = new List<Department>();
        DepartmentList = (from department in _context.Departments
                          select department).ToList();
        DepartmentList.Insert(0, new Department { DepartmentID = 0, DepartmentName = "-- Seleccione Departamento --" });
        ViewBag.ListofDepartment = DepartmentList;

        StoreIndexData edit = new StoreIndexData();
        List<District> ListofDistrict = new List<District>();
        ListofDistrict.Insert(0, new District { DistrictID = 0, DistrictName = "-- PRUEBA --" });
        ViewBag.ListofDistrict = ListofDistrict;

        return PartialView("~/Views/Shared/Stores/_Create.cshtml");
    }

The problem:

I have the following jQuery which asigns a value to DistrictID once the modal opens:

The problem right now is that after this line jQuery is executed, the value that was assigned to DistrictID gets overwritten by :

  ViewBag.ListofDistrict = ListofDistrict; //"-- PRUEBA --"

And this line is lost:

var items = "<option value='0'>-- Seleccione Distrito --</option>";

What I suspect is that the information coming from the Controller overwrites any result from jQuery over the  in the modal.

After debugging I have identified three diferent moments:

Moment 1: First time we open the modal

The modal hasn't opened yet and the jQuery executes

For this reason it does not identify DistrictID

The result from the GET Action fills the modal's inputs.

Moment 2 - Part 1: Second time we open the modal

This time the modal opens before the jQuery is executed

The DistrictID has the value from the GET Method before we assign the value from jQuery

Moment 2 - Part 2: When the value from jQuery is assigned

The value from jQuery is assigned to DistrictID

This value will be overwritten by the result of the GET Action

Question:

Can anyone explain or help me understand what might be causing this? What else can I do to identify the reason behind this?

Body:
modal() only accepts an options object or a string. To append elements to your modal, we can append them when the show.bs.modal is triggered:

$('#modal-action-store').on('show.bs.modal', function(e){
 var items = "<option value='0'>-- Seleccione Distrito --</option>";
    $('#DistrictID').html(items);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<div class="btn-group" id="modalbutton">
    <a id="createEditStoreModal" data-toggle="modal" asp-action="Create"
         data-target="#modal-action-store" class="btn btn-primary">
            <i class="glyphicon glyphicon-plus"></i>  NEW STORE
        </a>
</div>
<div class="modal" id="modal-action-store">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <select class="form-control" id="DistrictID" name="DistrictID">
        </select>
      </div>
    </div>
  </div>
</div>


问:
MySQL: Get the difference between timestamps

Possible Duplicate:

  MySQL: how to get the difference between two timestamps in seconds

How can I get the difference in seconds (or any other unit) between two timestamps? If I use select NOW() - '2012-01-01 00:00:00' I get 20110121168303 which is wrong.

My favorite solution

http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timestampdiff

答: Maybe this can help you : http://forums.mysql.com/read.php?52,124334,124334</p>

ContentLicense: CC BY-SA 2.5


问:
Display: inline-block for a list
I want to create a list that should look like this

```<code>Few Clouds
Humidity: 33%
Wind: 5.1 mph
</code>```

However, because I'm using JS to insert
 elements , I have to pre-write some parts of the list like this (excluding the [JS] part):

```<code>[JS]
Humidity: [JS]%
Wind: [JS] mph
</code>```

Here's my code to solve this:

```<code><ul class="list-unstyled">
    <li class="clouds text-capitalize inline"> </li>
    <span class="inline">Humidity: </span><li class="wind inline"> </li><span class="inline">%</span>
    <span class="inline">Wind: </span><li class="humidity inline"> </li><span class="inline">mph</span>
 </ul>
</code>```

and

```<code>.inline{
   display: inline-block;
}
</code>```

but this results in (after the javascript plugs in data)

```<code>Few Clouds Humidity: 5.82 % Wind: 100mph
</code>```

which is expected, but I dont know how to fix it so it looks like how I wanted in the first snippet. Ignore the other classes, they're bootstrap classes and classes for me to access them in javascript. Thank you for any help.

答:
The only valid child of
 is
. Your  tags should go inside your
 tags, not the other way around. I'd also recommend creating a second  tag inside each
 to cover the JavaScript components. Considering  tags are inline by default, the pair of  tags will display next to each other on the same line.

This can be seen in the following:

var elements = document.getElementsByClassName('javascript');

for (var i = 0; i < elements.length; i++) {
  elements[i].innerHTML = i;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="list-unstyled">
  <li class="clouds text-capitalize inline">
    <span class="inline">Humidity: </span>
    <span class="javascript"></span></li>
  <li class="wind inline">
    <span class="inline">Wind %: </span>
    <span class="javascript"></span>
  </li>
  <li class="humidity inline">
    <span class="inline">mph: </span>
    <span class="javascript"></span>
  </li>
</ul></code>```

Note that if you want all three components to display on the same line, you could set the
 elements to display: inline-block with:

```<code>li {
  display: inline-block;
}
</code>```

...Though that would essentially defeat the purpose of using an
 element in the first place.

Hope this helps! :)

Title: Display: inline-block for a list

Body:
I want to create a list that should look like this

Few Clouds
Humidity: 33%
Wind: 5.1 mph

However, because I'm using JS to insert
 elements , I have to pre-write some parts of the list like this (excluding the [JS] part):

[JS]
Humidity: [JS]%
Wind: [JS] mph

Here's my code to solve this:

    Humidity:

%
    Wind:

mph

and

.inline{
   display: inline-block;
}

but this results in (after the javascript plugs in data)

Few Clouds Humidity: 5.82 % Wind: 100mph

which is expected, but I dont know how to fix it so it looks like how I wanted in the first snippet. Ignore the other classes, they're bootstrap classes and classes for me to access them in javascript. Thank you for any help.

Body:
The only valid child of <ul> is <li>. Your <span> tags should go inside your <li> tags, not the other way around. I'd also recommend creating a second <span> tag inside each <li> to cover the JavaScript components. Considering <span> tags are inline by default, the pair of <span> tags will display next to each other on the same line.

This can be seen in the following:

var elements = document.getElementsByClassName('javascript');

for (var i = 0; i < elements.length; i++) {
  elements[i].innerHTML = i;
}

<ul class="list-unstyled">
  <li class="clouds text-capitalize inline">
    <span class="inline">Humidity: </span>
    <span class="javascript"></span></li>
  <li class="wind inline">
    <span class="inline">Wind %: </span>
    <span class="javascript"></span>
  </li>
  <li class="humidity inline">
    <span class="inline">mph: </span>
    <span class="javascript"></span>
  </li>
</ul>

Note that if you want all three components to display on the same line, you could set the <li> elements to display: inline-block with:

li {
  display: inline-block;
}

...Though that would essentially defeat the purpose of using an <li> element in the first place.

Hope this helps! :)


问:
How to select data from firebase realtime database
I have a database with a structure, roughly like

```<code>// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}
</code>```

But I can't figure out how to select users who are members of the same set of groups

答:
You'd have to define an additional group_combinations or all_groups index, where you store each user under their combines the groups:

```<code>all_groups: {
  "techpioneers_womentechmakers": {
    alovelace: true
  }
}
</code>```

Body:
I have a database with a structure, roughly like

// An index to track Ada's memberships
{
  "users": {
    "alovelace": {
      "name": "Ada Lovelace",
      // Index Ada's groups in her profile
      "groups": {
         // the value here doesn't matter, just that the key exists
         "techpioneers": true,
         "womentechmakers": true
      }
    },
    ...
  },
  "groups": {
    "techpioneers": {
      "name": "Historical Tech Pioneers",
      "members": {
        "alovelace": true,
        "ghopper": true,
        "eclarke": true
      }
    },
    ...
  }
}

But I can't figure out how to select users who are members of the same set of groups

Body:
You'd have to define an additional group_combinations or all_groups index, where you store each user under their combines the groups:

all_groups: {
  "techpioneers_womentechmakers": {
    alovelace: true
  }
}


问:
Add value to Hashtable using lambda
Fist of all, I'm pretty new to Java my approach to the problem might not be optimal.

I have some lists of strings, say {"a", "b", "e", "g"} and {"no", "a", "g", "great"}, which contain 4 items each from a set of values.

I want to create a Hashtable of that set, assigning an int value to each String. For a specific String, I want to use a lambda expression to assign different values to it based on the other items in the list it's contained in, something like:

```<code>class bla {
    static Map stuff;
    static {
        // If I write it like this, I get the error "Cannot resolve method ContainsAll"
         stuff.put("g", (aList) -> (aList.containsAll(Arrays.asList("a", "b", "e", "g")) ? 1 : 2));
    }
}
</code>```

If I add a List<String> to (aList) like so, (List <String> aList) then I get, a "Target type of a lambda expression must be an interface" error.

If I replace () with {} for the lambda body, I get the "; expected error".

How can I write this to work? Or, do you have a better idea?

答:
I found my mistake.. finally. I know the code I posted was more of a idea of i wanted and i was focused on this line:

```<code>stuff.put("g", (aList) -> (aList.containsAll(Arrays.asList("a", "b", "e", "g")) ? 1 : 2));
</code>```

I realized the HashMap needs to be defined as Map(String, InterfaceName) and not (String, Integer):

```<code>interface Something{
    int doStuff(List<String> blabla);
}

class bla{
    static Map<String, Something> stuff;
    static{
        stuff = new HashMap<>();
        stuff.put("a", (List<String> aList) -> 30);
        stuff.put("g", (List<String> aList) -> aList.containsAll(Arrays.asList("a", "b", "e", "g")) ? 10 : 25); // I only need this for a few of the strings
    }
}
</code>```

Title: Add value to Hashtable using lambda

Body:
Fist of all, I'm pretty new to Java my approach to the problem might not be optimal.

I have some lists of strings, say {"a", "b", "e", "g"} and {"no", "a", "g", "great"}, which contain 4 items each from a set of values.

I want to create a Hashtable of that set, assigning an int value to each String. For a specific String, I want to use a lambda expression to assign different values to it based on the other items in the list it's contained in, something like:

class bla {
    static Map stuff;
    static {
        // If I write it like this, I get the error "Cannot resolve method ContainsAll"
         stuff.put("g", (aList) -> (aList.containsAll(Arrays.asList("a", "b", "e", "g")) ? 1 : 2));
    }
}

If I add a List<String> to (aList) like so, (List <String> aList) then I get, a "Target type of a lambda expression must be an interface" error.

If I replace () with {} for the lambda body, I get the "; expected error".

How can I write this to work? Or, do you have a better idea?

Body:
I found my mistake.. finally. I know the code I posted was more of a idea of i wanted and i was focused on this line:

stuff.put("g", (aList) -> (aList.containsAll(Arrays.asList("a", "b", "e", "g")) ? 1 : 2));

I realized the HashMap needs to be defined as Map(String, InterfaceName) and not (String, Integer):

interface Something{
    int doStuff(List<String> blabla);
}

class bla{
    static Map<String, Something> stuff;
    static{
        stuff = new HashMap<>();
        stuff.put("a", (List<String> aList) -> 30);
        stuff.put("g", (List<String> aList) -> aList.containsAll(Arrays.asList("a", "b", "e", "g")) ? 10 : 25); // I only need this for a few of the strings
    }
}


问:
Python - Abstract class subclassing
I'm trying to find the best for users of my python library to implement an abstract class I wrote.
Namely, my abstract class define an API to access specific values stored in a database, but I would like to let the user choose how to store it (simple text file, json, sqlite, etc.)

My problem is, how should I retrieve the class the user create and use it in my library ?

This is the solution I came up with, but I don't find it very graceful and wonder if there is a more pythonic way.

In my library:

```<code>from abc import ABC, abstractmethod

class Database(ABC):

    @abstractmethod
    def get(self, index):
        pass

    @abstractmethod
    def insert(self, data):
        pass

def get_database():
    """call this anywhere I need a concrete database class"""
    return Database.__subclasses__()[-1]
</code>```

In the user code

```<code>class SqliteDatabase(Database):

    def get(self, index):
        # sqlite SELECT and such
        return data

    def insert(self, data):
        # sqlite INSERT INTO
        # return data with index provided
        return data
</code>```

Of course, I will return a better error than IndexError if there is no subclass defined, but you get the idea.

Thank you in advance !

答:
I finally settled for something else, as Blorgbeard suggested

```<code>_databases = {}

def register(dbname="default"):
    def wrapper(klass):
        _databases[dbname] = klass
        return klass
    return wrapper

def get_db(name="default"):
    return _databases[name]
</code>```

And the user only needs to declare

```<code>@register()
class SqliteDatabase:

    def __get__(self, index):
        # retrieve data
        if data is None:
            raise KeyError(index)
        return data
</code>```

This way, anybody can declare as many as databases as they want.
If you have improvements over this version, I'll gladly take them.

Title: Python - Abstract class subclassing

Body:
I'm trying to find the best for users of my python library to implement an abstract class I wrote.
Namely, my abstract class define an API to access specific values stored in a database, but I would like to let the user choose how to store it (simple text file, json, sqlite, etc.)

My problem is, how should I retrieve the class the user create and use it in my library ?

This is the solution I came up with, but I don't find it very graceful and wonder if there is a more pythonic way.

In my library:

from abc import ABC, abstractmethod

class Database(ABC):

    @abstractmethod
    def get(self, index):
        pass

    @abstractmethod
    def insert(self, data):
        pass

def get_database():
    """call this anywhere I need a concrete database class"""
    return Database.__subclasses__()[-1]

In the user code

class SqliteDatabase(Database):

    def get(self, index):
        # sqlite SELECT and such
        return data

    def insert(self, data):
        # sqlite INSERT INTO
        # return data with index provided
        return data

Of course, I will return a better error than IndexError if there is no subclass defined, but you get the idea.

Thank you in advance !

Body:
I finally settled for something else, as Blorgbeard suggested

_databases = {}

def register(dbname="default"):
    def wrapper(klass):
        _databases[dbname] = klass
        return klass
    return wrapper

def get_db(name="default"):
    return _databases[name]

And the user only needs to declare

@register()
class SqliteDatabase:

    def __get__(self, index):
        # retrieve data
        if data is None:
            raise KeyError(index)
        return data

This way, anybody can declare as many as databases as they want.
If you have improvements over this version, I'll gladly take them.


问:
Convert Java to C# with a tool, or manually?
I have a Java project which I'd like to convert to C#, and after looking here and elsewhere found out about a tool, Sharpen.

However, in order to get it up and running (I'm new to Java) the site linked above describes grabbing the source and building it as a plugin to the Eclipse IDE, which I'd rather not do since I don't ordinarily do Java.

Does anyone know whether a standalone EXE exists which can simply utilize Sharpen to take a given Java project and run it through the wringer to convert it to C#? Or are Java and C# similar enough that it should be pretty straightforward to just port the code over to .NET manually?

答: There's no one-to-one conversion (or even close), so you should really do it manually. However, if you need a decent, automated piece of software, either as a starting point or as a rough converter, see this link.</p>


问:
How to Configure SSL for Amazon S3 bucket
I am using an Amazon S3 bucket for uploading and downloading of data using my .NET application. Now my question is: I want to access my S3 bucket using SSL. Is it possible to implement SSL for an Amazon s3 bucket?</p>

答:
As mentioned before, you cannot create free certificates for S3 buckets. However, you can create Cloud Front distribution and then assign the certificate for the Cloud Front instead. You request the certificate for your domain and then just assign it to the Cloud Front distribution in the Cloud Front settings. I've used this method to serve static websites via SSL as well as serve static files.

For static website creation Amazon is the go to place. It is really affordable to get a static website with SSL.


问:
dsacls - Invalid DN Syntax in powershell
I am trying to modify the servicePrincipalName permission within powershell script using the 'dsacls' command.

I am taking all the dynamic parameter as script arguments.

The script is not working when I form a command with the arguments variable I received. There is something I am missing with string manipulation.

```<code> $perStr ='"' + $strDN + '"' + ' /G ' + $DomainNetBIOSName + '\' + $SQLUser + ':RPWP;"servicePrincipalName"'

  $ret = dsacls ${perStr}
</code>```

The above gives an error:

```<code>Invalid DN Syntax
</code>```

When I run with hardcoded values it runs fine.

答:
When I have a hard time constructing strings to use with external executables I tend to build the entire command and then use Invoke-Expression to run it. Something like this:

```<code>$perStr = '& dsacls --% "{0}" /G {1}\{2}:RPWP;"servicePrincipalName"' -f $strDN, $DomainNetBIOSName, $SQLUser
$ret = Invoke-Expression -Command $perStr
</code>```

The --% will tell it to stop interpreting things beyond that point so it will take all arguments exactly as typed and pass them to the command. See if that works for you, and if not you may want to look at the content of $perStr to make sure that it looks right to you.

Body:
I am trying to modify the servicePrincipalName permission within powershell script using the 'dsacls' command.

I am taking all the dynamic parameter as script arguments.

The script is not working when I form a command with the arguments variable I received. There is something I am missing with string manipulation.

 $perStr ='"' + $strDN + '"' + ' /G ' + $DomainNetBIOSName + '\' + $SQLUser + ':RPWP;"servicePrincipalName"'

  $ret = dsacls ${perStr}

The above gives an error:

Invalid DN Syntax

When I run with hardcoded values it runs fine.

Body:
When I have a hard time constructing strings to use with external executables I tend to build the entire command and then use Invoke-Expression to run it. Something like this:

$perStr = '& dsacls --% "{0}" /G {1}\{2}:RPWP;"servicePrincipalName"' -f $strDN, $DomainNetBIOSName, $SQLUser
$ret = Invoke-Expression -Command $perStr

The --% will tell it to stop interpreting things beyond that point so it will take all arguments exactly as typed and pass them to the command. See if that works for you, and if not you may want to look at the content of $perStr to make sure that it looks right to you.


问:
DateTime Round Up and Down
Ive been looking for a proper rounding mechanism but nothing I find seems to be exactly what I need.

I need to round up and round down seperately and I also need to account for the the case when its already rounded.

I need the following rounding to happen

```<code>5:00 -> RoundDown() -> 5:00
5:04 -> RoundDown() -> 5:00
5:09 -> RoundDown() -> 5:00
5:10 -> RoundDown() -> 5:10

4:00 -> RoundUp() -> 4:00
4:50 -> RoundUp() -> 4:50
4:51 -> RoundUp() -> 5:00
4:56 -> RoundUp() -> 5:00
</code>```

Basically I need it to RoundUp() or RoundDown() to the nearest 10 minutes explicitly but it should also leave time untouched if it already is in a multiple of 10 minutes. Also I'd like to truncate any seconds to that they have no effect on the rounding procedure

4:50:45 -> 4:50:00 -> RoundUp() -> 4:50

Does anyone have any handy code to accomplish this.

I found this code somewhere but it rounds 5:00 -> RoundUp() -> 5:10 rather than leaving it intact because its already a multiple of 10 and needs no rounding. Also Im not sure how seconds would effect it

```<code>public static DateTime RoundDateTime(this DateTime dt, int minutes, RoundingDirection direction)
{
    TimeSpan t;
    switch (direction)
    {
        case RoundingDirection.Up:
            t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes, 0)); break;
        case RoundingDirection.Down:
            t = (dt.Subtract(DateTime.MinValue)); break;
        default:
            t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes / 2, 0)); break;
    }
    return DateTime.MinValue.Add(new TimeSpan(0,
           (((int)t.TotalMinutes) / minutes) * minutes, 0));
}
</code>```

Hope someone can edit that method to make it work for me. Thanks

答:
This function will round up or down to the nearest interval (minutes).</p>

```<code>    private static DateTime NormalizeReadingInterval(DateTime originalTime, int interval)
    {
        if (originalTime.Minute % interval == 0) return originalTime;
        var epochTime = new DateTime(1900, 1, 1);
        var minutes = (originalTime - epochTime).TotalMinutes;
        var numIntervals = minutes / interval;
        var roundedNumIntervals = Math.Round(numIntervals, 0);
        return epochTime.AddMinutes(roundedNumIntervals * interval);
    }
</code>```

Title: DateTime Round Up and Down

Body:
Ive been looking for a proper rounding mechanism but nothing I find seems to be exactly what I need.

I need to round up and round down seperately and I also need to account for the the case when its already rounded.

I need the following rounding to happen

5:00 -> RoundDown() -> 5:00
5:04 -> RoundDown() -> 5:00
5:09 -> RoundDown() -> 5:00
5:10 -> RoundDown() -> 5:10

4:00 -> RoundUp() -> 4:00
4:50 -> RoundUp() -> 4:50
4:51 -> RoundUp() -> 5:00
4:56 -> RoundUp() -> 5:00

Basically I need it to RoundUp() or RoundDown() to the nearest 10 minutes explicitly but it should also leave time untouched if it already is in a multiple of 10 minutes. Also I'd like to truncate any seconds to that they have no effect on the rounding procedure

4:50:45 -> 4:50:00 -> RoundUp() -> 4:50

Does anyone have any handy code to accomplish this.

I found this code somewhere but it rounds 5:00 -> RoundUp() -> 5:10 rather than leaving it intact because its already a multiple of 10 and needs no rounding. Also Im not sure how seconds would effect it

public static DateTime RoundDateTime(this DateTime dt, int minutes, RoundingDirection direction)
{
    TimeSpan t;
    switch (direction)
    {
        case RoundingDirection.Up:
            t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes, 0)); break;
        case RoundingDirection.Down:
            t = (dt.Subtract(DateTime.MinValue)); break;
        default:
            t = (dt.Subtract(DateTime.MinValue)).Add(new TimeSpan(0, minutes / 2, 0)); break;
    }
    return DateTime.MinValue.Add(new TimeSpan(0,
           (((int)t.TotalMinutes) / minutes) * minutes, 0));
}

Hope someone can edit that method to make it work for me. Thanks

Body:
This function will round up or down to the nearest interval (minutes).

    private static DateTime NormalizeReadingInterval(DateTime originalTime, int interval)
    {
        if (originalTime.Minute % interval == 0) return originalTime;
        var epochTime = new DateTime(1900, 1, 1);
        var minutes = (originalTime - epochTime).TotalMinutes;
        var numIntervals = minutes / interval;
        var roundedNumIntervals = Math.Round(numIntervals, 0);
        return epochTime.AddMinutes(roundedNumIntervals * interval);
    }


问:
MongoDB: Query elements of an array of objects nested in a collection property
I have a Mongo DB database set up with the following collection, Races:

```<code>[
    {
        "_id": "5a24b47f8b8498252a0a0ef9",
        "year": 2017,
        "runners": [
            {
                "Place": "1",
                "Div/Tot": "1/126",
                "FName": "XXXX",
                "LName": "XXXX",
                "Num": "XXXX",
                "S": "M",
                "Ag": "25",
                "City": "XXXX",
                "St": "XX",
                "Gun-Time": "32:15.2",
                "Net-Time": "32:14.91",
                "Pace": "5:13"
            },
            {
                "Place": "2",
                "Div/Tot": "1/138",
                "FName": "XXXX",
                "LName": "XXXX",
                "Num": "XXXX",
                "S": "M",
                "Ag": "34",
                "City": "XXXX",
                "St": "XXXX",
                "Gun-Time": "MD",
                "Net-Time": "32:19.0",
                "Pace": "32:18.78"
            },
        ....
</code>```

I am trying to query by year to bring up the right element of the collection, and then query within the element's "runners" array based on input criteria.  So far I have not been able to direct the query into this array.  The goal is to derive members of an array of objects held within an element of a collection.

I looked at the syntax for mongo DB's $in and $all operators but I have not been able to construct a query that matches against the properties of the objects in the array.

I am using Node and this is the end-point I have tried to adapt;

```<code>router.route( '/race/:year' )
  .get( ( req, res ) => {
      console.log( 'query', req.query, ' params ', req.params );
      Race.find( { year: req.params.year }, {runners: {$elemMatch: req.query } } )
      .then( race => {
          return res.json( race );
      } )
      .catch( () => res.status( 500 ).send( 'endpoint error..........' ) );
});
</code>```

The problem with this query is that it only returns the first array element that matches req.query, not all of the values that do.

Is there a concise way to construct a query into the objects of the array that returns all of the matches?  Thank you for your time.

答:
This should get you started:</p>

```<code>Race.aggregate([
{
    $match: {
        "year": req.params.year // filter out all documents that we're not interested in
    }
}, {
    $project: {
        _id: 0
        "runners": {
            $filter: {
                input: "$runners", // we want to filter the "runners" array
                as: "runner",
                cond: {
                    $eq: [ "$$runner.Ag", "34" ] // just an example filter
                }
            }
        }
    }
}], function(err, results) {
      rs.json(results);
});
</code>```

Body:
I have a Mongo DB database set up with the following collection, Races:

[
    {
        "_id": "5a24b47f8b8498252a0a0ef9",
        "year": 2017,
        "runners": [
            {
                "Place": "1",
                "Div/Tot": "1/126",
                "FName": "XXXX",
                "LName": "XXXX",
                "Num": "XXXX",
                "S": "M",
                "Ag": "25",
                "City": "XXXX",
                "St": "XX",
                "Gun-Time": "32:15.2",
                "Net-Time": "32:14.91",
                "Pace": "5:13"
            },
            {
                "Place": "2",
                "Div/Tot": "1/138",
                "FName": "XXXX",
                "LName": "XXXX",
                "Num": "XXXX",
                "S": "M",
                "Ag": "34",
                "City": "XXXX",
                "St": "XXXX",
                "Gun-Time": "MD",
                "Net-Time": "32:19.0",
                "Pace": "32:18.78"
            },
        ....

I am trying to query by year to bring up the right element of the collection, and then query within the element's "runners" array based on input criteria.  So far I have not been able to direct the query into this array.  The goal is to derive members of an array of objects held within an element of a collection.

I looked at the syntax for mongo DB's $in and $all operators but I have not been able to construct a query that matches against the properties of the objects in the array.

I am using Node and this is the end-point I have tried to adapt;

router.route( '/race/:year' )
  .get( ( req, res ) => {
      console.log( 'query', req.query, ' params ', req.params );
      Race.find( { year: req.params.year }, {runners: {$elemMatch: req.query } } )
      .then( race => {
          return res.json( race );
      } )
      .catch( () => res.status( 500 ).send( 'endpoint error..........' ) );
});

The problem with this query is that it only returns the first array element that matches req.query, not all of the values that do.

Is there a concise way to construct a query into the objects of the array that returns all of the matches?  Thank you for your time.

Body:
This should get you started:

Race.aggregate([
{
    $match: {
        "year": req.params.year // filter out all documents that we're not interested in
    }
}, {
    $project: {
        _id: 0
        "runners": {
            $filter: {
                input: "$runners", // we want to filter the "runners" array
                as: "runner",
                cond: {
                    $eq: [ "$$runner.Ag", "34" ] // just an example filter
                }
            }
        }
    }
}], function(err, results) {
      rs.json(results);
});


问:
Variadic-templates class constructor
I wrote the following code to create a class with a constructor that takes as arguments a variable number (N) of integer plus two double, as follow:

```<code>#include <cstdio>
#include <cstdlib>

#include <vector>
#include <array>

template <std::size_t N>
class point_t {

public:

  std::vector<int> values;

  template<typename ... Args>
  point_t(Args ... args, double distance, double value) {

    std::array<int , N> list = {(args)...};

    for(std::size_t i=0; i<N; ++i) values[i] = list[i];

  }

};

int main(int argc, char *argv[]) {

  point_t<4> test(1, 2, 3, 4, 3.0, 6.7);

  return 0;

}
</code>```

The compiler return the following error:

No matching constructor for initialization of 'point_t<4>'

  Candidate constructor not viable: requires 2 arguments, but 6 were provided

What am I'm missing?

答:
What I'm missing?

That a variadic pack can be deduced only if it's in the last position.

So

```<code>template<typename ... Args>
point_t(double distance, double value, Args... args)
</code>```

works and

```<code>template<typename ... Args>
point_t(Args ... args, double distance, double value) {
</code>```

doesn't.

Title: Variadic-templates class constructor

Body:
I wrote the following code to create a class with a constructor that takes as arguments a variable number (N) of integer plus two double, as follow:

#include <cstdio>
#include <cstdlib>

#include <vector>
#include <array>

template <std::size_t N>
class point_t {

public:

  std::vector<int> values;

  template<typename ... Args>
  point_t(Args ... args, double distance, double value) {

    std::array<int , N> list = {(args)...};

    for(std::size_t i=0; i<N; ++i) values[i] = list[i];

  }

};

int main(int argc, char *argv[]) {

  point_t<4> test(1, 2, 3, 4, 3.0, 6.7);

  return 0;

}

The compiler return the following error:

No matching constructor for initialization of 'point_t<4>'

  Candidate constructor not viable: requires 2 arguments, but 6 were provided

What am I'm missing?

Body:
What I'm missing?

That a variadic pack can be deduced only if it's in the last position.

So

template<typename ... Args>
point_t(double distance, double value, Args... args)

works and

template<typename ... Args>
point_t(Args ... args, double distance, double value) {

doesn't.


问:
Error:An entity object cannot be referenced by multiple instances of IEntityChangeTracker
So, I am just about at my wits end here.  I am an experienced programmer and SQL user but new to Entity Framework.  (Using VS Pro 2015, EF 6)

This is my first post here, forgive me if I don't have all the protocols down yet.

I am getting the error “An entity object cannot be referenced by multiple instances of IEntityChangeTracker” when trying to attach an entity object to a Database context.  I understand what the error means: My object is already attached to a context.  What I don’t understand is why/how my object is still attached to a database context.

The object in question is fetched via a method call on an owning object:

```<code>ActiveWorkSession = tcUser.getActiveWorkSession();
</code>```

Here is the getActiveWorkSession method:

```<code>public EmployeeWorkSession getActiveWorkSession()
{
    EmployeeWorkSession activeWS = null;

    using (PHSRP_DashboardDataModel _DBC = new PHSRP_DashboardDataModel())
    {
        var ews = _DBC.EmployeeWorkSessions
                      .Where(w => (w.EmployeeID == this.EmployeeRecord.EmployeeID) &&
                                  (w.WorkEndDateTime_Actual == null))
                      .Include(w => w.WorkStartRecords)
                      .Include(w => w.WorkEndRecords)
                      .Include(w => w.WorkSessionBreaks);

        if (ews.Count() > 0)
        {
            activeWS = ews.First();
            if (ews.Count() > 1)
            {
                activeWS = ews.Last();
            }
        }
    }

    return activeWS;
}
</code>```

You see that, in addition to being a local scope object, the DbContext (_DBC) is disposed of by the using statement before the method returns.
So when later, I need to attach this ActveWorkSession to a DbContext again (since I disposed of its original context!) I first tried this:

```<code>private void btn_UndoButton_Click(object sender, EventArgs e)
{
        |
        |
         //  Various condition tests
        |
        |

    tcPunch lPunch = tcLastPunchUndo.LastPunch;

    PHSRP_DashboardDataModel _DBC = new PHSRP_DashboardDataModel();
    _DBC.EmployeeWorkSessions.Attach(ActiveWorkSession);
                          //  Blows up here   ^
    switch (lPunch.Type)
    {
        Cases with try-catch
    }
}
</code>```

This gives me the "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" at the Attach statement.

Since apparently, in some cases, I was still attached to a DbContext I decided to use that context:

```<code>private void btn_UndoButton_Click(object sender, EventArgs e)
{
        |
        |
        //  Various condition tests
        |
        |

     tcPunch lPunch = tcLastPunchUndo.LastPunch;

     PHSRP_DashboardDataModel _DBC;

     if (GetDbContextFromEntity(ActiveWorkSession)!=null)    // is ActiveWorkSession still attached to a Dbcontext ?
     {
         _DBC = (PHSRP_DashboardDataModel) GetDbContextFromEntity(ActiveWorkSession);        //  Get that Context
         // Blows up here ^
     }
     else
     {
         _DBC = new PHSRP_DashboardDataModel();        // Open new context and attach
         _DBC.EmployeeWorkSessions.Attach(ActiveWorkSession);
     }

     switch (lPunch.Type)
     {
        //  Cases with try-catch
     }
}
</code>```

The GetDbContextFromEntity code is from a StackOverflow answer

This of course gives me an InvaildCastException: "Unable to cast object of type 'System.Data.Entity.DbContext' to type 'PHSRP_Dashboard.PHSRP_DashboardDataModel'." when I attempt to cast the base type of DbContext to my derived type of PHSRP_DashboardDataModel.  I’m aware that that was wishful thinking on my part.

So I am looking for a solution.  I’m flexible. A way to disconnect the ActiveWorkSession from its existing dbcontext, or a way to get a proper handle on that existing context, or some other option I haven’t seen yet.

My thanks.

Modifying my query (as suggested by Frank) to:

```<code>var ews = _DBC.EmployeeWorkSessions
              .Where(w => (w.EmployeeID == this.EmployeeRecord.EmployeeID) &&
                          (w.WorkEndDateTime_Actual == null))
              .Include(w => w.WorkStartRecords)
              .Include(w => w.WorkEndRecords)
              .Include(w => w.WorkSessionBreaks)
              .AsNoTracking();
</code>```

did not resolve the problem- Same error

答:
I found two solutions:

The first was to use the exiting DbContext without casting:

This requires additional infrastructure to use a gereral DbContext instance or a specific  PHSRP_DashboardDataModel based on the entity state

I don’t like it since it does not explain or correct the underlying problem, but it works.

```<code>PHSRP_DashboardDataModel _DBC = null;
DbContext _PDBC = null;
Boolean existingContext;

if (GetDbContextFromEntity(ActiveWorkSession)!=null)    // is ActiveWorkSession still attached to a Dbcontext ?
{
    _PDBC = GetDbContextFromEntity(ActiveWorkSession);        //  Get that Context
    existingContext = true;
}
else
{
    _DBC = new PHSRP_DashboardDataModel();             // Open new Context and attach
    _DBC.EmployeeWorkSessions.Attach(ActiveWorkSession);
    existingContext = false;
}

switch (lPunch.Type)
{
     case PunchType.OutForShift:
     {
        // Remove END punch, set SessionEnd time to null
        try
        {
            WorkEndRecord wsr = ActiveWorkSession.WorkEndRecords.First();

            if (existingContext)
            {
                ActiveWorkSession.WorkEndRecords.Remove(wsr);
                ActiveWorkSession.WorkEndDateTime_Actual = null;
                _PDBC.SaveChanges();
            }
            else
            {
               _DBC.WorkEndRecords.Remove(wsr);
               ActiveWorkSession.WorkEndDateTime_Actual = null;
              _DBC.SaveChanges();
            }

        }
        catch (Exception ex)
        {
             //  handle exception
        }

        tcUser.UpdateClockState();
        UpdateClockView();

        break;
     }

         |
         |
     Other cases
         |
         |
}
</code>```

Frank Fajardo’s question sent me looking for other references to the Database Context, and ultimately the second, better solution.

The task that this code is “undoing” is a clock-out.  That’s where I found my prior, still attached, reference to ActiveWorkSession.

My reference to the Database context in the SessionClockOut method was not enclosed in a “using” block.  As a test, I added a detach instruction- that worked.  I then placed the _DBC in a “using” block.  That allowed my original btn_UndoButton_Click code to work without needing to detach the ActiveWorkSession object from the Context:

```<code>private Boolean SessionClockOut(DateTime timeOUT)
{
    Boolean success = false;
    Boolean abort = false;

    tcPunch newPunch = new tcPunch();

 // Added 'using' statement
    using (PHSRP_DashboardDataModel _DBC = new PHSRP_DashboardDataModel())
    {
        while (!success && !abort)
        {
            var wsUpdate = _DBC.EmployeeWorkSessions
                               .Where(w => (w.EmployeeWorkSessionID == ActiveWorkSession.EmployeeWorkSessionID))
                               .Include(w => w.WorkStartRecords)
                               .Include(w => w.WorkEndRecords)
                               .Include(w => w.WorkSessionBreaks)
                               .FirstOrDefault();

            if (wsUpdate != null)
            {
                WorkEndRecord er = new WorkEndRecord();

                try
                {
                    wsUpdate.WorkEndDateTime_Actual = timeOUT;

                    er.EmployeeWorkSessionID = ActiveWorkSession.EmployeeWorkSessionID;
                    er.EditTimeStamp = DateTime.Now;
                    er.WorkEndDateTime_Official = timeOUT;
                    er.VarianceReasonID = VarianceReason.VR_None;
                    er.EditByID = ActiveWorkSession.EmployeeID;

                    wsUpdate.WorkEndRecords.Add(er);
                    _DBC.SaveChanges();

                    ActiveWorkSession = wsUpdate;
                    tcUser.UpdateClockState();
                        UpdateClockView();

        //  Tried this before adding the using statement. It also worked.
        //          _DBC.Entry(ActiveWorkSession).State = EntityState.Detached;         // Release from DB Context
                    PreviousWorkSession = ActiveWorkSession;                            // needed For Undo Punch
                    ActiveWorkSession = null;                                           // Worksession has ended
                    success = true;

                }
                catch (DbUpdateException e)
                {
                   //  handle exception...
                    abort = true;
                    throw;
                }

                newPunch.EmployeeID = wsUpdate.EmployeeID;
                newPunch.WorksessionID = wsUpdate.EmployeeWorkSessionID;
                newPunch.Type = PunchType.OutForShift;
                newPunch.TimeStamp = er.EditTimeStamp;
                if (tcUser.hasPriv(PrivilegeTokenValue.TC_UndoRecentPunch)) tcLastPunchUndo.StartUndoTimer(newPunch);
            }  // if
        }  //  while

    }  // using

    return success;
}
</code>```

Being new to Entity Framework I don't yet understand all the issues related to working with the DbContext.

Body:
So, I am just about at my wits end here.  I am an experienced programmer and SQL user but new to Entity Framework.  (Using VS Pro 2015, EF 6)

This is my first post here, forgive me if I don't have all the protocols down yet.

I am getting the error “An entity object cannot be referenced by multiple instances of IEntityChangeTracker” when trying to attach an entity object to a Database context.  I understand what the error means: My object is already attached to a context.  What I don’t understand is why/how my object is still attached to a database context.

The object in question is fetched via a method call on an owning object:

ActiveWorkSession = tcUser.getActiveWorkSession();

Here is the getActiveWorkSession method:

public EmployeeWorkSession getActiveWorkSession()
{
    EmployeeWorkSession activeWS = null;

    using (PHSRP_DashboardDataModel _DBC = new PHSRP_DashboardDataModel())
    {
        var ews = _DBC.EmployeeWorkSessions
                      .Where(w => (w.EmployeeID == this.EmployeeRecord.EmployeeID) &&
                                  (w.WorkEndDateTime_Actual == null))
                      .Include(w => w.WorkStartRecords)
                      .Include(w => w.WorkEndRecords)
                      .Include(w => w.WorkSessionBreaks);

        if (ews.Count() > 0)
        {
            activeWS = ews.First();
            if (ews.Count() > 1)
            {
                activeWS = ews.Last();
            }
        }
    }

    return activeWS;
}

You see that, in addition to being a local scope object, the DbContext (_DBC) is disposed of by the using statement before the method returns.
So when later, I need to attach this ActveWorkSession to a DbContext again (since I disposed of its original context!) I first tried this:

private void btn_UndoButton_Click(object sender, EventArgs e)
{
        |
        |
         //  Various condition tests
        |
        |

    tcPunch lPunch = tcLastPunchUndo.LastPunch;

    PHSRP_DashboardDataModel _DBC = new PHSRP_DashboardDataModel();
    _DBC.EmployeeWorkSessions.Attach(ActiveWorkSession);
                          //  Blows up here   ^
    switch (lPunch.Type)
    {
        Cases with try-catch
    }
}

This gives me the "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" at the Attach statement.

Since apparently, in some cases, I was still attached to a DbContext I decided to use that context:

private void btn_UndoButton_Click(object sender, EventArgs e)
{
        |
        |
        //  Various condition tests
        |
        |

     tcPunch lPunch = tcLastPunchUndo.LastPunch;

     PHSRP_DashboardDataModel _DBC;

     if (GetDbContextFromEntity(ActiveWorkSession)!=null)    // is ActiveWorkSession still attached to a Dbcontext ?
     {
         _DBC = (PHSRP_DashboardDataModel) GetDbContextFromEntity(ActiveWorkSession);        //  Get that Context
         // Blows up here ^
     }
     else
     {
         _DBC = new PHSRP_DashboardDataModel();        // Open new context and attach
         _DBC.EmployeeWorkSessions.Attach(ActiveWorkSession);
     }

     switch (lPunch.Type)
     {
        //  Cases with try-catch
     }
}

The GetDbContextFromEntity code is from a StackOverflow answer

This of course gives me an InvaildCastException: "Unable to cast object of type 'System.Data.Entity.DbContext' to type 'PHSRP_Dashboard.PHSRP_DashboardDataModel'." when I attempt to cast the base type of DbContext to my derived type of PHSRP_DashboardDataModel.  I’m aware that that was wishful thinking on my part.

So I am looking for a solution.  I’m flexible. A way to disconnect the ActiveWorkSession from its existing dbcontext, or a way to get a proper handle on that existing context, or some other option I haven’t seen yet.

My thanks.

Modifying my query (as suggested by Frank) to:

var ews = _DBC.EmployeeWorkSessions
              .Where(w => (w.EmployeeID == this.EmployeeRecord.EmployeeID) &&
                          (w.WorkEndDateTime_Actual == null))
              .Include(w => w.WorkStartRecords)
              .Include(w => w.WorkEndRecords)
              .Include(w => w.WorkSessionBreaks)
              .AsNoTracking();

did not resolve the problem- Same error

Body:
I found two solutions:

The first was to use the exiting DbContext without casting:

This requires additional infrastructure to use a gereral DbContext instance or a specific  PHSRP_DashboardDataModel based on the entity state

I don’t like it since it does not explain or correct the underlying problem, but it works.

PHSRP_DashboardDataModel _DBC = null;
DbContext _PDBC = null;
Boolean existingContext;

if (GetDbContextFromEntity(ActiveWorkSession)!=null)    // is ActiveWorkSession still attached to a Dbcontext ?
{
    _PDBC = GetDbContextFromEntity(ActiveWorkSession);        //  Get that Context
    existingContext = true;
}
else
{
    _DBC = new PHSRP_DashboardDataModel();             // Open new Context and attach
    _DBC.EmployeeWorkSessions.Attach(ActiveWorkSession);
    existingContext = false;
}

switch (lPunch.Type)
{
     case PunchType.OutForShift:
     {
        // Remove END punch, set SessionEnd time to null
        try
        {
            WorkEndRecord wsr = ActiveWorkSession.WorkEndRecords.First();

            if (existingContext)
            {
                ActiveWorkSession.WorkEndRecords.Remove(wsr);
                ActiveWorkSession.WorkEndDateTime_Actual = null;
                _PDBC.SaveChanges();
            }
            else
            {
               _DBC.WorkEndRecords.Remove(wsr);
               ActiveWorkSession.WorkEndDateTime_Actual = null;
              _DBC.SaveChanges();
            }

        }
        catch (Exception ex)
        {
             //  handle exception
        }

        tcUser.UpdateClockState();
        UpdateClockView();

        break;
     }

         |
         |
     Other cases
         |
         |
}

Frank Fajardo’s question sent me looking for other references to the Database Context, and ultimately the second, better solution.

The task that this code is “undoing” is a clock-out.  That’s where I found my prior, still attached, reference to ActiveWorkSession.

My reference to the Database context in the SessionClockOut method was not enclosed in a “using” block.  As a test, I added a detach instruction- that worked.  I then placed the _DBC in a “using” block.  That allowed my original btn_UndoButton_Click code to work without needing to detach the ActiveWorkSession object from the Context:

private Boolean SessionClockOut(DateTime timeOUT)
{
    Boolean success = false;
    Boolean abort = false;

    tcPunch newPunch = new tcPunch();

 // Added 'using' statement
    using (PHSRP_DashboardDataModel _DBC = new PHSRP_DashboardDataModel())
    {
        while (!success && !abort)
        {
            var wsUpdate = _DBC.EmployeeWorkSessions
                               .Where(w => (w.EmployeeWorkSessionID == ActiveWorkSession.EmployeeWorkSessionID))
                               .Include(w => w.WorkStartRecords)
                               .Include(w => w.WorkEndRecords)
                               .Include(w => w.WorkSessionBreaks)
                               .FirstOrDefault();

            if (wsUpdate != null)
            {
                WorkEndRecord er = new WorkEndRecord();

                try
                {
                    wsUpdate.WorkEndDateTime_Actual = timeOUT;

                    er.EmployeeWorkSessionID = ActiveWorkSession.EmployeeWorkSessionID;
                    er.EditTimeStamp = DateTime.Now;
                    er.WorkEndDateTime_Official = timeOUT;
                    er.VarianceReasonID = VarianceReason.VR_None;
                    er.EditByID = ActiveWorkSession.EmployeeID;

                    wsUpdate.WorkEndRecords.Add(er);
                    _DBC.SaveChanges();

                    ActiveWorkSession = wsUpdate;
                    tcUser.UpdateClockState();
                        UpdateClockView();

        //  Tried this before adding the using statement. It also worked.
        //          _DBC.Entry(ActiveWorkSession).State = EntityState.Detached;         // Release from DB Context
                    PreviousWorkSession = ActiveWorkSession;                            // needed For Undo Punch
                    ActiveWorkSession = null;                                           // Worksession has ended
                    success = true;

                }
                catch (DbUpdateException e)
                {
                   //  handle exception...
                    abort = true;
                    throw;
                }

                newPunch.EmployeeID = wsUpdate.EmployeeID;
                newPunch.WorksessionID = wsUpdate.EmployeeWorkSessionID;
                newPunch.Type = PunchType.OutForShift;
                newPunch.TimeStamp = er.EditTimeStamp;
                if (tcUser.hasPriv(PrivilegeTokenValue.TC_UndoRecentPunch)) tcLastPunchUndo.StartUndoTimer(newPunch);
            }  // if
        }  //  while

    }  // using

    return success;
}

Being new to Entity Framework I don't yet understand all the issues related to working with the DbContext.


问:
GPU Emulator for CUDA programming without the hardware
Question: Is there an emulator for a Geforce card that would allow me to program and test CUDA without having the actual hardware?

Info:

I'm looking to speed up a few simulations of mine in CUDA, but my problem is that I'm not always around my desktop for doing this development. I would like to do some work on my netbook instead, but my netbook doesn't have a GPU. Now as far as I know, you need a CUDA capable GPU to run CUDA. Is there a way to get around this? It would seem like the only way is a GPU emulator (which obviously would be painfully slow, but would work). But whatever way there is to do this I would like to hear.

I'm programming on Ubuntu 10.04 LTS.

答:
This response may be too late, but it's worth noting anyway. GPU Ocelot (of which I am one of the core contributors) can be compiled without CUDA device drivers (libcuda.so) installed if you wish to use the Emulator or LLVM backends. I've demonstrated the emulator on systems without NVIDIA GPUs.

The emulator attempts to faithfully implement the PTX 1.4 and PTX 2.1 specifications which may include features older GPUs do not support. The LLVM translator strives for correct and efficient translation from PTX to x86 that will hopefully make CUDA an effective way of programming multicore CPUs as well as GPUs. -deviceemu has been a deprecated feature of CUDA for quite some time, but the LLVM translator has always been faster.

Additionally, several correctness checkers are built into the emulator to verify: aligned memory accesses, accesses to shared memory are properly synchronized, and global memory dereferencing accesses allocated regions of memory. We have also implemented a command-line interactive debugger inspired largely by gdb to single-step through CUDA kernels, set breakpoints and watchpoints, etc... These tools were specifically developed to expedite the debugging of CUDA programs; you may find them useful.

Sorry about the Linux-only aspect. We've started a Windows branch (as well as a Mac OS X port) but the engineering burden is already large enough to stress our research pursuits. If anyone has any time and interest, they may wish to help us provide support for Windows!

Hope this helps.

[1]: GPU Ocelot - https://code.google.com/archive/p/gpuocelot/

[2]: Ocelot Interactive Debugger - http://forums.nvidia.com/index.php?showtopic=174820


问:
Compare two Arrays with Objects and create new array with unmatched objects
I have the following two Javascript arrays:

```<code>const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];
</code>```

I now want a new array array3 that contains only the objects that aren't already in array2, so:

```<code>const array3 = [{ id: 2}, { id: 4 }];
</code>```

I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.

```<code>const array3 = array1.filter(entry1 => {
  return array2.some(entry2 => entry1.id !== entry2.id);
});
</code>```

Any idea? ES6 welcome

答:
Nina's answer is a good start but will miss any unique elements in array 2.
This extends her answer to get the unique elements from each array and then combine them:

const
    array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
    array2 = [{ id: 1 }, { id: 3 }, { id: 5 }],
    array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id)),
    array4 = array2.filter(entry1 => !array1.some(entry2 => entry1.id === entry2.id)),
    array5 = array3.concat(array4);

console.log(array5);```

Body:
I have the following two Javascript arrays:

const array1 = [{ id: 1}, { id: 2 }, { id: 3 }, { id: 4}];
const array2 = [{ id: 1}, { id: 3 }];

I now want a new array array3 that contains only the objects that aren't already in array2, so:

const array3 = [{ id: 2}, { id: 4 }];

I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.

const array3 = array1.filter(entry1 => {
  return array2.some(entry2 => entry1.id !== entry2.id);
});

Any idea? ES6 welcome


问:
Replace NA in Column A, comparing column A and a list
I have a data.frame DF which contains two columns. Names and Score.
I than have a list (the.list) containing names. Some are equal to the names in names in DF$names.
I need to insert a number (2000) into DF$score, if the name is in the.list and the score is NA

The data:

```<code>DF.scores <- data.frame(c("steve", "anna", "albert", "john", "sarah", "lily"), c(2000, 1500, NA, NA, NA, 1750))
names(DF.scores) <- c("names", "score")
the.list <- c("anna", "steve", "john")
</code>```

I need the data frame to end up like this:

```<code>names   score
steve   2000
anna    1500
albert  NA
john    2000
sarah   NA
lily    1750
</code>```

I have tried subsetting the data, use which command but getting no results.

答:
Consider using dplyr::mutate() for this:

```<code>dplyr::mutate(DF.scores, score = ifelse(names %in% the.list & is.na(score), 2000, score))
</code>```

This sets score to 2000 if both conditions are met, names is in the.list and score is NA.

```<code>> dplyr::mutate(DF.scores, score = ifelse(names %in% the.list & is.na(score), 2000, score))
   names score
1  steve  2000
2   anna  1500
3 albert    NA
4   john  2000
5  sarah    NA
6   lily  1750
</code>```

Body:
I have a data.frame DF which contains two columns. Names and Score.
I than have a list (the.list) containing names. Some are equal to the names in names in DF$names.
I need to insert a number (2000) into DF$score, if the name is in the.list and the score is NA

The data:

DF.scores <- data.frame(c("steve", "anna", "albert", "john", "sarah", "lily"), c(2000, 1500, NA, NA, NA, 1750))
names(DF.scores) <- c("names", "score")
the.list <- c("anna", "steve", "john")

I need the data frame to end up like this:

names   score
steve   2000
anna    1500
albert  NA
john    2000
sarah   NA
lily    1750

I have tried subsetting the data, use which command but getting no results.

Body:
Consider using dplyr::mutate() for this:

dplyr::mutate(DF.scores, score = ifelse(names %in% the.list & is.na(score), 2000, score))

This sets score to 2000 if both conditions are met, names is in the.list and score is NA.

> dplyr::mutate(DF.scores, score = ifelse(names %in% the.list & is.na(score), 2000, score))
   names score
1  steve  2000
2   anna  1500
3 albert    NA
4   john  2000
5  sarah    NA
6   lily  1750


问:
Google maps show multiple markers from firebase
I have code that allows me to input the location name with the lat and longitude and then the map displays the location with a marker.

The issue i am having is that i want the map to show all the locations, each with its own marker on the map.

Below is the code i have used to get the one location showing on the map

```<code>public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setOnMarkerClickListener(this);
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot s : dataSnapshot.getChildren()){
                Venue venue = s.getValue(Venue.class);
                LatLng location=new LatLng(venue.venueLat,venue.venueLong);
                mMap.addMarker(new MarkerOptions().position(location).title(venue.venueName)).setIcon(BitmapDescriptorFactory.defaultMarker());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

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

Any help is much apreciated

I have no errors just shows the one location that i have added to the firebasedatabase

答:
```<code>   Marker marker;
List<Venue> venueList;
</code>```

//in onCreate method
  venueList = new ArrayList<>();

```<code>    mVenues.push().setValue(marker);
</code>```

//onMaps ready method

```<code>public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot s : dataSnapshot.getChildren()){
                Venue venue = s.getValue(Venue.class);

                venueList.add(venue);
                for (int i = 0; i < venueList.size(); i++)
                {
                    LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
                    if (mMap != null) {
                        marker = mMap.addMarker(new MarkerOptions().position(latLng).title(venue.venueName));
                                            }
                }
            }

        }
</code>```

Body:
I have code that allows me to input the location name with the lat and longitude and then the map displays the location with a marker.

The issue i am having is that i want the map to show all the locations, each with its own marker on the map.

Below is the code i have used to get the one location showing on the map

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setOnMarkerClickListener(this);
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot s : dataSnapshot.getChildren()){
                Venue venue = s.getValue(Venue.class);
                LatLng location=new LatLng(venue.venueLat,venue.venueLong);
                mMap.addMarker(new MarkerOptions().position(location).title(venue.venueName)).setIcon(BitmapDescriptorFactory.defaultMarker());
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

Any help is much apreciated

I have no errors just shows the one location that i have added to the firebasedatabase

Body:
   Marker marker;
List<Venue> venueList;

//in onCreate method
  venueList = new ArrayList<>();

    mVenues.push().setValue(marker);

//onMaps ready method

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    mVenues.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot s : dataSnapshot.getChildren()){
                Venue venue = s.getValue(Venue.class);

                venueList.add(venue);
                for (int i = 0; i < venueList.size(); i++)
                {
                    LatLng latLng = new LatLng(venue.venueLat,venue.venueLong);
                    if (mMap != null) {
                        marker = mMap.addMarker(new MarkerOptions().position(latLng).title(venue.venueName));
                                            }
                }
            }

        }


问:
Ajax call not appending to div
My ajax call

```<code>$('#searchform').submit(function(event) {
  $.ajax({
  type: "get",
  url: "/list",
  dataType: "text",
  data: $("#searchform").serialize(),
   beforeSend: function() {
              $(".se-pre-con").show();
           },
  success: function(data)
  {
    console.log(data);
    $("#testcontent").append(data);
    location.href="/test?"+$("#searchform").serialize();
  }

});
  event.preventDefault();
});
</code>```

This ajax call does not append the data to the testcontentdiv. I get the console log for data very well, but it just does not want to append. The div #testcontentis always empty.

What am I doing wrong.

答: Actually, you are appending data to #testcontent, but there is one mistake here - you are refreshing the page on success by calling location.href="/test?"+... and the browser renders default view again.

Title: Ajax call not appending to div

Body:
My ajax call

$('#searchform').submit(function(event) {
  $.ajax({
  type: "get",
  url: "/list",
  dataType: "text",
  data: $("#searchform").serialize(),
   beforeSend: function() {
              $(".se-pre-con").show();
           },
  success: function(data)
  {
    console.log(data);
    $("#testcontent").append(data);
    location.href="/test?"+$("#searchform").serialize();
  }

});
  event.preventDefault();
});

This ajax call does not append the data to the testcontentdiv. I get the console log for data very well, but it just does not want to append. The div #testcontentis always empty.

What am I doing wrong.


问:
Google Sheets Script getLastRow() not returning all values

I have email addresses in first column. When I try to get the last row of this column, the function only returns the first two values. Here is a link to the sheet: https://docs.google.com/spreadsheets/d/1piGCiWMcUKUWagIJSZ_0SxxuNG3tcEcrx-fKnMDOIlQ/edit?usp=sharing

Here is the script function:

```<code>function myFunction() {
  var rangeLastRow = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1).getLastRow();
  var emails = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1,rangeLastRow).getValues();
  Logger.log(emails);
}
</code>```

Shouldn't it be returning all of the email addresses in the first column?

It is only returning the first two email addresses.

答:
No, it's working correctly. range.getLastRow() returns the absolute index of the last row of the range.  Your line

```<code>var rangeLastRow = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1).getLastRow();
</code>```

returns the row index of cell A2 that you specified in getRange(2, 1), so your call to range.getValues() is getting the values of the range A2:A3. i.e. Your call to range.getLastRow() returns 2 because your range is (row 2, col 1), so your call to range.getValues() is looking at the range (row 2, col 1, 2 rows)

You want the last row of data in the sheet, which you get with sheet.getLastRow().  In fact, why not do away with var rangelastRow altogether? The following give you the result you're after:

```<code>function myFunction() {
  var ss = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  var emails = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1,ss.getLastRow() - 1).getValues();
  Logger.log(emails);
}
</code>```

Note that you actually want to use getLastRow() - 1 at set the number of rows in the range because your range starts at row 2, not row 1.

Body:
I have email addresses in first column. When I try to get the last row of this column, the function only returns the first two values. Here is a link to the sheet: https://docs.google.com/spreadsheets/d/1piGCiWMcUKUWagIJSZ_0SxxuNG3tcEcrx-fKnMDOIlQ/edit?usp=sharing

Here is the script function:

function myFunction() {
  var rangeLastRow = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1).getLastRow();
  var emails = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1,rangeLastRow).getValues();
  Logger.log(emails);
}

Shouldn't it be returning all of the email addresses in the first column?

It is only returning the first two email addresses.

Body:
No, it's working correctly. range.getLastRow() returns the absolute index of the last row of the range.  Your line

var rangeLastRow = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1).getLastRow();

returns the row index of cell A2 that you specified in getRange(2, 1), so your call to range.getValues() is getting the values of the range A2:A3. i.e. Your call to range.getLastRow() returns 2 because your range is (row 2, col 1), so your call to range.getValues() is looking at the range (row 2, col 1, 2 rows)

You want the last row of data in the sheet, which you get with sheet.getLastRow().  In fact, why not do away with var rangelastRow altogether? The following give you the result you're after:

function myFunction() {
  var ss = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  var emails = SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(2, 1,ss.getLastRow() - 1).getValues();
  Logger.log(emails);
}

Note that you actually want to use getLastRow() - 1 at set the number of rows in the range because your range starts at row 2, not row 1.