问:
ASP.NET TempData persists between requests
I am using temp data as follow in my controllers - very simple, when there is a problem:

```<code>TempData("StatusMessage") = "You have no items set to Auto-Ship."
</code>```

Then on every page I have a user control as follows:

```<code><div class="error-container">
<%  If TempData.ContainsKey("ErrorMessage") Then%>
<script> $('div.error-container').show();</script>
<div class="msg-error"><p><%=TempData("ErrorMessage") %></p></div>
<% End If%>
<%  If TempData.ContainsKey("StatusMessage") Then%>
<script> $('div.error-container').show();</script>
<div class="msg-status"><p><%=TempData("StatusMessage")%></p></div>
<% End If%>
<ul></ul>
</div>
</code>```

Problem is when I do have an error added to tempdata it shows up properly on the first request but ALSO shows up again on the next request as well - which is obviously very confusing and not a desired behavior.

I am not using any IoC, I did see the post with the same problems when using that.

答:
would this be acceptable (removing the error once it has been shown):</p>

```<code><%  If TempData.ContainsKey("ErrorMessage") Then %>
<script> $('div.error-container').show();</script>
<div class="msg-error"><p><%=TempData("ErrorMessage") %></p></div>
<%
    TempData.Remove("ErrorMessage")
End If
%>
</code>```

OwnerDisplayName: Max Fraser

Body:
I am using temp data as follow in my controllers - very simple, when there is a problem:

TempData("StatusMessage") = "You have no items set to Auto-Ship."

Then on every page I have a user control as follows:

<%  If TempData.ContainsKey("ErrorMessage") Then%>

<%=TempData("ErrorMessage") %>

<% End If%>
<%  If TempData.ContainsKey("StatusMessage") Then%>

<%=TempData("StatusMessage")%>

<% End If%>

Problem is when I do have an error added to tempdata it shows up properly on the first request but ALSO shows up again on the next request as well - which is obviously very confusing and not a desired behavior.

I am not using any IoC, I did see the post with the same problems when using that.

Body:
would this be acceptable (removing the error once it has been shown):

<%  If TempData.ContainsKey("ErrorMessage") Then %>
<script> $('div.error-container').show();</script>
<div class="msg-error"><p><%=TempData("ErrorMessage") %></p></div>
<%
    TempData.Remove("ErrorMessage")
End If
%>

OwnerDisplayName: Spikolynn


来源: stackexchange

问:
Get all conflict dates in a rails query
everyone!

I'm creating a rails app to manage and schedule vacations in a government institution.

The system has to filter the vacations and load them into a grid (see the grid in the link below, in portuguese, sorry for that).

The problem is: I've got to filter all vacations that are in conflict.

Example: (MM-dd-yyyy)

John's vacation: starts in 01-01-2018, ends 01-15-2018.
Marie's vacation start in 01-01-2018, ends 01-10-2018.

John's vacation and Marie's vacation are in conflict.

A person can split your vacation through the year.

How can i write a rails query to get all vacations that are in conflict?

Vacation's schema:

```<code>t.integer "fs_manager_id", limit: 19, precision: 19
t.integer "year", precision: 38
t.date "date_ini"
t.date "date_end"
t.integer "days", precision: 38
t.boolean "approved", default: false
t.datetime "date_approved", precision: 6
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "fs_balance_id", precision: 38
t.integer "fs_person_id", precision: 38
t.index ["fs_balance_id"], name: "i_fs_vacations_fs_balance_id"
t.index ["fs_manager_id"], name: "i_fs_vacations_fs_manager_id"
t.index ["fs_person_id"], name: "i_fs_vacations_fs_person_id"
</code>```

Image: Grid with all vacations and vacation's owner dd/MM/yyyy

EDIT : The problem is: I've got to filter all vacations that are in conflict and show them to user.

答:
It's hard to say how to make such query using ActiveRecord

But you can write a <s>monster</s> simple sql query:

```<code>query = 'select distinct a1.*
    from vacations as a1, vacations as a2
    where a1.start_date < a2.end_date and
    a1.end_date > a2.start_date and
    a1.id <> a2.id'
response = ApplicationRecord.connection.execute(query)
</code>```

And then manually parse a reponse using map or anything like this.

ContentLicense: CC BY-SA 3.0

Title: Get all conflict dates in a rails query

Body:
everyone!

I'm creating a rails app to manage and schedule vacations in a government institution.

The system has to filter the vacations and load them into a grid (see the grid in the link below, in portuguese, sorry for that).

The problem is: I've got to filter all vacations that are in conflict.

Example: (MM-dd-yyyy)

John's vacation: starts in 01-01-2018, ends 01-15-2018.
Marie's vacation start in 01-01-2018, ends 01-10-2018.

John's vacation and Marie's vacation are in conflict.

A person can split your vacation through the year.

How can i write a rails query to get all vacations that are in conflict?

Vacation's schema:

t.integer "fs_manager_id", limit: 19, precision: 19
t.integer "year", precision: 38
t.date "date_ini"
t.date "date_end"
t.integer "days", precision: 38
t.boolean "approved", default: false
t.datetime "date_approved", precision: 6
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "fs_balance_id", precision: 38
t.integer "fs_person_id", precision: 38
t.index ["fs_balance_id"], name: "i_fs_vacations_fs_balance_id"
t.index ["fs_manager_id"], name: "i_fs_vacations_fs_manager_id"
t.index ["fs_person_id"], name: "i_fs_vacations_fs_person_id"

Image: Grid with all vacations and vacation's owner dd/MM/yyyy

EDIT : The problem is: I've got to filter all vacations that are in conflict and show them to user.

Body:
It's hard to say how to make such query using ActiveRecord

But you can write a <s>monster</s> simple sql query:

query = 'select distinct a1.*
    from vacations as a1, vacations as a2
    where a1.start_date < a2.end_date and
    a1.end_date > a2.start_date and
    a1.id <> a2.id'
response = ApplicationRecord.connection.execute(query)

And then manually parse a reponse using map or anything like this.


问:
Trying to implement a LeftJoin extension method to work with EF Core 2.0
I am trying to have an extension method to implement left outer join which returns IQueryable that run against EF Core 2.0 data context.

I read the Stack Overflow thread here for help: Extension method for IQueryable left outer join using LINQ.  The accepted answer had some problems that were addressed in a later answer here by Jan Van der Haegen.  I attempted to use the LeftJoin extension method described there with an EF Core 2.0 data context and ran into an exception which I cannot seem to resolve.

As I cannot find any fault with the implementation of the LeftJoin extension method, I attempted to run the same method against a data context using EF6 and it worked as expected. I have shared my experiment including the SQL scripts to generate the test data here:

Experiment with LeftJoin extension run against EF6 and EF Core 2.0

It contains two projects one running LeftJoin against EF6 and the other running it against EF Core 2.0.  The extension method is shared via a .Net Standard 2.0 class library.

The extension method for LeftJoin is as follows:

```<code>namespace QueryableExtensions
{
    // Much of the code copied from following URL:
    // https://stackoverflow.com/questions/21615693/extension-method-for-iqueryable-left-outer-join-using-linq
    internal class KeyValuePairHolder<T1, T2>
    {
        public T1 Item1 { get; set; }
        public T2 Item2 { get; set; }
    }

    internal class ResultSelectorRewriter<TOuter, TInner, TResult> : ExpressionVisitor
    {
        private Expression<Func<TOuter, TInner, TResult>> resultSelector;
        public Expression<Func<KeyValuePairHolder<TOuter, IEnumerable<TInner>>, TInner, TResult>> CombinedExpression { get; private set; }

        private ParameterExpression OldTOuterParamExpression;
        private ParameterExpression OldTInnerParamExpression;
        private ParameterExpression NewTOuterParamExpression;
        private ParameterExpression NewTInnerParamExpression;

        public ResultSelectorRewriter(Expression<Func<TOuter, TInner, TResult>> resultSelector)
        {
            this.resultSelector = resultSelector;
            this.OldTOuterParamExpression = resultSelector.Parameters[0];
            this.OldTInnerParamExpression = resultSelector.Parameters[1];

            this.NewTOuterParamExpression = Expression.Parameter(typeof(KeyValuePairHolder<TOuter, IEnumerable<TInner>>));
            this.NewTInnerParamExpression = Expression.Parameter(typeof(TInner));

            var newBody = this.Visit(this.resultSelector.Body);
            var combinedExpression = Expression.Lambda(newBody, new ParameterExpression[] { this.NewTOuterParamExpression, this.NewTInnerParamExpression });
            this.CombinedExpression = (Expression<Func<KeyValuePairHolder<TOuter, IEnumerable<TInner>>, TInner, TResult>>)combinedExpression;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            if (node == this.OldTInnerParamExpression)
                return this.NewTInnerParamExpression;
            else if (node == this.OldTOuterParamExpression)
                return Expression.PropertyOrField(this.NewTOuterParamExpression, "Item1");
            else
                throw new InvalidOperationException("What is this sorcery?", new InvalidOperationException("Did not expect a parameter: " + node));
        }
    }

    public static class JoinExtensions
    {
        internal static readonly System.Reflection.MethodInfo
            Enumerable_DefaultIfEmpty = typeof(Enumerable).GetMethods()
                .First(x => x.Name == "DefaultIfEmpty" && x.GetParameters().Length == 1);
        internal static readonly System.Reflection.MethodInfo
            Queryable_SelectMany = typeof(Queryable).GetMethods()
                .Where(x => x.Name == "SelectMany" && x.GetParameters().Length == 3)
                .OrderBy(x => x.ToString().Length).First();
        internal static readonly System.Reflection.MethodInfo
            Queryable_Where = typeof(Queryable).GetMethods()
                .First(x => x.Name == "Where" && x.GetParameters().Length == 2);
        internal static readonly System.Reflection.MethodInfo
            Queryable_GroupJoin = typeof(Queryable).GetMethods()
                .First(x => x.Name == "GroupJoin" && x.GetParameters().Length == 5);

        public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
                   this IQueryable<TOuter> outer,
                   IQueryable<TInner> inner,
                   Expression<Func<TOuter, TKey>> outerKeySelector,
                   Expression<Func<TInner, TKey>> innerKeySelector,
                   Expression<Func<TOuter, TInner, TResult>> resultSelector)
        {

            var keyValuePairHolderWithGroup = typeof(KeyValuePairHolder<,>)
                .MakeGenericType(
                    typeof(TOuter),
                    typeof(IEnumerable<>).MakeGenericType(typeof(TInner))
                );
            var paramOuter = Expression.Parameter(typeof(TOuter));
            var paramInner = Expression.Parameter(typeof(IEnumerable<TInner>));

            var resultSel = Expression
                .Lambda(
                    Expression.MemberInit(
                        Expression.New(keyValuePairHolderWithGroup),
                        Expression.Bind(
                            keyValuePairHolderWithGroup.GetMember("Item1").Single(),
                            paramOuter
                            ),
                        Expression.Bind(
                            keyValuePairHolderWithGroup.GetMember("Item2").Single(),
                            paramInner
                            )
                        ),
                    paramOuter,
                    paramInner
                );
            var groupJoin = Queryable_GroupJoin
                .MakeGenericMethod(
                    typeof(TOuter),
                    typeof(TInner),
                    typeof(TKey),
                    keyValuePairHolderWithGroup
                )
                .Invoke(
                    "ThisArgumentIsIgnoredForStaticMethods",
                    new object[]{
                        outer,
                        inner,
                        outerKeySelector,
                        innerKeySelector,
                        resultSel
                    }
                );

            var paramGroup = Expression.Parameter(keyValuePairHolderWithGroup);
            Expression collectionSelector = Expression.Lambda(
                            Expression.Call(
                                    null,
                                    Enumerable_DefaultIfEmpty.MakeGenericMethod(typeof(TInner)),
                                    Expression.MakeMemberAccess(paramGroup, keyValuePairHolderWithGroup.GetProperty("Item2")))
                            ,
                            paramGroup
                        );

            Expression newResultSelector =
                new ResultSelectorRewriter<TOuter, TInner, TResult>(resultSelector)
                    .CombinedExpression;

            var selectMany1Result = Queryable_SelectMany
                .MakeGenericMethod(
                    keyValuePairHolderWithGroup,
                    typeof(TInner),
                    typeof(TResult)
                )
                .Invoke(
                    "ThisArgumentIsIgnoredForStaticMethods",
                    new object[]
                    {
                        groupJoin,
                        collectionSelector,
                        newResultSelector
                    }
                );
            return (IQueryable<TResult>)selectMany1Result;
        }
    }
}
</code>```

When I run the above with a data context by EF Core 2.0 I get the following exception thrown at runtime:

```<code>System.ArgumentNullException occurred
  HResult = 0x80004003
  Message = Value cannot be null.
    Source =< Cannot evaluate the exception source>
      StackTrace:
   at Remotion.Utilities.ArgumentUtility.CheckNotNull[T](String argumentName, T actualValue)
   at Remotion.Utilities.ArgumentUtility.CheckNotNullOrEmpty(String argumentName, String actualValue)
   at Remotion.Linq.Clauses.GroupJoinClause..ctor(String itemName, Type itemType, JoinClause joinClause)
   at Remotion.Linq.Parsing.Structure.IntermediateModel.GroupJoinExpressionNode.ApplyNodeSpecificSemantics(QueryModel queryModel, ClauseGenerationContext clauseGenerationContext)
   at Remotion.Linq.Parsing.Structure.IntermediateModel.MethodCallExpressionNodeBase.Apply(QueryModel queryModel, ClauseGenerationContext clauseGenerationContext)
   at Remotion.Linq.Parsing.Structure.QueryParser.ApplyAllNodes(IExpressionNode node, ClauseGenerationContext clauseGenerationContext)
   at Remotion.Linq.Parsing.Structure.QueryParser.ApplyAllNodes(IExpressionNode node, ClauseGenerationContext clauseGenerationContext)
   at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](Expression query, INodeTypeProvider nodeTypeProvider, IDatabase database, IDiagnosticsLogger`1 logger, Type contextType)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<> c__DisplayClass15_0`1.< Execute > b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Remotion.Linq.QueryableBase`1.GetEnumerator()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at TestWithEFCore2.Program.Main() in C: \Users\hewasud\Git\TestLeftJoinExtensionWithEF6\TestWithEF6\TestWithEFCore2\Program.cs:line 27
</code>```

My questions:

Is this a bug in EF Core 2.0 or am I doing something wrong here?

Is there a better way to produce an extension method which combines the GroupJoin and SelectMany methods to perform a LeftJoin when using EF Core 2.0 assuming that this code must be functional within a .Net Standard class library allowing portability?

Thank you.

答:
As it is suggested here, Only workable solution was using the LinqKit.Core library.  Despite all effort I was not able to get the Expression based solution to work with EF.Core under .Net Core or .Net Standard library projects.  LinqKit.Core library was the key to have the extension be portable and used within a .Net Standard 2.0 class library project.

As it was suggested, with LinkqKit.Core the solution is very simple:

```<code>    /// <summary>
    /// Implement Left Outer join implemented by calling GroupJoin and
    /// SelectMany within this extension method
    /// </summary>
    /// <typeparam name="TOuter">Outer Type</typeparam>
    /// <typeparam name="TInner">Inner Type</typeparam>
    /// <typeparam name="TKey">Key Type</typeparam>
    /// <typeparam name="TResult">Result Type</typeparam>
    /// <param name="outer">Outer set</param>
    /// <param name="inner">Inner set</param>
    /// <param name="outerKeySelector">Outer Key Selector</param>
    /// <param name="innerKeySelector">Inner Key Selector</param>
    /// <param name="resultSelector">Result Selector</param>
    /// <returns>IQueryable Result set</returns>
    public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
       this IQueryable<TOuter> outer,
       IQueryable<TInner> inner,
       Expression<Func<TOuter, TKey>> outerKeySelector,
       Expression<Func<TInner, TKey>> innerKeySelector,
       Expression<Func<TOuter, TInner, TResult>> resultSelector)
    {
        //LinqKit allows easy runtime evaluation of inline invoked expressions
        // without manually writing expression trees.
        return outer
            .AsExpandable()// Tell LinqKit to convert everything into an expression tree.
            .GroupJoin(
                inner,
                outerKeySelector,
                innerKeySelector,
                (outerItem, innerItems) => new { outerItem, innerItems })
            .SelectMany(
                joinResult => joinResult.innerItems.DefaultIfEmpty(),
                (joinResult, innerItem) =>
                    resultSelector.Invoke(joinResult.outerItem, innerItem));
    }
</code>```

The Experiment in Github updated to illustrate working solution here: GitHub solution illustrating LeftJoin extension implemented in a .Net Standard Library

ContentLicense: CC BY-SA 4.0

Body:
I am trying to have an extension method to implement left outer join which returns IQueryable that run against EF Core 2.0 data context.

I read the Stack Overflow thread here for help: Extension method for IQueryable left outer join using LINQ.  The accepted answer had some problems that were addressed in a later answer here by Jan Van der Haegen.  I attempted to use the LeftJoin extension method described there with an EF Core 2.0 data context and ran into an exception which I cannot seem to resolve.

As I cannot find any fault with the implementation of the LeftJoin extension method, I attempted to run the same method against a data context using EF6 and it worked as expected. I have shared my experiment including the SQL scripts to generate the test data here:

Experiment with LeftJoin extension run against EF6 and EF Core 2.0

It contains two projects one running LeftJoin against EF6 and the other running it against EF Core 2.0.  The extension method is shared via a .Net Standard 2.0 class library.

The extension method for LeftJoin is as follows:

namespace QueryableExtensions
{
    // Much of the code copied from following URL:
    // https://stackoverflow.com/questions/21615693/extension-method-for-iqueryable-left-outer-join-using-linq
    internal class KeyValuePairHolder<T1, T2>
    {
        public T1 Item1 { get; set; }
        public T2 Item2 { get; set; }
    }

    internal class ResultSelectorRewriter<TOuter, TInner, TResult> : ExpressionVisitor
    {
        private Expression<Func<TOuter, TInner, TResult>> resultSelector;
        public Expression<Func<KeyValuePairHolder<TOuter, IEnumerable<TInner>>, TInner, TResult>> CombinedExpression { get; private set; }

        private ParameterExpression OldTOuterParamExpression;
        private ParameterExpression OldTInnerParamExpression;
        private ParameterExpression NewTOuterParamExpression;
        private ParameterExpression NewTInnerParamExpression;

        public ResultSelectorRewriter(Expression<Func<TOuter, TInner, TResult>> resultSelector)
        {
            this.resultSelector = resultSelector;
            this.OldTOuterParamExpression = resultSelector.Parameters[0];
            this.OldTInnerParamExpression = resultSelector.Parameters[1];

            this.NewTOuterParamExpression = Expression.Parameter(typeof(KeyValuePairHolder<TOuter, IEnumerable<TInner>>));
            this.NewTInnerParamExpression = Expression.Parameter(typeof(TInner));

            var newBody = this.Visit(this.resultSelector.Body);
            var combinedExpression = Expression.Lambda(newBody, new ParameterExpression[] { this.NewTOuterParamExpression, this.NewTInnerParamExpression });
            this.CombinedExpression = (Expression<Func<KeyValuePairHolder<TOuter, IEnumerable<TInner>>, TInner, TResult>>)combinedExpression;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            if (node == this.OldTInnerParamExpression)
                return this.NewTInnerParamExpression;
            else if (node == this.OldTOuterParamExpression)
                return Expression.PropertyOrField(this.NewTOuterParamExpression, "Item1");
            else
                throw new InvalidOperationException("What is this sorcery?", new InvalidOperationException("Did not expect a parameter: " + node));
        }
    }

    public static class JoinExtensions
    {
        internal static readonly System.Reflection.MethodInfo
            Enumerable_DefaultIfEmpty = typeof(Enumerable).GetMethods()
                .First(x => x.Name == "DefaultIfEmpty" && x.GetParameters().Length == 1);
        internal static readonly System.Reflection.MethodInfo
            Queryable_SelectMany = typeof(Queryable).GetMethods()
                .Where(x => x.Name == "SelectMany" && x.GetParameters().Length == 3)
                .OrderBy(x => x.ToString().Length).First();
        internal static readonly System.Reflection.MethodInfo
            Queryable_Where = typeof(Queryable).GetMethods()
                .First(x => x.Name == "Where" && x.GetParameters().Length == 2);
        internal static readonly System.Reflection.MethodInfo
            Queryable_GroupJoin = typeof(Queryable).GetMethods()
                .First(x => x.Name == "GroupJoin" && x.GetParameters().Length == 5);

        public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
                   this IQueryable<TOuter> outer,
                   IQueryable<TInner> inner,
                   Expression<Func<TOuter, TKey>> outerKeySelector,
                   Expression<Func<TInner, TKey>> innerKeySelector,
                   Expression<Func<TOuter, TInner, TResult>> resultSelector)
        {

            var keyValuePairHolderWithGroup = typeof(KeyValuePairHolder<,>)
                .MakeGenericType(
                    typeof(TOuter),
                    typeof(IEnumerable<>).MakeGenericType(typeof(TInner))
                );
            var paramOuter = Expression.Parameter(typeof(TOuter));
            var paramInner = Expression.Parameter(typeof(IEnumerable<TInner>));

            var resultSel = Expression
                .Lambda(
                    Expression.MemberInit(
                        Expression.New(keyValuePairHolderWithGroup),
                        Expression.Bind(
                            keyValuePairHolderWithGroup.GetMember("Item1").Single(),
                            paramOuter
                            ),
                        Expression.Bind(
                            keyValuePairHolderWithGroup.GetMember("Item2").Single(),
                            paramInner
                            )
                        ),
                    paramOuter,
                    paramInner
                );
            var groupJoin = Queryable_GroupJoin
                .MakeGenericMethod(
                    typeof(TOuter),
                    typeof(TInner),
                    typeof(TKey),
                    keyValuePairHolderWithGroup
                )
                .Invoke(
                    "ThisArgumentIsIgnoredForStaticMethods",
                    new object[]{
                        outer,
                        inner,
                        outerKeySelector,
                        innerKeySelector,
                        resultSel
                    }
                );

            var paramGroup = Expression.Parameter(keyValuePairHolderWithGroup);
            Expression collectionSelector = Expression.Lambda(
                            Expression.Call(
                                    null,
                                    Enumerable_DefaultIfEmpty.MakeGenericMethod(typeof(TInner)),
                                    Expression.MakeMemberAccess(paramGroup, keyValuePairHolderWithGroup.GetProperty("Item2")))
                            ,
                            paramGroup
                        );

            Expression newResultSelector =
                new ResultSelectorRewriter<TOuter, TInner, TResult>(resultSelector)
                    .CombinedExpression;

            var selectMany1Result = Queryable_SelectMany
                .MakeGenericMethod(
                    keyValuePairHolderWithGroup,
                    typeof(TInner),
                    typeof(TResult)
                )
                .Invoke(
                    "ThisArgumentIsIgnoredForStaticMethods",
                    new object[]
                    {
                        groupJoin,
                        collectionSelector,
                        newResultSelector
                    }
                );
            return (IQueryable<TResult>)selectMany1Result;
        }
    }
}

When I run the above with a data context by EF Core 2.0 I get the following exception thrown at runtime:

System.ArgumentNullException occurred
  HResult = 0x80004003
  Message = Value cannot be null.
    Source =< Cannot evaluate the exception source>
      StackTrace:
   at Remotion.Utilities.ArgumentUtility.CheckNotNull[T](String argumentName, T actualValue)
   at Remotion.Utilities.ArgumentUtility.CheckNotNullOrEmpty(String argumentName, String actualValue)
   at Remotion.Linq.Clauses.GroupJoinClause..ctor(String itemName, Type itemType, JoinClause joinClause)
   at Remotion.Linq.Parsing.Structure.IntermediateModel.GroupJoinExpressionNode.ApplyNodeSpecificSemantics(QueryModel queryModel, ClauseGenerationContext clauseGenerationContext)
   at Remotion.Linq.Parsing.Structure.IntermediateModel.MethodCallExpressionNodeBase.Apply(QueryModel queryModel, ClauseGenerationContext clauseGenerationContext)
   at Remotion.Linq.Parsing.Structure.QueryParser.ApplyAllNodes(IExpressionNode node, ClauseGenerationContext clauseGenerationContext)
   at Remotion.Linq.Parsing.Structure.QueryParser.ApplyAllNodes(IExpressionNode node, ClauseGenerationContext clauseGenerationContext)
   at Remotion.Linq.Parsing.Structure.QueryParser.GetParsedQuery(Expression expressionTreeRoot)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](Expression query, INodeTypeProvider nodeTypeProvider, IDatabase database, IDiagnosticsLogger`1 logger, Type contextType)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<> c__DisplayClass15_0`1.< Execute > b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Remotion.Linq.QueryableBase`1.GetEnumerator()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at TestWithEFCore2.Program.Main() in C: \Users\hewasud\Git\TestLeftJoinExtensionWithEF6\TestWithEF6\TestWithEFCore2\Program.cs:line 27

My questions:

Is this a bug in EF Core 2.0 or am I doing something wrong here?

Is there a better way to produce an extension method which combines the GroupJoin and SelectMany methods to perform a LeftJoin when using EF Core 2.0 assuming that this code must be functional within a .Net Standard class library allowing portability?

Thank you.

Body:
As it is suggested here, Only workable solution was using the LinqKit.Core library.  Despite all effort I was not able to get the Expression based solution to work with EF.Core under .Net Core or .Net Standard library projects.  LinqKit.Core library was the key to have the extension be portable and used within a .Net Standard 2.0 class library project.

As it was suggested, with LinkqKit.Core the solution is very simple:

    /// <summary>
    /// Implement Left Outer join implemented by calling GroupJoin and
    /// SelectMany within this extension method
    /// </summary>
    /// <typeparam name="TOuter">Outer Type</typeparam>
    /// <typeparam name="TInner">Inner Type</typeparam>
    /// <typeparam name="TKey">Key Type</typeparam>
    /// <typeparam name="TResult">Result Type</typeparam>
    /// <param name="outer">Outer set</param>
    /// <param name="inner">Inner set</param>
    /// <param name="outerKeySelector">Outer Key Selector</param>
    /// <param name="innerKeySelector">Inner Key Selector</param>
    /// <param name="resultSelector">Result Selector</param>
    /// <returns>IQueryable Result set</returns>
    public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
       this IQueryable<TOuter> outer,
       IQueryable<TInner> inner,
       Expression<Func<TOuter, TKey>> outerKeySelector,
       Expression<Func<TInner, TKey>> innerKeySelector,
       Expression<Func<TOuter, TInner, TResult>> resultSelector)
    {
        //LinqKit allows easy runtime evaluation of inline invoked expressions
        // without manually writing expression trees.
        return outer
            .AsExpandable()// Tell LinqKit to convert everything into an expression tree.
            .GroupJoin(
                inner,
                outerKeySelector,
                innerKeySelector,
                (outerItem, innerItems) => new { outerItem, innerItems })
            .SelectMany(
                joinResult => joinResult.innerItems.DefaultIfEmpty(),
                (joinResult, innerItem) =>
                    resultSelector.Invoke(joinResult.outerItem, innerItem));
    }

The Experiment in Github updated to illustrate working solution here: GitHub solution illustrating LeftJoin extension implemented in a .Net Standard Library


问:
Make .vimrc discriminate against filetype or working directory?
I wasn't really sure how to search for this topic, so I hope that this is an original question.

Context

When I code in vim, I like to set number (I have placed it in my .vimrc), but when I view my markdown file of personal links (to recipes etc.), I do not need set number, but do not want to always type set nonumber.

Question

Is there a way to have set number (or other properties for that matter) toggle on or off based on filetype or the directory that is being worked in (a type of whitelist or blacklist)?

Edit

I just found the autocmd Filetype setlocal ... option, but autocmd Filetype setlocal set nonumber does not work.

答:
You need the pattern for the autocmd. Since you are using the FileType event the pattern will be matching against the 'filetype'.

```<code>augroup my_ft
  autocmd!
  autocmd FileType markdown setlocal nonumber
augroup END
</code>```

You can also add set nonumber in ~/.vim/after/ftplugin/markdown.vim.

Body:
You need the pattern for the autocmd. Since you are using the FileType event the pattern will be matching against the 'filetype'.

augroup my_ft
  autocmd!
  autocmd FileType markdown setlocal nonumber
augroup END

You can also add set nonumber in ~/.vim/after/ftplugin/markdown.vim.


问:
Not getting the user's name when anonymous linking with google account
I have two way method for signing-in, one is normal Google sign-in and other is Anonymous Sign-in. In my google sign-in there is no problem and everything works fine even the user's credentials are also coming great including name, email and firebase id.
Now the problem is that when I link my anonymous account to the google id using firebase, it is also working fine but at the time of getting credentials all I'm getting is null when getDisplayName() is called.

NOTE: I'm getting the firebase id and email correctly but the name is coming null.

This is my log output here :

```<code>11-15 12:58:26.712 21983-21983/in.pinelane.myhovi E/userName: null
11-15 12:58:26.712 21983-21983/in.pinelane.myhovi E/userEmail: xyz@gmail.com
</code>```

Since my code is working fine but still no luck, code goes like this :

```<code>private void linkGuestWithCredential(AuthCredential credentials) {

    firebaseAuth.getCurrentUser().linkWithCredential(credentials)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if( task.isSuccessful()){
                        mProgress.dismiss();
                        Log.d(TAG, "linkWithCredential:success");

                        FirebaseUser permanentUser = task.getResult().getUser();
                        callAnonymousUpdateApi(permanentUser);

                        Intent signIntent = new Intent(LoginActivity.this, MainActivity.class);
                        signIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(signIntent);
                        Toast.makeText(LoginActivity.this, "Welcome to MyHovi!", Toast.LENGTH_LONG)
                                .show();
                        finish();
                        overridePendingTransition(R.anim.right_enter, R.anim.left_exit);

                    }else{
                        mProgress.dismiss();
                        Log.e(TAG, "linkWithCredential:failure", task.getException());
                        Toast.makeText(getApplicationContext(), "Sign-in failed", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });
</code>```

In the callAnonymousUpdateApi(permanentUSer) I'm actually getting the credentials :

```<code>private void callAnonymousUpdateApi(FirebaseUser permanentUser) {

    final String name = permanentUser.getDisplayName();
    final String email = permanentUser.getEmail();
    final String firebaseId = permanentUser.getUid();

    RequestParams params = new RequestParams();
    params.add("user_id", userId);
    params.add("name", name);
    params.add("email", email);
    params.add("firebase_id", firebaseId);
    params.add("user_complete", "true");
}
</code>```

What I have tried so far is :

Changing FirebseUser permanentUSer = task.getResult().getUser(); to FirebseUser permanentUSer = FirebaseAuth.getInstance().getCurrentUser();

Tried the same thing in different way that is in the callAnonymousUpdateApi(FirebaseUser permanentUser) what I've done is trying the to get the name as final String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();

but still no luck, any help would be highly appreciated. Thanks

答:
When linking a provider, the provider's displayName and photoURL are not automatically copied to the top level. You can simply copy these fields when linking to an anonymous user. You can get the Google displayName:

FirebaseAuth.getInstance().getCurrentUser().getProviderData().get(0).getDisplayName()

You would then updateProfile:

```<code>UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setDisplayName(displayName).build();
user.updateProfile(profileUpdates)
   .addOnCompleteListener(new OnCompleteListener<Void>() {
     @Override
     public void onComplete(@NonNull Task<Void> task) {
       if (task.isSuccessful()) {
         Log.d(TAG, "User profile updated.");
       }
     }
   }
});
</code>```

Body:
I have two way method for signing-in, one is normal Google sign-in and other is Anonymous Sign-in. In my google sign-in there is no problem and everything works fine even the user's credentials are also coming great including name, email and firebase id.
Now the problem is that when I link my anonymous account to the google id using firebase, it is also working fine but at the time of getting credentials all I'm getting is null when getDisplayName() is called.

NOTE: I'm getting the firebase id and email correctly but the name is coming null.

This is my log output here :

11-15 12:58:26.712 21983-21983/in.pinelane.myhovi E/userName: null
11-15 12:58:26.712 21983-21983/in.pinelane.myhovi E/userEmail: xyz@gmail.com

Since my code is working fine but still no luck, code goes like this :

private void linkGuestWithCredential(AuthCredential credentials) {

    firebaseAuth.getCurrentUser().linkWithCredential(credentials)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if( task.isSuccessful()){
                        mProgress.dismiss();
                        Log.d(TAG, "linkWithCredential:success");

                        FirebaseUser permanentUser = task.getResult().getUser();
                        callAnonymousUpdateApi(permanentUser);

                        Intent signIntent = new Intent(LoginActivity.this, MainActivity.class);
                        signIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(signIntent);
                        Toast.makeText(LoginActivity.this, "Welcome to MyHovi!", Toast.LENGTH_LONG)
                                .show();
                        finish();
                        overridePendingTransition(R.anim.right_enter, R.anim.left_exit);

                    }else{
                        mProgress.dismiss();
                        Log.e(TAG, "linkWithCredential:failure", task.getException());
                        Toast.makeText(getApplicationContext(), "Sign-in failed", Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            });

In the callAnonymousUpdateApi(permanentUSer) I'm actually getting the credentials :

private void callAnonymousUpdateApi(FirebaseUser permanentUser) {

    final String name = permanentUser.getDisplayName();
    final String email = permanentUser.getEmail();
    final String firebaseId = permanentUser.getUid();

    RequestParams params = new RequestParams();
    params.add("user_id", userId);
    params.add("name", name);
    params.add("email", email);
    params.add("firebase_id", firebaseId);
    params.add("user_complete", "true");
}

What I have tried so far is :

Changing FirebseUser permanentUSer = task.getResult().getUser(); to FirebseUser permanentUSer = FirebaseAuth.getInstance().getCurrentUser();

Tried the same thing in different way that is in the callAnonymousUpdateApi(FirebaseUser permanentUser) what I've done is trying the to get the name as final String name = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();

but still no luck, any help would be highly appreciated. Thanks

Body:
When linking a provider, the provider's displayName and photoURL are not automatically copied to the top level. You can simply copy these fields when linking to an anonymous user. You can get the Google displayName:

FirebaseAuth.getInstance().getCurrentUser().getProviderData().get(0).getDisplayName()

You would then updateProfile:

UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder().setDisplayName(displayName).build();
user.updateProfile(profileUpdates)
   .addOnCompleteListener(new OnCompleteListener<Void>() {
     @Override
     public void onComplete(@NonNull Task<Void> task) {
       if (task.isSuccessful()) {
         Log.d(TAG, "User profile updated.");
       }
     }
   }
});


问:
Convert and Operation Not working as expected. Ignoring Year value
I have the following code:

```<code>CONVERT(VARCHAR(20), TimeCard_Date, 101) <
CONVERT(VARCHAR(20), dateadd(dd,-3,getdate()), 101)
</code>```

The Original TimeCard_Date value = 2018-06-01

The GetDate() return = 11/14/2017

Can anyone assist as to why it thinks the Timecard_Date value set for June  2018 is less than the GetDate() minus 3 days value?

答:
When you convert, it converts to a varchar datatype.  06/01/2018 is less than 11/14/2017 as a varchar since it is an alphabetical (or by number?) comparison.  If you compare by date, the comparison is by the date datatype, which is as you expect.

You can change your code to:
TimeCard_Date < dateadd(dd,-3,getdate())

Body:
I have the following code:

CONVERT(VARCHAR(20), TimeCard_Date, 101) <
CONVERT(VARCHAR(20), dateadd(dd,-3,getdate()), 101)

The Original TimeCard_Date value = 2018-06-01

The GetDate() return = 11/14/2017

Can anyone assist as to why it thinks the Timecard_Date value set for June  2018 is less than the GetDate() minus 3 days value?


问:
Deep copy an ArrayList containing objects with ArrayLists in Java
I have a problem to deep copy an ArrayList containing Attribute objects. After I have copied the ArrayList dataSet in a new one called trainingSet, I am trying to clear (of the trainingSet) all the content of the internal ArrayList of the Attribute called data. When I do so all the same content of the the ArrayList dataSet (data of dataSet) gets cleared, too. So in that case I have tried to deep copy all the content of the original list to the new one using the below tuts:

http://javarevisited.blogspot.gr/2014/03/how-to-clone-collection-in-java-deep-copy-vs-shallow.html#axzz4ybComIhC

https://beginnersbook.com/2013/12/how-to-clone-an-arraylist-to-another-arraylist/

How to make a deep copy of Java ArrayList

but I got the same behavior. So can someone please tell me how I can fix this problem and where the wrong thinking is?

Thank you for help.

ID3Algorithm.java

```<code>...
ArrayList<Attribute> dataSet = new ArrayList<dataSet>();
ArrayList<Attribute> trainingSet = new ArrayList<Attribute>(dataSet);

for(Attribute att : trainingSet) {
  att.GetData().clear();  // At this point all the data in dataSet are cleared,too.
}
...
</code>```

Attribute.java

```<code>public class Attribute
{
  private String name;
  private ArrayList<String> branchNames = new ArrayList<String>();
  private ArrayList<String> data = new ArrayList<String>();
  private ArrayList<Branch> branches = new ArrayList<Branch>();
  private HashMap<String, Integer> classes = new HashMap<String, Integer>();
  private ID3Algorithm id3;
  private Leaf leaf = null;

  public ArrayList<String> GetData() { return data; }

  public Attribute(String attribName, ArrayList<String> attribBranchNames, ArrayList<String> attribData, ID3Algorithm algo) {
    name = attribName;
    branchNames = attribBranchNames;
    data = attribData;
    id3 = algo;
  }
  ...
}
</code>```

答:
When you are assigning a value to trainingSet

```<code>ArrayList<Attribute> trainingSet = new ArrayList<Attribute>(dataSet);
</code>```

You are only passing the references for the existing attributes into a new list.  It is not a new list of different attribute objects.  The first link you post, describes this process in detail. I would re-read it in depth.(The first example is a shallow copy)

http://javarevisited.blogspot.gr/2014/03/how-to-clone-collection-in-java-deep-copy-vs-shallow.html#axzz4ybComIhC

So when you call

```<code>att.GetData().clear();
</code>```

You are clearing the orginal attribute objects data (which dataset also references)

Try creating new Attribute objects and assigning new data to each(copied from the orginal) then adding those to your trainingSet list.

Body:
I have a problem to deep copy an ArrayList containing Attribute objects. After I have copied the ArrayList dataSet in a new one called trainingSet, I am trying to clear (of the trainingSet) all the content of the internal ArrayList of the Attribute called data. When I do so all the same content of the the ArrayList dataSet (data of dataSet) gets cleared, too. So in that case I have tried to deep copy all the content of the original list to the new one using the below tuts:

http://javarevisited.blogspot.gr/2014/03/how-to-clone-collection-in-java-deep-copy-vs-shallow.html#axzz4ybComIhC

https://beginnersbook.com/2013/12/how-to-clone-an-arraylist-to-another-arraylist/

How to make a deep copy of Java ArrayList

but I got the same behavior. So can someone please tell me how I can fix this problem and where the wrong thinking is?

Thank you for help.

ID3Algorithm.java

...
ArrayList<Attribute> dataSet = new ArrayList<dataSet>();
ArrayList<Attribute> trainingSet = new ArrayList<Attribute>(dataSet);

for(Attribute att : trainingSet) {
  att.GetData().clear();  // At this point all the data in dataSet are cleared,too.
}
...

Attribute.java

public class Attribute
{
  private String name;
  private ArrayList<String> branchNames = new ArrayList<String>();
  private ArrayList<String> data = new ArrayList<String>();
  private ArrayList<Branch> branches = new ArrayList<Branch>();
  private HashMap<String, Integer> classes = new HashMap<String, Integer>();
  private ID3Algorithm id3;
  private Leaf leaf = null;

  public ArrayList<String> GetData() { return data; }

  public Attribute(String attribName, ArrayList<String> attribBranchNames, ArrayList<String> attribData, ID3Algorithm algo) {
    name = attribName;
    branchNames = attribBranchNames;
    data = attribData;
    id3 = algo;
  }
  ...
}

Body:
When you are assigning a value to trainingSet

ArrayList<Attribute> trainingSet = new ArrayList<Attribute>(dataSet);

You are only passing the references for the existing attributes into a new list.  It is not a new list of different attribute objects.  The first link you post, describes this process in detail. I would re-read it in depth.(The first example is a shallow copy)

http://javarevisited.blogspot.gr/2014/03/how-to-clone-collection-in-java-deep-copy-vs-shallow.html#axzz4ybComIhC

So when you call

att.GetData().clear();

You are clearing the orginal attribute objects data (which dataset also references)

Try creating new Attribute objects and assigning new data to each(copied from the orginal) then adding those to your trainingSet list.


问:
Recyclerview updating all viewholders
I have a recyclerview that has multiple view types. Basically, onclick button, I want to loop through all of the recyclerview's children (including viewholders not visible on the screen) and save it to Firebase. Then later on, I want to grab that information from Firebase and repopulate my recyclerview with that data. How would I go about this? My issue is that calling getChildCount() on recyclerview only gets the visible children on the screen. However, I need all children. Am I going about this the right way? Or should I be populating my viewholders with data as it is being shown on the screen?

Code for clarification

This is what I'm using to get the data so that I can insert it into Firebase

```<code>int numberOfViews = displayWorkoutAdapter.rowTypeList.size() - 1;
                                    Log.d("numberOfViews", String.format("%s", numberOfViews));
                                    for (int a = 0; a < numberOfViews; a++) {
                                        RowType rowType = displayWorkoutAdapter.rowTypeList.get(a);
                                        Log.d("rowTypeClass", rowType.getClass().toString());

                                        if (rowType.getClass() == ExerciseModel.class) {
                                            ExerciseModel exerciseModel = (ExerciseModel) rowType;
                                            String exerciseString = exerciseModel.getExercise();
                                            String weightString = exerciseModel.getWeight();
                                            String setString = exerciseModel.getSets();
                                            String repsString = exerciseModel.getReps();
                                            Log.d("exerciseString", exerciseString);

                                            insertDataToTable(tableName, exerciseView, null, exerciseString, weightString, setString, repsString, null, null, "0");

                                        }
</code>```

OnBindViewHolder

```<code>    @Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position){

    if(holder instanceof ExerciseRowHolder) {
        ((ExerciseRowHolder) holder).exercise.setText(((ExerciseModel) rowTypeList.get(position)).getExercise());
        ((ExerciseRowHolder) holder).weight.setText(((ExerciseModel) rowTypeList.get(position)).getWeight());
        ((ExerciseRowHolder) holder).set.setText(((ExerciseModel) rowTypeList.get(position)).getSets());
        ((ExerciseRowHolder) holder).rep.setText(((ExerciseModel) rowTypeList.get(position)).getReps());
        ((ExerciseRowHolder) holder).dragHandle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mDragStartListener.onStartDrag(holder);
                }
                return false;
            }
        });
        ((ExerciseRowHolder) holder).exercise.setAdapter(getExerciseAdapter(home.getContext()));
    }
</code>```

ExerciseRowHolder class

```<code>    public static class ExerciseRowHolder extends RecyclerView.ViewHolder{

    public ImageView dragHandle;
    public EditText weight;
    public EditText set;
    public EditText rep;
    public AutoCompleteTextView exercise;
    public ExerciseRowTextListener exerciseRowTextListener;

    public ExerciseRowHolder(View view, ExerciseRowTextListener exerciseRowTextListener){
        super(view);

        dragHandle = view.findViewById(R.id.reorder);
        weight = view.findViewById(R.id.weight);
        set = view.findViewById(R.id.sets);
        rep = view.findViewById(R.id.reps);
        exercise = view.findViewById(R.id.autoCompleteTextView);

    }
}
</code>```

答:
Store your data in adapter instead of viewholder, see: RecyclerView Creating Lists and Cards

onclick button, I want to loop through all of the recyclerview's children (including viewholders not visible on the screen) and save it to Firebase.

To loop through all the recyclerview's data, instead of using recyclerview.getChildCount(), use adapter.getItemCount().

Then later on, I want to grab that information from Firebase and repopulate my recyclerview with that data. How would I go about this?

After you gets all the data from firebase, store your data in your adapter. and then use adapter.notifyDataSetChanged()

Example:

Your adapter:
    public class YourAdapter extends RecyclerView.Adapter {
     private ArrayList mData;

```<code>public AppPickerGridListAdapter(@NonNull Context context, ArrayList<ExerciseModel> apps) {
    mData = apps;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
   // create a new view
    View v = (View) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.your_view_layout, parent, false);
    // set the view's size, margins, paddings and layout parameters
    ...
    ExerciseRowHolder vh = new ExerciseRowHolder(v, exerciseRowHolderListener);
    vh..dragHandle.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mDragStartListener.onStartDrag(holder);
            }
            return false;
        }
    });
    return vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ExerciseModel item = mData.get(position);
    ((ExerciseRowHolder) holder).exercise.setText(item.getExercise());
    ((ExerciseRowHolder) holder).weight.setText(item.getWeight());
    ((ExerciseRowHolder) holder).set.setText(item.getSets());
    ((ExerciseRowHolder) holder).rep.setText(item.getReps());

}

@Override
public int getItemCount() {
    return mData.size();
}

public ExerciseModel getItem(int position) {
   return mData.get(position);
}

public ArrayList<ExerciseModel> getData() {
    return mData;
}

public void setData(ArrayList<ExerciseModel> data) {
   mData = data;
   notifyDataSetChanged();
}
}
</code>```

Your Activity after your save button clicked:

```<code>ArrayList<ExerciseModel> data = mAdapter.getData();
// save this data to firebase
</code>```

After you get your data from firebase:

```<code>ArrayList<ExcerciseModal> data = getFirebaseData();
mAdapter.setData(data);
</code>```

Hope it helps

Title: Recyclerview updating all viewholders

Body:
I have a recyclerview that has multiple view types. Basically, onclick button, I want to loop through all of the recyclerview's children (including viewholders not visible on the screen) and save it to Firebase. Then later on, I want to grab that information from Firebase and repopulate my recyclerview with that data. How would I go about this? My issue is that calling getChildCount() on recyclerview only gets the visible children on the screen. However, I need all children. Am I going about this the right way? Or should I be populating my viewholders with data as it is being shown on the screen?

Code for clarification

This is what I'm using to get the data so that I can insert it into Firebase

int numberOfViews = displayWorkoutAdapter.rowTypeList.size() - 1;
                                    Log.d("numberOfViews", String.format("%s", numberOfViews));
                                    for (int a = 0; a < numberOfViews; a++) {
                                        RowType rowType = displayWorkoutAdapter.rowTypeList.get(a);
                                        Log.d("rowTypeClass", rowType.getClass().toString());

                                        if (rowType.getClass() == ExerciseModel.class) {
                                            ExerciseModel exerciseModel = (ExerciseModel) rowType;
                                            String exerciseString = exerciseModel.getExercise();
                                            String weightString = exerciseModel.getWeight();
                                            String setString = exerciseModel.getSets();
                                            String repsString = exerciseModel.getReps();
                                            Log.d("exerciseString", exerciseString);

                                            insertDataToTable(tableName, exerciseView, null, exerciseString, weightString, setString, repsString, null, null, "0");

                                        }

OnBindViewHolder

    @Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position){

    if(holder instanceof ExerciseRowHolder) {
        ((ExerciseRowHolder) holder).exercise.setText(((ExerciseModel) rowTypeList.get(position)).getExercise());
        ((ExerciseRowHolder) holder).weight.setText(((ExerciseModel) rowTypeList.get(position)).getWeight());
        ((ExerciseRowHolder) holder).set.setText(((ExerciseModel) rowTypeList.get(position)).getSets());
        ((ExerciseRowHolder) holder).rep.setText(((ExerciseModel) rowTypeList.get(position)).getReps());
        ((ExerciseRowHolder) holder).dragHandle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mDragStartListener.onStartDrag(holder);
                }
                return false;
            }
        });
        ((ExerciseRowHolder) holder).exercise.setAdapter(getExerciseAdapter(home.getContext()));
    }

ExerciseRowHolder class

    public static class ExerciseRowHolder extends RecyclerView.ViewHolder{

    public ImageView dragHandle;
    public EditText weight;
    public EditText set;
    public EditText rep;
    public AutoCompleteTextView exercise;
    public ExerciseRowTextListener exerciseRowTextListener;

    public ExerciseRowHolder(View view, ExerciseRowTextListener exerciseRowTextListener){
        super(view);

        dragHandle = view.findViewById(R.id.reorder);
        weight = view.findViewById(R.id.weight);
        set = view.findViewById(R.id.sets);
        rep = view.findViewById(R.id.reps);
        exercise = view.findViewById(R.id.autoCompleteTextView);

    }
}

Body:
Store your data in adapter instead of viewholder, see: RecyclerView Creating Lists and Cards

onclick button, I want to loop through all of the recyclerview's children (including viewholders not visible on the screen) and save it to Firebase.

To loop through all the recyclerview's data, instead of using recyclerview.getChildCount(), use adapter.getItemCount().

Then later on, I want to grab that information from Firebase and repopulate my recyclerview with that data. How would I go about this?

After you gets all the data from firebase, store your data in your adapter. and then use adapter.notifyDataSetChanged()

Example:

Your adapter:
    public class YourAdapter extends RecyclerView.Adapter {
     private ArrayList mData;

public AppPickerGridListAdapter(@NonNull Context context, ArrayList<ExerciseModel> apps) {
    mData = apps;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
   // create a new view
    View v = (View) LayoutInflater.from(parent.getContext())
            .inflate(R.layout.your_view_layout, parent, false);
    // set the view's size, margins, paddings and layout parameters
    ...
    ExerciseRowHolder vh = new ExerciseRowHolder(v, exerciseRowHolderListener);
    vh..dragHandle.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mDragStartListener.onStartDrag(holder);
            }
            return false;
        }
    });
    return vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    ExerciseModel item = mData.get(position);
    ((ExerciseRowHolder) holder).exercise.setText(item.getExercise());
    ((ExerciseRowHolder) holder).weight.setText(item.getWeight());
    ((ExerciseRowHolder) holder).set.setText(item.getSets());
    ((ExerciseRowHolder) holder).rep.setText(item.getReps());

}

@Override
public int getItemCount() {
    return mData.size();
}

public ExerciseModel getItem(int position) {
   return mData.get(position);
}

public ArrayList<ExerciseModel> getData() {
    return mData;
}

public void setData(ArrayList<ExerciseModel> data) {
   mData = data;
   notifyDataSetChanged();
}
}

Your Activity after your save button clicked:

ArrayList<ExerciseModel> data = mAdapter.getData();
// save this data to firebase

After you get your data from firebase:

ArrayList<ExcerciseModal> data = getFirebaseData();
mAdapter.setData(data);

Hope it helps


问:
Large eCommerce site: Is it time for HTML5?
I currently work for a large company and I design for their high-traffic ecommerce website. We support tens-of-thousands of users across a variety of browsers. Our current browser stats point to most people using either Firefox 3+ and IE8. There are about 5% of users still on IE6.

Is it time to start coding for the future and impliment HTML5 across the site? Is it a responsible thing to do or should I wait a year for people to upgrade to better supporting browsers?

Thank you.

答:
IE8 doesnt support most of HTML5.
There are libraries you can use to make it more HTML5 aware; but for a large production site I think your better of waiting a year.</p>

ContentLicense: CC BY-SA 2.5


问:
Using Graph API to get reactions count for posts in feed
I am trying to use Facebook's graph API to access every post in a group's feed, along with the number of reactions of each type, for every post.

When I try with just one reaction type, it works fine:

```<code>[GROUP_ID]/feed/?fields=message,from,created_time,updated_time,reactions.type(LOVE).limit(0).summary(total_count)&limit=1
</code>```

However, when I add multiple reaction types, I receive an error.

```<code>[GROUP_ID]/feed?fields=message,from,created_time,updated_time,reactions.type(LOVE).limit(0).summary(total_count),reactions.type(WOW).limit(0).summary(total_count)&limit=1
</code>```

gives me:

```<code>{
  "error": {
    "message": "Syntax error \"Field reactions specified more than once. This is only possible before version 2.1\" at character 139: message,from,created_time,updated_time,reactions.type(LOVE).limit(0).summary(total_count),reactions.type(WOW).limit(0).summary(total_count)",
    "type": "OAuthException",
    "code": 2500,
    "fbtrace_id": "GzMCG2dRioK"
  }
}
</code>```

I followed the syntax in this post, however it seems to only work when trying to access reactions for a single post, not for every post in a feed. Is the only option to use the API to grab the post ID's for every post in the feed, and then make individual calls on every post?

答:
You can get around the aliasing issue, and still receive what you need, by asking for the following:

```<code>    insights.metric(post_reactions_by_type_total).period(lifetime)
</code>```

(I found it here: Getting Facebook Post all Reactions Count in single Graph API request)

Body:
I am trying to use Facebook's graph API to access every post in a group's feed, along with the number of reactions of each type, for every post.

When I try with just one reaction type, it works fine:

[GROUP_ID]/feed/?fields=message,from,created_time,updated_time,reactions.type(LOVE).limit(0).summary(total_count)&limit=1

However, when I add multiple reaction types, I receive an error.

[GROUP_ID]/feed?fields=message,from,created_time,updated_time,reactions.type(LOVE).limit(0).summary(total_count),reactions.type(WOW).limit(0).summary(total_count)&limit=1

gives me:

{
  "error": {
    "message": "Syntax error \"Field reactions specified more than once. This is only possible before version 2.1\" at character 139: message,from,created_time,updated_time,reactions.type(LOVE).limit(0).summary(total_count),reactions.type(WOW).limit(0).summary(total_count)",
    "type": "OAuthException",
    "code": 2500,
    "fbtrace_id": "GzMCG2dRioK"
  }
}

I followed the syntax in this post, however it seems to only work when trying to access reactions for a single post, not for every post in a feed. Is the only option to use the API to grab the post ID's for every post in the feed, and then make individual calls on every post?

Body:
You can get around the aliasing issue, and still receive what you need, by asking for the following:

    insights.metric(post_reactions_by_type_total).period(lifetime)

(I found it here: Getting Facebook Post all Reactions Count in single Graph API request)


问:
Ramda: replace NULL values in json array
We have a json array that has the form:

```<code>[
{id: 123, name: 'abc', symbol: 'xyz'},
{id: 456, name: 'def', symbol: null},
...
]
</code>```

We are looking for a Ramda transformation that will replace all instances where the 'symbol' property is NULL, with a simple '' (empty string). Any ideas about how this can be done without getting into a forEach or for...next loop?

答:
How about this?</p>

```<code>R.map(({ symbol, ...otherProps }) => ({ ...otherProps, symbol: symbol || '' }))(arr);
</code>```

Body:
We have a json array that has the form:

[
{id: 123, name: 'abc', symbol: 'xyz'},
{id: 456, name: 'def', symbol: null},
...
]

We are looking for a Ramda transformation that will replace all instances where the 'symbol' property is NULL, with a simple '' (empty string). Any ideas about how this can be done without getting into a forEach or for...next loop?

Body:
How about this?

R.map(({ symbol, ...otherProps }) => ({ ...otherProps, symbol: symbol || '' }))(arr);


问:
PHP Traits: How to circumvenient constructors or force them to be called?
Have a look at the following trait:

```<code>trait PrimaryModelRest {

    use RestController;

    protected $primaryModel;

    public function __construct() {
        $mc = $this->getPrimaryModelClass();

        try {
            $this->primaryModel = new $mc();
            if(!($this->primaryModel instanceof Model)) {
                throw new ClassNotFoundException("Primary Model fatal exception: The given Class is not an instance of Illuminate\Database\Eloquent\Model");
            }
        } catch (Exception $e) {
            throw new WrongImplementationException("Primary Model Exception: Class not found.");
        }
    }

    /**
     * @return string: Classname of the primary model.
     */
    public abstract function getPrimaryModelClass();

    // various functions here

}
</code>```

As you can see the trait makes sure that the using class holds a certain model instance and it implements certain methods. This works as long as the implementing class does not override the constructor.

So here is my question: I want to make sure that either the constructor is called or a better solution, such that I can instantiate this model on initialization.

Please make in answer which respects Multiple inheritance as well es Multi-Level inheritance.

答:
I think you are trying to make the trait do a job it is not designed for.

Traits are not a form of multiple inheritance, but rather "horizontal reuse" - they're often described as "compiler-assisted copy-and-paste". As such, the job of a trait is to provide some code, so that you don't have to copy it into the class manually. The only relationship it has is with the class where the use statement occurs, where the code is "pasted". To aid in this role, it can make some basic requirements of that target class, but after that, the trait takes no part in inheritance.

In your example, you are concerned that a sub-class might try to access $primaryModel without running the constructor code which initialises it, and you are trying to use the trait to enforce that; but this is not actually the trait's responsibility.

The following definitions of class Sub are completely equivalent:

```<code>trait Test {
    public function foo() {
        echo 'Hello, World!';
    }
}
class ParentWithTrait {
    use Test;
}
class Sub inherits ParentWithTrait {
}
</code>```

vs:

```<code>class ParentWithMethodDefinition {
    public function foo() {
        echo 'Hello, World!';
    }
}
class Sub inherits ParentWithMethodDefinition {
}
</code>```

In either case, class Sub could have its own definition of foo(), and by-pass the logic you'd written in the parent class.

The only contract that can prevent that is the final keyword, which in your case would mean marking your constructor as final. You can then provide an extension point that can be overridden for sub-classes to add their own initialisation:

```<code>class Base {
    final public function __construct() {
         important_things(); // Always run this!
         $this->onConstruct(); // Extension point
    }
    protected function onConstruct() {
         // empty default definition
    }
}
class Sub {
    protected function onConstruct() {
         stuff_for_sub(); // Runs after mandatory important_things()
    }
}
</code>```

A trait can also mark its constructor as final, but this is part of the code being pasted, not a requirement on the class using the trait. You could actually use a trait with a constructor, but then write a new constructor as well, and it would mask the trait's version completely:

```<code>trait Test {
    final public function __construct() {
        echo "Trait Constructor";
    }
}
class Noisy {
    use Test;
}
class Silent {
    use Test;
    public function __construct() {
        // Nothing
    }
}
</code>```

As far as the trait is concerned, this is like buying a bottle of beer and pouring it down the sink: you asked for its code and didn't use it, but that's your problem.

Crucially, though, you can also alias the methods of the trait, creating a new method with the same code but a different name and/or a different visibility. This means you can mix in code from traits which declare constructors, and use that code in a more complex constructor, or somewhere else in the class altogether.

The target class might also use the "final + hook" pattern:

```<code>trait TestOne {
    final public function __construct() {
        echo "Trait TestOne Constructor\n";
    }
}
trait TestTwo {
    final public function __construct() {
        echo "Trait TestTwo Constructor\n";
    }
}
class Mixed {
    final public function __construct() {
        echo "Beginning\n";
        $this->testOneConstructor();
        echo "Middle\n";
        $this->testTwoConstructor();
        echo "After Traits\n";
        $this->onConstruct();
        echo "After Sub-Class Hook\n";
    }
    use TestOne { __construct as private testOneConstructor; }
    use TestTwo { __construct as private testTwoConstructor; }

    protected function onConstruct() {
        echo "Default hook\n";
    }
}
class ChildOfMixed extends Mixed {
    protected function onConstruct() {
        echo "Child hook\n";
    }
}
</code>```

The trait hasn't forced the Mixed class to implement this pattern, but it has enabled it, in keeping with its purpose of facilitating code reuse.

Interestingly, the below code doesn't work, because the as keyword adds an alias, rather than renaming the normal method, so this ends up trying to override the final constructor from Mixed:

```<code>class ChildOfMixed extends Mixed {
    use TestTwo { __construct as private testTwoConstructor; }

    protected function onConstruct() {
        $this->testTwoConstructor();
        echo "Child hook\n";
    }
}
</code>```

Body:
Have a look at the following trait:

trait PrimaryModelRest {

    use RestController;

    protected $primaryModel;

    public function __construct() {
        $mc = $this->getPrimaryModelClass();

        try {
            $this->primaryModel = new $mc();
            if(!($this->primaryModel instanceof Model)) {
                throw new ClassNotFoundException("Primary Model fatal exception: The given Class is not an instance of Illuminate\Database\Eloquent\Model");
            }
        } catch (Exception $e) {
            throw new WrongImplementationException("Primary Model Exception: Class not found.");
        }
    }

    /**
     * @return string: Classname of the primary model.
     */
    public abstract function getPrimaryModelClass();

    // various functions here

}

As you can see the trait makes sure that the using class holds a certain model instance and it implements certain methods. This works as long as the implementing class does not override the constructor.

So here is my question: I want to make sure that either the constructor is called or a better solution, such that I can instantiate this model on initialization.

Please make in answer which respects Multiple inheritance as well es Multi-Level inheritance.

Body:
I think you are trying to make the trait do a job it is not designed for.

Traits are not a form of multiple inheritance, but rather "horizontal reuse" - they're often described as "compiler-assisted copy-and-paste". As such, the job of a trait is to provide some code, so that you don't have to copy it into the class manually. The only relationship it has is with the class where the use statement occurs, where the code is "pasted". To aid in this role, it can make some basic requirements of that target class, but after that, the trait takes no part in inheritance.

In your example, you are concerned that a sub-class might try to access $primaryModel without running the constructor code which initialises it, and you are trying to use the trait to enforce that; but this is not actually the trait's responsibility.

The following definitions of class Sub are completely equivalent:

trait Test {
    public function foo() {
        echo 'Hello, World!';
    }
}
class ParentWithTrait {
    use Test;
}
class Sub inherits ParentWithTrait {
}

vs:

class ParentWithMethodDefinition {
    public function foo() {
        echo 'Hello, World!';
    }
}
class Sub inherits ParentWithMethodDefinition {
}

In either case, class Sub could have its own definition of foo(), and by-pass the logic you'd written in the parent class.

The only contract that can prevent that is the final keyword, which in your case would mean marking your constructor as final. You can then provide an extension point that can be overridden for sub-classes to add their own initialisation:

class Base {
    final public function __construct() {
         important_things(); // Always run this!
         $this->onConstruct(); // Extension point
    }
    protected function onConstruct() {
         // empty default definition
    }
}
class Sub {
    protected function onConstruct() {
         stuff_for_sub(); // Runs after mandatory important_things()
    }
}

A trait can also mark its constructor as final, but this is part of the code being pasted, not a requirement on the class using the trait. You could actually use a trait with a constructor, but then write a new constructor as well, and it would mask the trait's version completely:

trait Test {
    final public function __construct() {
        echo "Trait Constructor";
    }
}
class Noisy {
    use Test;
}
class Silent {
    use Test;
    public function __construct() {
        // Nothing
    }
}

As far as the trait is concerned, this is like buying a bottle of beer and pouring it down the sink: you asked for its code and didn't use it, but that's your problem.

Crucially, though, you can also alias the methods of the trait, creating a new method with the same code but a different name and/or a different visibility. This means you can mix in code from traits which declare constructors, and use that code in a more complex constructor, or somewhere else in the class altogether.

The target class might also use the "final + hook" pattern:

trait TestOne {
    final public function __construct() {
        echo "Trait TestOne Constructor\n";
    }
}
trait TestTwo {
    final public function __construct() {
        echo "Trait TestTwo Constructor\n";
    }
}
class Mixed {
    final public function __construct() {
        echo "Beginning\n";
        $this->testOneConstructor();
        echo "Middle\n";
        $this->testTwoConstructor();
        echo "After Traits\n";
        $this->onConstruct();
        echo "After Sub-Class Hook\n";
    }
    use TestOne { __construct as private testOneConstructor; }
    use TestTwo { __construct as private testTwoConstructor; }

    protected function onConstruct() {
        echo "Default hook\n";
    }
}
class ChildOfMixed extends Mixed {
    protected function onConstruct() {
        echo "Child hook\n";
    }
}

The trait hasn't forced the Mixed class to implement this pattern, but it has enabled it, in keeping with its purpose of facilitating code reuse.

Interestingly, the below code doesn't work, because the as keyword adds an alias, rather than renaming the normal method, so this ends up trying to override the final constructor from Mixed:

class ChildOfMixed extends Mixed {
    use TestTwo { __construct as private testTwoConstructor; }

    protected function onConstruct() {
        $this->testTwoConstructor();
        echo "Child hook\n";
    }
}


问:
Accessing a Dictionary.Keys Key through a numeric index
I'm using a Dictionary<string, int> where the int is a count of the key.

Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:

```<code>int LastCount = mydict[mydict.keys[mydict.keys.Count]];
</code>```

does not work, because Dictionary.Keys does not implement a []-indexer.

I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?

答:
As @Falanwe points out in a comment, doing something like this is incorrect:

```<code>int LastCount = mydict.Keys.ElementAt(mydict.Count -1);
</code>```

You should not depend on the order of keys in a Dictionary. If you need ordering, you should use an OrderedDictionary, as suggested in this answer. The other answers on this page are interesting as well.

Body:
I'm using a Dictionary<string, int> where the int is a count of the key.

Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:

int LastCount = mydict[mydict.keys[mydict.keys.Count]];

does not work, because Dictionary.Keys does not implement a []-indexer.

I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?

Body:
As @Falanwe points out in a comment, doing something like this is incorrect:

int LastCount = mydict.Keys.ElementAt(mydict.Count -1);

You should not depend on the order of keys in a Dictionary. If you need ordering, you should use an OrderedDictionary, as suggested in this answer. The other answers on this page are interesting as well.


问:
How to read the data in a razor variable , assigned by a checkbox from a controller
My View has a list of rows for Edit , and each row has multiple checkbox . So I want to index each checkbox value with its corresponding row index.
For this I have in view :

```<code>List<string> FilterIds =new List<string>();
</code>```

.
.
.

```<code><td width="200px">
                        <div class="form-group">
                            <div class=" text-left">Apply Filter(s)</div>
                            <div class="col-md-10">

                                    @foreach (var item in ViewBag.Filters)
                                    {

                                    <input type="checkbox" value="@item.FilterId" name="@FilterIds"/>@item.FilterId
                                    <text> </text>
                                       //FilterId[i] = FilterIds;

                                    }
</code>```

And my controller looks like this :

```<code>public ActionResult Edit([Bind(Include = "Conf_ActionTypeCTAMeta_V1_Id,Conf_CTAId,Conf_Clicklistid,ApprovedBy,DateApproved,EditedBy,DateEdited,Conf_TrackingActionTypeUnique_Id,ConfMarketid,MarketFilterId")] Conf_ActionTypeCTAMeta_V1[] conf_ActionTypeCTAMeta_V1, List<string> FilterIds)
</code>```

Any quick solutions , how I can read the checked value per row ?

答:
In this code has little bit mistake.

when you post data view(html) page to server side that time map with action parameter and html input tag "name attribute". and the name is same then assign value into param.

replace @FilterIds to FilterIds because you define controller in "FilterIds" so.

```<code><input type="checkbox" value="@item.FilterId" name="FilterIds"/>@item.FilterId
</code>```

not need any extra variable to store selected value.

Using html input tag with razor syntax the razor syntax work for display purpose.

Update Action Method :

```<code>public ActionResult Edit([Bind(Include = "Conf_ActionTypeCTAMeta_V1_Id,Conf_CTAId,Conf_Clicklistid,ApprovedBy,DateApproved,EditedBy,DateEdited,Conf_TrackingActionTypeUnique_Id,ConfMarketid,MarketFilterId")] Conf_ActionTypeCTAMeta_V1[] conf_ActionTypeCTAMeta_V1, CheckBox checkBox)
</code>```

Create DTO class like :-

```<code>public class CheckBox
{
  public List<string> FilterIds1 {get;set;}
  public List<string> FilterIds2 {get;set;}
  public List<string> FilterIds3 {get;set;}
}
</code>```

update name attribute

```<code> <input type="checkbox" value="@item.FilterId" name="checkBox.FilterIds1"/>@item.FilterId

    <input type="checkbox" value="@item.FilterId" name="checkBox.FilterIds2"/>@item.FilterId

    <input type="checkbox" value="@item.FilterId" name="checkBox.FilterIds3"/>@item.FilterId
</code>```

if you row generate dynamic then you can use like this:

```<code>public ActionResult Edit([Bind(Include = "Conf_ActionTypeCTAMeta_V1_Id,Conf_CTAId,Conf_Clicklistid,ApprovedBy,DateApproved,EditedBy,DateEdited,Conf_TrackingActionTypeUnique_Id,ConfMarketid,MarketFilterId")] Conf_ActionTypeCTAMeta_V1[] conf_ActionTypeCTAMeta_V1, CheckBox[] checkBox)
</code>```

DTO class is :

```<code>public class CheckBox
    {
      public int Id { set; get; }
      public string Name { set; get; }
      public int index { set; get; }
    }
</code>```

i is a index value

```<code> foreach (var item in ViewBag.Data)
{
    <input type="checkbox" value="@item.Id" name="checkbox[@item.index].Id" id="checkbox[@item.index].Id"/>@item.Name  <br />
    <input type="hidden" value="@item.index"  name="checkbox[@item.index].index"/>
}
</code>```

Body:
My View has a list of rows for Edit , and each row has multiple checkbox . So I want to index each checkbox value with its corresponding row index.
For this I have in view :

List<string> FilterIds =new List<string>();

.
.
.

Apply Filter(s)

                                    @foreach (var item in ViewBag.Filters)
                                    {

                                    <input type="checkbox" value="@item.FilterId" name="@FilterIds"/>@item.FilterId
                                    <text> </text>
                                       //FilterId[i] = FilterIds;

                                    }

And my controller looks like this :

public ActionResult Edit([Bind(Include = "Conf_ActionTypeCTAMeta_V1_Id,Conf_CTAId,Conf_Clicklistid,ApprovedBy,DateApproved,EditedBy,DateEdited,Conf_TrackingActionTypeUnique_Id,ConfMarketid,MarketFilterId")] Conf_ActionTypeCTAMeta_V1[] conf_ActionTypeCTAMeta_V1, List<string> FilterIds)

Any quick solutions , how I can read the checked value per row ?

Body:
In this code has little bit mistake.

when you post data view(html) page to server side that time map with action parameter and html input tag "name attribute". and the name is same then assign value into param.

replace @FilterIds to FilterIds because you define controller in "FilterIds" so.

<input type="checkbox" value="@item.FilterId" name="FilterIds"/>@item.FilterId

not need any extra variable to store selected value.

Using html input tag with razor syntax the razor syntax work for display purpose.

Update Action Method :

public ActionResult Edit([Bind(Include = "Conf_ActionTypeCTAMeta_V1_Id,Conf_CTAId,Conf_Clicklistid,ApprovedBy,DateApproved,EditedBy,DateEdited,Conf_TrackingActionTypeUnique_Id,ConfMarketid,MarketFilterId")] Conf_ActionTypeCTAMeta_V1[] conf_ActionTypeCTAMeta_V1, CheckBox checkBox)

Create DTO class like :-

public class CheckBox
{
  public List<string> FilterIds1 {get;set;}
  public List<string> FilterIds2 {get;set;}
  public List<string> FilterIds3 {get;set;}
}

update name attribute

 <input type="checkbox" value="@item.FilterId" name="checkBox.FilterIds1"/>@item.FilterId

    <input type="checkbox" value="@item.FilterId" name="checkBox.FilterIds2"/>@item.FilterId

    <input type="checkbox" value="@item.FilterId" name="checkBox.FilterIds3"/>@item.FilterId

if you row generate dynamic then you can use like this:

public ActionResult Edit([Bind(Include = "Conf_ActionTypeCTAMeta_V1_Id,Conf_CTAId,Conf_Clicklistid,ApprovedBy,DateApproved,EditedBy,DateEdited,Conf_TrackingActionTypeUnique_Id,ConfMarketid,MarketFilterId")] Conf_ActionTypeCTAMeta_V1[] conf_ActionTypeCTAMeta_V1, CheckBox[] checkBox)

DTO class is :

public class CheckBox
    {
      public int Id { set; get; }
      public string Name { set; get; }
      public int index { set; get; }
    }

i is a index value

 foreach (var item in ViewBag.Data)
{
    <input type="checkbox" value="@item.Id" name="checkbox[@item.index].Id" id="checkbox[@item.index].Id"/>@item.Name  <br />
    <input type="hidden" value="@item.index"  name="checkbox[@item.index].index"/>
}


问:
Checking if 2 variables out 3 are equal in python
I am making a code where three dice are rolled and if all three dice are equal the values are added. If 2 of the dice are equal then the 2 equal dice values are added and the odd dice value is subtracted from the sum.

This is my code so far

```<code>import random

d1 = random.randint(1,6)
d2 = random.randint(1,6)
d3 = random.randint(1,6)

print(d1)
print(d2)
print(d3)

if d1 == d2 and d2 == d3:
    score = d1 + d2 + d3
elif d1 == d2 or d1 == d3 or d2 == d3:
</code>```

Now I don't know how I would find out which of the 2 dice are equal to be able to add them together. How would I do this?

答:
Using sets is probably the most elegant solution to determine if you have a repeat, but it does not tell you which element repeats.

You could maintain all your dice in a list:

```<code>d = [random.randint(1,6) for _ in range(3)]
</code>```

You can sort the list. If all the elements are the same, the first and last value will match. If there is a repeat, the middle element will match either the first or the last one:

```<code>d.sort()
if d[0] == d[2]:
    score = sum(d)
elif d[0] == d[1]:
    score = d[0] + d[1] - d[2]
elif d[1] == d[2]:
    score = d[1] + d[2] - d[0]
else:
    score = 0
</code>```

Body:
I am making a code where three dice are rolled and if all three dice are equal the values are added. If 2 of the dice are equal then the 2 equal dice values are added and the odd dice value is subtracted from the sum.

This is my code so far

import random

d1 = random.randint(1,6)
d2 = random.randint(1,6)
d3 = random.randint(1,6)

print(d1)
print(d2)
print(d3)

if d1 == d2 and d2 == d3:
    score = d1 + d2 + d3
elif d1 == d2 or d1 == d3 or d2 == d3:

Now I don't know how I would find out which of the 2 dice are equal to be able to add them together. How would I do this?

Body:
Using sets is probably the most elegant solution to determine if you have a repeat, but it does not tell you which element repeats.

You could maintain all your dice in a list:

d = [random.randint(1,6) for _ in range(3)]

You can sort the list. If all the elements are the same, the first and last value will match. If there is a repeat, the middle element will match either the first or the last one:

d.sort()
if d[0] == d[2]:
    score = sum(d)
elif d[0] == d[1]:
    score = d[0] + d[1] - d[2]
elif d[1] == d[2]:
    score = d[1] + d[2] - d[0]
else:
    score = 0


问:
Reliable way to get all user directories?
After much googling, I'm still not finding what I'm looking for.

I simply want to find the names of every user account on my machine. For example, in the C:\Users\ directory, there will be directories for every user on the machine. There must be a more elegant way than simply regexing the usernames from the users directory, though.

These are not the same names that are shown in Win32_UserAccount WMI query. When I execute:

```<code>Get-WMIObject -query 'SELECT * from Win32_UserAccount'
</code>```

... I get names such as 'Administrator', 'Default Account', etc. These are not the names I am looking for. I want the names that are shown in C:\Users\

What is the most programmatic way to get the names of all the users in the c:\Users folder?

Thanks!

答: Ended up just gathering all directories in the c:\users\ directory and regexing out the name of the folders in that directory.</p>

Body:
After much googling, I'm still not finding what I'm looking for.

I simply want to find the names of every user account on my machine. For example, in the C:\Users\ directory, there will be directories for every user on the machine. There must be a more elegant way than simply regexing the usernames from the users directory, though.

These are not the same names that are shown in Win32_UserAccount WMI query. When I execute:

Get-WMIObject -query 'SELECT * from Win32_UserAccount'

... I get names such as 'Administrator', 'Default Account', etc. These are not the names I am looking for. I want the names that are shown in C:\Users\

What is the most programmatic way to get the names of all the users in the c:\Users folder?

Thanks!