问:
LUIS response throws error with Bad Request
I have started integrating Luis into my BOT. The LUIS query works great in a browser, but when invoked through code, the response from LUIS GetResult throws an error.

The LUIS query is here

Source code of the dialog:

```<code> [LuisModel("2d3e39d8-632a-4e00-bf2f-d98ea4b2ed79&", "subscription Key")]
    [Serializable]
    public class SupportDialog : LuisDialog<object>
    {

        [LuisIntent("")]
        public async Task None(IDialogContext context, LuisResult result)
        {
            await context.PostAsync("Sorry, I dont understand what you need");
            context.Wait(MessageReceived);
        }

        [LuisIntent("OrderStatus")]
        public async Task OrderStatus(IDialogContext context, LuisResult result)
        {
            var returnMsg = "You wanted to check the order status";
            var orderStatus = "Dispatched";
            var deliveryDate = DateTime.Now.AddDays(3);

            var entities = new List<EntityRecommendation>(result.Entities);
            if(entities.Any((entity)=> entity.Type == "Order"))
            {
                var orderEntity = entities.Where((entity) => entity.Type == "Order").FirstOrDefault();
                var resolutionStr = orderEntity.Resolution.FirstOrDefault().Value ?? null;
                if(!string.IsNullOrEmpty(resolutionStr))
                {
                    returnMsg = "Your order " + resolutionStr + " status is " + orderStatus + " and expected to deliver by " + deliveryDate.Humanize();
                }
            }

            await context.PostAsync(returnMsg);
            context.Wait(MessageReceived);
        }

    }
</code>```

MessageController Source Code:

```<code> internal static IDialog<object> MakeRoot()
        {
            return Chain.From(() => new SupportDialog());
        }

        [ResponseType(typeof(void))]
        public virtual async Task<HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity != null)
            {
                // one of these will have an interface and process it
                switch (activity.GetActivityType())
                {
                    case ActivityTypes.Message:
                        await Conversation.SendAsync(activity, MakeRoot);
                        break;

                    case ActivityTypes.ConversationUpdate:
                    case ActivityTypes.ContactRelationUpdate:
                    case ActivityTypes.Typing:
                    case ActivityTypes.DeleteUserData:
                    default:
                        Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
                        break;
                }
            }
            return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
        }
</code>```

I get the following error (partial extract only) in my BOT Emulator when trying to debug:

```<code>> Exception: System.Net.Http.HttpRequestException: Response status code
> does not indicate success: 400 (Bad Request).\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Luis.LuisService.<Microsoft-Bot-Builder-Luis-ILuisService-QueryAsync>d__4.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Luis.Extensions.<QueryAsync>d__3.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.LuisDialog`1.<MessageReceived>d__7.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__4.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__7.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__13.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
> at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter<T>.GetResult()\r\n
> at
> Microsoft.Bot.Builder.Dialogs.Chain.FromDialog`1.<ResumeAsync>d__3.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__4.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__7.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__13.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
> at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter<T>.GetResult()\r\n
> at
> Microsoft.Bot.Builder.Dialogs.Chain.LoopDialog`1.<ResumeAsync>d__3.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__4.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__7.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__13.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IDialogStack-PollAsync>d__19.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__21`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.ReactiveDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.LocalizedDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.ScoringDialogTask`1.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__6`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__6`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
> at
> Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__6`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.SerializingDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUserTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5`1.MoveNext()
</code>```

答:
This below error may also come; when you publish LUIS app under Staging slot

```<code>Response status code does not indicate success: 400 (Bad Request)
</code>```

So always publish your LUIS app under Production slot

And obviously you have to remove the ampersand(&) sign from your LuisModel ID.

Body:
I have started integrating Luis into my BOT. The LUIS query works great in a browser, but when invoked through code, the response from LUIS GetResult throws an error.

The LUIS query is here

Source code of the dialog:

 [LuisModel("2d3e39d8-632a-4e00-bf2f-d98ea4b2ed79&", "subscription Key")]
    [Serializable]
    public class SupportDialog : LuisDialog<object>
    {

        [LuisIntent("")]
        public async Task None(IDialogContext context, LuisResult result)
        {
            await context.PostAsync("Sorry, I dont understand what you need");
            context.Wait(MessageReceived);
        }

        [LuisIntent("OrderStatus")]
        public async Task OrderStatus(IDialogContext context, LuisResult result)
        {
            var returnMsg = "You wanted to check the order status";
            var orderStatus = "Dispatched";
            var deliveryDate = DateTime.Now.AddDays(3);

            var entities = new List<EntityRecommendation>(result.Entities);
            if(entities.Any((entity)=> entity.Type == "Order"))
            {
                var orderEntity = entities.Where((entity) => entity.Type == "Order").FirstOrDefault();
                var resolutionStr = orderEntity.Resolution.FirstOrDefault().Value ?? null;
                if(!string.IsNullOrEmpty(resolutionStr))
                {
                    returnMsg = "Your order " + resolutionStr + " status is " + orderStatus + " and expected to deliver by " + deliveryDate.Humanize();
                }
            }

            await context.PostAsync(returnMsg);
            context.Wait(MessageReceived);
        }

    }

MessageController Source Code:

 internal static IDialog<object> MakeRoot()
        {
            return Chain.From(() => new SupportDialog());
        }

        [ResponseType(typeof(void))]
        public virtual async Task<HttpResponseMessage> Post([FromBody] Activity activity)
        {
            if (activity != null)
            {
                // one of these will have an interface and process it
                switch (activity.GetActivityType())
                {
                    case ActivityTypes.Message:
                        await Conversation.SendAsync(activity, MakeRoot);
                        break;

                    case ActivityTypes.ConversationUpdate:
                    case ActivityTypes.ContactRelationUpdate:
                    case ActivityTypes.Typing:
                    case ActivityTypes.DeleteUserData:
                    default:
                        Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
                        break;
                }
            }
            return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
        }

I get the following error (partial extract only) in my BOT Emulator when trying to debug:

> Exception: System.Net.Http.HttpRequestException: Response status code
> does not indicate success: 400 (Bad Request).\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Luis.LuisService.<Microsoft-Bot-Builder-Luis-ILuisService-QueryAsync>d__4.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Luis.Extensions.<QueryAsync>d__3.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.LuisDialog`1.<MessageReceived>d__7.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__4.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__7.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__13.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
> at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter<T>.GetResult()\r\n
> at
> Microsoft.Bot.Builder.Dialogs.Chain.FromDialog`1.<ResumeAsync>d__3.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__4.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__7.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__13.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
> at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.Microsoft.Bot.Builder.Internals.Fibers.IAwaiter<T>.GetResult()\r\n
> at
> Microsoft.Bot.Builder.Dialogs.Chain.LoopDialog`1.<ResumeAsync>d__3.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.ThunkResume`1.<Rest>d__4.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Wait`2.<Microsoft-Bot-Builder-Internals-Fibers-IWait<C>-PollAsync>d__19.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Frame`1.<Microsoft-Bot-Builder-Internals-Fibers-IFrameLoop<C>-PollAsync>d__7.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Internals.Fibers.Fiber`1.<Microsoft-Bot-Builder-Internals-Fibers-IFiberLoop<C>-PollAsync>d__13.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IDialogStack-PollAsync>d__19.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.DialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__21`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.ReactiveDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.ExceptionTranslationDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.LocalizedDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__2`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.ScoringDialogTask`1.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__6`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__6`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n
> at
> Microsoft.Bot.Builder.Dialogs.Internals.PersistentDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__6`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.SerializingDialogTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__4`1.MoveNext()\r\n---
> End of stack trace from previous location where exception was thrown
> ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
> task)\r\n   at
> System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at
> Microsoft.Bot.Builder.Dialogs.Internals.PostUnhandledExceptionToUserTask.<Microsoft-Bot-Builder-Dialogs-Internals-IPostToBot-PostAsync>d__5`1.MoveNext()

Body:
This below error may also come; when you publish LUIS app under Staging slot

Response status code does not indicate success: 400 (Bad Request)

So always publish your LUIS app under Production slot

And obviously you have to remove the ampersand(&) sign from your LuisModel ID.


来源: stackexchange

问:
DP approach for the n-puzzle problem
is there a DP approach for the n-puzzle problem

thanks all, appreciate that...

rajan

答:
Dynamic Programming is a technique used to solve problems by reducing difficult cases to simpler cases, recursively, until you reach a case simple enough to solve "by inspection". Therefore, there can only be a sensible DP approach to the n-puzzle problem if, at each stage, you can consider a move which reduces the complexity of the problem.

For instance, if the first "move" in a n-puzzle always made it into an "(n-1)-puzzle" (for some concrete definition of "move", and assuming an (n-1)-puzzle made sense), then you could apply DP, eventually solving the "1-puzzle", and composing back upwards to solve the n-puzzle.

I don't know of any such simplification process for the n-puzzle; and I can't think of one at the moment. However, that doesn't mean one doesn't exist.

ContentLicense: CC BY-SA 2.5

Title: DP approach for the n-puzzle problem


问:
Merge XML documents
I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have document1:

```<code><mapping>
    <key value="assigned">
        <a/>
    </key>
    <whatever attribute="x">
        <k/>
        <j/>
    </whatever>
</mapping>
</code>```

and document2:

```<code><mapping>
    <key value="identity">
        <a/>
        <b/>
    </key>
</mapping>
</code>```

I want to merge the two like this:

```<code><mapping>
    <key value="identity">
        <a/>
        <b/>
    </key>
    <whatever attribute="x">
        <k/>
        <j/>
    </whatever>
</mapping>
</code>```

I prefer Java or XSLT-based solutions, ant will do fine, but if there's an easy way to do that in Rake, Ruby or Python please don't be shy :-)

EDIT: actually I find I'd rather use an automated tool/script, even writing it by myself, because manually merging some 30 XML files is a bit unwieldy... :-(

答:
(also using Oliver's XSLT stlyesheets)

XSLT merge from PowerShell:

```<code>param(
[Parameter(Mandatory = $True)][string]$file1,
[Parameter(Mandatory = $True)][string]$file2,
[Parameter(Mandatory = $True)][string]$path
)

# using only abs paths .. just to be safe
$file1 = Join-Path $(Get-Location) $file1
$file2 = Join-Path $(Get-Location) $file2
$path = Join-Path $(Get-Location) $path

# awesome xsl stylesheet from Oliver Becker
# http://web.archive.org/web/20160502194427/http://www2.informatik.hu-berlin.de/~obecker/XSLT/merge/merge.xslt
$xsltfile = Join-Path $(Get-Location) "merge.xslt"

$XsltSettings = New-Object System.Xml.Xsl.XsltSettings
$XsltSettings.EnableDocumentFunction = 1

$xslt = New-Object System.Xml.Xsl.XslCompiledTransform;
$xslt.Load($xsltfile , $XsltSettings, $(New-Object System.Xml.XmlUrlResolver))

[System.Xml.Xsl.XsltArgumentList]$al = [System.Xml.Xsl.XsltArgumentList]::new()
$al.AddParam("with", "", $file2)
$al.AddParam("replace", "", "true")

[System.Xml.XmlWriter]$xmlwriter = [System.Xml.XmlWriter]::Create($path)
$xslt.Transform($file1, $al, $xmlwriter)
</code>```

Using 'plain ol' Saxon:

```<code>java -jar saxon9he.jar .\FileA.xml .\merge.xslt with=FileB.xml replace=true
</code>```

OwnerDisplayName: Manrico Corazzi

ContentLicense: CC BY-SA 4.0

Title: Merge XML documents

Body:
I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have document1:

<mapping>
    <key value="assigned">

    </key>
    <whatever attribute="x">
        <k/>
        <j/>
    </whatever>
</mapping>

and document2:

<mapping>
    <key value="identity">

    </key>
</mapping>

I want to merge the two like this:

<mapping>
    <key value="identity">

    </key>
    <whatever attribute="x">
        <k/>
        <j/>
    </whatever>
</mapping>

I prefer Java or XSLT-based solutions, ant will do fine, but if there's an easy way to do that in Rake, Ruby or Python please don't be shy :-)

EDIT: actually I find I'd rather use an automated tool/script, even writing it by myself, because manually merging some 30 XML files is a bit unwieldy... :-(

LastEditorDisplayName: Manrico Corazzi

Body:
(also using Oliver's XSLT stlyesheets)

XSLT merge from PowerShell:

param(
[Parameter(Mandatory = $True)][string]$file1,
[Parameter(Mandatory = $True)][string]$file2,
[Parameter(Mandatory = $True)][string]$path
)

# using only abs paths .. just to be safe
$file1 = Join-Path $(Get-Location) $file1
$file2 = Join-Path $(Get-Location) $file2
$path = Join-Path $(Get-Location) $path

# awesome xsl stylesheet from Oliver Becker
# http://web.archive.org/web/20160502194427/http://www2.informatik.hu-berlin.de/~obecker/XSLT/merge/merge.xslt
$xsltfile = Join-Path $(Get-Location) "merge.xslt"

$XsltSettings = New-Object System.Xml.Xsl.XsltSettings
$XsltSettings.EnableDocumentFunction = 1

$xslt = New-Object System.Xml.Xsl.XslCompiledTransform;
$xslt.Load($xsltfile , $XsltSettings, $(New-Object System.Xml.XmlUrlResolver))

[System.Xml.Xsl.XsltArgumentList]$al = [System.Xml.Xsl.XsltArgumentList]::new()
$al.AddParam("with", "", $file2)
$al.AddParam("replace", "", "true")

[System.Xml.XmlWriter]$xmlwriter = [System.Xml.XmlWriter]::Create($path)
$xslt.Transform($file1, $al, $xmlwriter)

Using 'plain ol' Saxon:

java -jar saxon9he.jar .\FileA.xml .\merge.xslt with=FileB.xml replace=true

ContentLicense: CC BY-SA 3.0


问:
Memory Leaks in pop() for A Queue
My pop function does not seem to work as it should.  Basically, my queue has a pointer to the first and last elements.

My pop functions starts by freeing the first element and assigning it to NULL.

Then it uses the pointer curr to get to the next element each time until it find a NULL.

Finally, my the first pointer in my queue gets assigned to prev, which was pointing to the last element before my curr reached null.

```<code>#include <stdlib.h>

struct Queue {
    struct Node* first;
    struct Node* last;
};

struct Node {
    Item val;
    struct Node* next;
};

void initQueue (struct Queue **queue){
    (*queue) = malloc(sizeof(struct Queue));
    (*queue)->first = NULL;
    (*queue)->last = NULL;
}

struct Node* createNewNode(){
    struct Node *newNode;
    newNode = malloc(sizeof(struct Node));
    newNode->next = NULL;

    return newNode;
}

void push (Item val, struct Queue *queue){
    struct Node* newNode = createNewNode();
    newNode->val = val;

    if(queue->first == NULL){
        queue->first = newNode;
        queue->last = newNode;
    }

    else{
        newNode->next = queue->last;
        queue->last = newNode;
    }
}

void pop(struct Queue *queue){

    struct Node* curr = queue->last;
    struct Node* prev = queue->last;

    free(queue->first);
    queue->first = NULL;

    while(curr != NULL){
        prev = curr;
        curr = curr->next;
    }

    queue->first = prev;

}
</code>```

答:
To pop from the front of the list, simply have first point to first->next.

```<code>void pop(struct Queue *queue)
{
    if (NULL != queue->first) {
        struct Node *first = queue->first;
        // Update first ptr
        queue->first = queue->first->next;
        free(first);
        // Only need to update tail if list is empty
        if (NULL == queue->first) {
            queue->last = NULL;
        }
    }
}
</code>```

EDIT
Based on your comment it looks like you aren't seeing what I'm doing, so here's an example.

Assume the queue looks like this:

queue->first

↓

A → B → C → D ← queue->last

First, make a temporary pointer and have it point to queue->first. Then move queue->first so that it points to queue->first->next. The list now looks like:

       queue->first

        ↓

A → B → C → D ← queue->last

↑

first (temp var)

Then, delete the temp var and the list is:

queue->first

↓

B → C → D ← queue->last

EDIT 2 I also notice your push function is incorrect. In a queue, you add new items to the end of the list and take items from the front (FIFO - First In First Out). Like people lining up to see a show. The first person to get there and get in line will be the first to enter the theater. And the last person to arrive goes to the back of the line. So push should be:

```<code>void push (Item val, struct Queue *queue){
    struct Node* newNode = createNewNode();
    newNode->val = val;

    if(queue->first == NULL) {
        queue->first = newNode;
        queue->last = newNode;
    }
    else{
        queue->last->next = newNode;  // Add to END of list
        queue->last = newNode;
    }
}
</code>```

Title: Memory Leaks in pop() for A Queue

Body:
My pop function does not seem to work as it should.  Basically, my queue has a pointer to the first and last elements.

My pop functions starts by freeing the first element and assigning it to NULL.

Then it uses the pointer curr to get to the next element each time until it find a NULL.

Finally, my the first pointer in my queue gets assigned to prev, which was pointing to the last element before my curr reached null.

#include <stdlib.h>

struct Queue {
    struct Node* first;
    struct Node* last;
};

struct Node {
    Item val;
    struct Node* next;
};

void initQueue (struct Queue **queue){
    (*queue) = malloc(sizeof(struct Queue));
    (*queue)->first = NULL;
    (*queue)->last = NULL;
}

struct Node* createNewNode(){
    struct Node *newNode;
    newNode = malloc(sizeof(struct Node));
    newNode->next = NULL;

    return newNode;
}

void push (Item val, struct Queue *queue){
    struct Node* newNode = createNewNode();
    newNode->val = val;

    if(queue->first == NULL){
        queue->first = newNode;
        queue->last = newNode;
    }

    else{
        newNode->next = queue->last;
        queue->last = newNode;
    }
}

void pop(struct Queue *queue){

    struct Node* curr = queue->last;
    struct Node* prev = queue->last;

    free(queue->first);
    queue->first = NULL;

    while(curr != NULL){
        prev = curr;
        curr = curr->next;
    }

    queue->first = prev;

}

Body:
To pop from the front of the list, simply have first point to first->next.

void pop(struct Queue *queue)
{
    if (NULL != queue->first) {
        struct Node *first = queue->first;
        // Update first ptr
        queue->first = queue->first->next;
        free(first);
        // Only need to update tail if list is empty
        if (NULL == queue->first) {
            queue->last = NULL;
        }
    }
}

EDIT
Based on your comment it looks like you aren't seeing what I'm doing, so here's an example.

Assume the queue looks like this:

queue->first

↓

A → B → C → D ← queue->last

First, make a temporary pointer and have it point to queue->first. Then move queue->first so that it points to queue->first->next. The list now looks like:

       queue->first

        ↓

A → B → C → D ← queue->last

↑

first (temp var)

Then, delete the temp var and the list is:

queue->first

↓

B → C → D ← queue->last

EDIT 2 I also notice your push function is incorrect. In a queue, you add new items to the end of the list and take items from the front (FIFO - First In First Out). Like people lining up to see a show. The first person to get there and get in line will be the first to enter the theater. And the last person to arrive goes to the back of the line. So push should be:

void push (Item val, struct Queue *queue){
    struct Node* newNode = createNewNode();
    newNode->val = val;

    if(queue->first == NULL) {
        queue->first = newNode;
        queue->last = newNode;
    }
    else{
        queue->last->next = newNode;  // Add to END of list
        queue->last = newNode;
    }
}


问:
React - does a child component re-mount each time the parent component renders?
In this very basic example I am including the component Bar inside the render function of component Foo. I am observing that the componentDidMount method for Bar is firing each time Foo re-renders - is this the correct behaviour?

```<code>import Bar from './Bar.jsx';

export default class Foo extends Component {
    render() {
        return (
            <Bar />
        );
    }
}
</code>```

Note: I have asked this question to sanity check the expected behaviour, in order to track down a bug.

答:
The children behaviour depends on the parent behaviour.

componentDidMount() is invoked immediately after a component is mounted. The componentDidMount() method of child components is invoked before that of parent components.

If your parent component simply re-renders, it is expected that child components also simply re-render, since componentDidMount() is invoked only once in the component's lifecycle.

Body:
In this very basic example I am including the component Bar inside the render function of component Foo. I am observing that the componentDidMount method for Bar is firing each time Foo re-renders - is this the correct behaviour?

import Bar from './Bar.jsx';

export default class Foo extends Component {
    render() {
        return (
            <Bar />
        );
    }
}

Note: I have asked this question to sanity check the expected behaviour, in order to track down a bug.


问:
how do I exclude tmp files in Sublime "Go to Anything"?
I've tried this but it doesn't seem to work:

```<code>{
    // index_exclude_patterns indicate which files won't be indexed.
    "index_exclude_patterns": ["tmp/*", "*.cache", "*.log"],
}
</code>```

Perhaps I need to reindex? But I don't know how to do that...

答:
Your issue is that the index is used to collect symbols for Goto Definition and has no effect on the list of files that are presented to you when you use Goto Anything. So adding those folders to the list of files to exclude in indexing doesn't stop you from seeing them in the file list.

Goto Anything offers you all of the files that are currently contained in your project (if you're using one) or all open folders, excluding any files that it considers to be binary, so in order to stop files from appearing in the Goto Anything panel you need to either have them removed from the project or considered to be binary.

The folder_exclude_patterns and file_exclude_patterns settings allow you to indicate what folder and file patterns respectively should not be considered part of the project. Extending those settings would remove the files from the sidebar and thus from Goto Anything.

If you want to be able to still see the files in the sidebar but not be offered the ability to jump to them with Goto Anything, you can modify the binary_file_patterns setting. That tells Sublime what files are considered to be binary, which will stop it from showing them in the Goto Anything panel or searching them via Find in Files but will still show them in the sidebar for you to manually open.

folder_exclude_patterns and file_exclude_patterns can be used in your sublime-project file (if you're using one) so that they can be set on a project by project basis. binary_file_patterns only works as a global setting, however.

Either way, you probably want to base your custom settings on the defaults or you may accidentally have files appear in your project that are currently being hidden.

Body:
I've tried this but it doesn't seem to work:

{
    // index_exclude_patterns indicate which files won't be indexed.
    "index_exclude_patterns": ["tmp/*", "*.cache", "*.log"],
}

Perhaps I need to reindex? But I don't know how to do that...


问:
Identify the DataGrid from ItemCommand inside Repeater
I've a DataGrid inside a Repeater. In this DataGrid I've a Button "btnTest". How to identify which (Index of the Repeater) DataGrid from ItemCommand in DataGrid.

ASPX:

```<code><asp:Repeater ID="ProdList" OnItemDataBound="ProdList_ItemDataBound" OnItemCommand="ProdList_ItemCommand" runat="server">
    <ItemTemplate>
        <div style="padding: 5px;">
            <asp:DataGrid ID="dtg" OnItemDataBound="dtg_ItemDataBound" OnItemCommand="dtg_ItemCommand" runat="server" AutoGenerateColumns="False" DataSource='<%# DataBinder.Eval(Container.DataItem, "ProductItems") %>'>
                <Columns>
                    <asp:BoundColumn HeaderText="ProdName" DataField="ProdName"></asp:BoundColumn>
                    <asp:TemplateColumn>
                        <ItemTemplate>
                            <asp:Button ID="btnTest" runat="server" CommandName="Test" Text="Test" />
                        </ItemTemplate>
                    </asp:TemplateColumn>
                </Columns>
            </asp:DataGrid>
            <asp:TextBox ID="txtSearch" runat="server" style="width:250px;" CssClass="txtSearch" autocomplete="off"></asp:TextBox>
            <asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="btnSearch" onclick="btnSearch_Click" />
            <asp:Button ID="btnCheckAvailability" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ProdId") %>' CssClass="button" CommandName="CheckAvailability" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ProdId") %>' />
        </div>
    </ItemTemplate>
</asp:Repeater>
</code>```

ASPX.CS:

```<code>protected void ProdList_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {

    }
}

protected void ProdList_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
{

}

protected void dtg_ItemDataBound(object sender, DataGridItemEventArgs e)
{

}

protected void dtg_ItemCommand(object source, DataGridCommandEventArgs e)
{
    // I want to identify DataGrid here
}
</code>```

Please help me.

答:
You have to navigate up the NamingContainer tree in dtg_ItemCommand.

```<code>//get the current datagrid item from the sender
DataGridItem gridIitem = (DataGridItem)(((Control)e.CommandSource).NamingContainer);

//the index of the griditem if needed
int gridItemIndex = gridIitem.ItemIndex;

//then the datagrid from the underlying datagriditem
DataGrid grid = (DataGrid)gridIitem.NamingContainer;

//then the repeateritem from the underlying datagrid
RepeaterItem repeaterItem = (RepeaterItem)grid.NamingContainer;

//now you can get the index of the repeateritem
int repeaterIndex = repeaterItem.ItemIndex;
</code>```

Body:
I've a DataGrid inside a Repeater. In this DataGrid I've a Button "btnTest". How to identify which (Index of the Repeater) DataGrid from ItemCommand in DataGrid.

ASPX:

<asp:Repeater ID="ProdList" OnItemDataBound="ProdList_ItemDataBound" OnItemCommand="ProdList_ItemCommand" runat="server">
    <ItemTemplate>

            <asp:DataGrid ID="dtg" OnItemDataBound="dtg_ItemDataBound" OnItemCommand="dtg_ItemCommand" runat="server" AutoGenerateColumns="False" DataSource='<%# DataBinder.Eval(Container.DataItem, "ProductItems") %>'>
                <Columns>
                    <asp:BoundColumn HeaderText="ProdName" DataField="ProdName"></asp:BoundColumn>
                    <asp:TemplateColumn>
                        <ItemTemplate>
                            <asp:Button ID="btnTest" runat="server" CommandName="Test" Text="Test" />
                        </ItemTemplate>
                    </asp:TemplateColumn>
                </Columns>
            </asp:DataGrid>
            <asp:TextBox ID="txtSearch" runat="server" style="width:250px;" CssClass="txtSearch" autocomplete="off"></asp:TextBox>
            <asp:Button ID="btnSearch" runat="server" Text="Search" CssClass="btnSearch" onclick="btnSearch_Click" />
            <asp:Button ID="btnCheckAvailability" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ProdId") %>' CssClass="button" CommandName="CheckAvailability" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "ProdId") %>' />

    </ItemTemplate>
</asp:Repeater>

ASPX.CS:

protected void ProdList_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {

    }
}

protected void ProdList_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
{

}

protected void dtg_ItemDataBound(object sender, DataGridItemEventArgs e)
{

}

protected void dtg_ItemCommand(object source, DataGridCommandEventArgs e)
{
    // I want to identify DataGrid here
}

Please help me.

Body:
You have to navigate up the NamingContainer tree in dtg_ItemCommand.

//get the current datagrid item from the sender
DataGridItem gridIitem = (DataGridItem)(((Control)e.CommandSource).NamingContainer);

//the index of the griditem if needed
int gridItemIndex = gridIitem.ItemIndex;

//then the datagrid from the underlying datagriditem
DataGrid grid = (DataGrid)gridIitem.NamingContainer;

//then the repeateritem from the underlying datagrid
RepeaterItem repeaterItem = (RepeaterItem)grid.NamingContainer;

//now you can get the index of the repeateritem
int repeaterIndex = repeaterItem.ItemIndex;


问:
Ignoring a NULL parameter in T-SQL
I want to be able to pass in a list of parameters, and ignore the ones which are NULL. So that the query is in effect pretending that the filter isn't there and ignoring it.

I was doing it like this:

```<code>(@thing IS NULL or Thing=@thing)
</code>```

Is this right, and if so, would it perform badly? It's seems to be a lot slower than constructing the SQL separately.

What's the optimal way to do this?

FIXED! See Marc Gravell's answer. In summary using IS NULL many times is a big performance hit.

答:
Look at the following link in the section titled "The Case Study: Searching Orders". This explores all options in depth and should give you an excellent overview of the costs associated with each of these options. Warning, be very careful when using COALESCE it may not return what you think it is.

Regards,

Tim

OwnerDisplayName: Damien

Title: Ignoring a NULL parameter in T-SQL

Body:
I want to be able to pass in a list of parameters, and ignore the ones which are NULL. So that the query is in effect pretending that the filter isn't there and ignoring it.

I was doing it like this:

(@thing IS NULL or Thing=@thing)

Is this right, and if so, would it perform badly? It's seems to be a lot slower than constructing the SQL separately.

What's the optimal way to do this?

FIXED! See Marc Gravell's answer. In summary using IS NULL many times is a big performance hit.

LastEditorDisplayName: Damien


问:
How to fix this strange crash with keyboard
I have been seeing some odd crashes with the keyboard for some of the users that are live.
Looks like a KVO issue with UIWindow.

We are not adding any observers for key path windowLevel, so wondering what is causing this crash or how to debug this.

An instance 0x12c653e70 of class UIRemoteKeyboardWindow was
  deallocated while key value observers were still registered with it.
  Current observation info: NSKeyValueObservationInfo 0x12d3e6100
  NSKeyValueObservance 0x1196e01a0: Observer: 0x1273223f0, Key path:
  windowLevel, Options:  Context: 0x0,
  Property: 0x12c633980>

Also this crash is so random, I have never encountered this personally but got this via Crashlytics. Any help would be appreciated.
Have anyone else experienced similar issues.

答:
It would be nice if you had provided some sample code. But I guess you may be removing all observers of your UIViewController at once and in wrong place. Move the code for removing observers to "viewWillDisappear" and it may solve it.

Another guess is you are changing an attribute of keyboard when it has been deallocated.

My other guess is that you may have a "weak" property of keyboard. If so, change it to "strong" and it will solve the problem.


问:
Cloud functions for firebase finished with status: 'timeout'
Function gets executed without errors. I am getting the status

Function execution took 60004 ms, finished with status: 'timeout'

I am not sure what the issue is. Everything in my function looks good to me. I also noticed functions sometimes take several seconds to update database and sometimes it is instantly. Is it normal that execution times varies from instantly to couple second? Should execution times be instantly?

```<code>exports.countproposals = functions.database.ref("/proposals/{jobid}/{propid}").onWrite((event) => {
    const jobid = event.params.jobid;
    const userId = event.params.propid;
    const userRef = admin.database().ref(`users/${userId}/proposals/sent`);
    if (event.data.exists() && !event.data.previous.exists()) {
        userRef.child(jobid).set({
            timestamp: admin.database.ServerValue.TIMESTAMP
        });
    } else if (!event.data.exists() && event.data.previous.exists()) {
        userRef.child(jobid).remove();
    }
    const collectionRef = admin.database().ref(`/jobs/${jobid}`);
    const countRef = collectionRef.child("proposals");
    return countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (current || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (current || 0) - 1;
        }
    });
});
</code>```

答:
From my experience I would guess that this is (hopefully) a temporary problem with firebase function itself.
I get the same warnings/error for a function which yesterday took ~200 milliseconds to execute in average.</p>

Body:
Function gets executed without errors. I am getting the status

Function execution took 60004 ms, finished with status: 'timeout'

I am not sure what the issue is. Everything in my function looks good to me. I also noticed functions sometimes take several seconds to update database and sometimes it is instantly. Is it normal that execution times varies from instantly to couple second? Should execution times be instantly?

exports.countproposals = functions.database.ref("/proposals/{jobid}/{propid}").onWrite((event) => {
    const jobid = event.params.jobid;
    const userId = event.params.propid;
    const userRef = admin.database().ref(`users/${userId}/proposals/sent`);
    if (event.data.exists() && !event.data.previous.exists()) {
        userRef.child(jobid).set({
            timestamp: admin.database.ServerValue.TIMESTAMP
        });
    } else if (!event.data.exists() && event.data.previous.exists()) {
        userRef.child(jobid).remove();
    }
    const collectionRef = admin.database().ref(`/jobs/${jobid}`);
    const countRef = collectionRef.child("proposals");
    return countRef.transaction(current => {
        if (event.data.exists() && !event.data.previous.exists()) {
            return (current || 0) + 1;
        } else if (!event.data.exists() && event.data.previous.exists()) {
            return (current || 0) - 1;
        }
    });
});


问:
TensorFlow: How to skip broken data
I am playing with TensorFlow 1.0. My input data are bulk of jpeg images. Some of them are broken for different reasons, and I just want to skip them at input.

Image loading part of the Graph is the following:

```<code>filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once(filename_list), capacity=1000, num_epochs=1)
whole_file_reader = tf.WholeFileReader()
_, image_binary = whole_file_reader.read(filename_queue)
image_tensor = tf.cast(tf.image.decode_jpeg(image_binary), tf.float32)
</code>```

Model running part as usual:

```<code>with sv.managed_session() as sess:
        sess.run(init_local)
        sess.run(init_all)

        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord, sess=sess)

        try:
                while not coord.should_stop() and not sv.should_stop():
                        sess.run(accumulator)
        except tf.errors.OutOfRangeError:
                print('Done training -- epoch limit reached')
                #
        except Exception as e:
                # Report exceptions to the coordinator.
                coord.request_stop(e)
        finally:
                coord.request_stop()

        coord.request_stop()
        coord.join(threads)
</code>```

When running this code I see the following, and I could not figure out how to catch this exception correctly.

```<code>Traceback (most recent call last):
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1022, in _do_call
    return fn(*args)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1004, in _run_fn
    status, run_metadata)
  File "/usr/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 469, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid JPEG data, size 0
         [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=0, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](ReaderReadV2:1)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "calculate_mean.py", line 67, in <module>
    coord.join(threads)
  File "/usr/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 973, in managed_session
    self.stop(close_summary_writer=close_summary_writer)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 801, in stop
    stop_grace_period_secs=self._stop_grace_secs)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/training/coordinator.py", line 386, in join
    six.reraise(*self._exc_info_to_raise)
  File "/usr/lib/python3/dist-packages/six.py", line 686, in reraise
    raise value
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/training/queue_runner_impl.py", line 234, in _run
    sess.run(enqueue_op)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 767, in run
    run_metadata_ptr)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 965, in _run
    feed_dict_string, options, run_metadata)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1015, in _do_run
    target_list, options, run_metadata)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1035, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid JPEG data, size 0
         [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=0, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](ReaderReadV2:1)]]

Caused by op 'DecodeJpeg', defined at:
  File "calculate_mean.py", line 19, in <module>
    image_tensor = tf.cast(tf.image.decode_jpeg(image_binary), tf.float32)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/ops/gen_image_ops.py", line 345, in decode_jpeg
    dct_method=dct_method, name=name)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op
    op_def=op_def)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2395, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1264, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Invalid JPEG data, size 0
         [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=0, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](ReaderReadV2:1)]]
</code>```

Unfortunately, an answer given in
Skipping nonexistent or corrupt files in Tensorflow
doesn't work for me. It seems that in my case an exception is raised by coord.join(threads) which is too late.

答:
Sorry for the late response. The answer may be contained in your error message:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid JPEG data, size 0
           [[Node: DecodeJpeg = DecodeJpegacceptable_fraction=1, channels=0, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"]]

For whatever reason a JPEG file may be corrupted. However, you've used the default settings for tf.image_decode_jpeg which requires perfect decoding. Instead you may want to allow some error by setting parameters try_recover_truncated = True and acceptable_fraction=0.5 (or whatever). See this link for more.

Title: TensorFlow: How to skip broken data

Body:
I am playing with TensorFlow 1.0. My input data are bulk of jpeg images. Some of them are broken for different reasons, and I just want to skip them at input.

Image loading part of the Graph is the following:

filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once(filename_list), capacity=1000, num_epochs=1)
whole_file_reader = tf.WholeFileReader()
_, image_binary = whole_file_reader.read(filename_queue)
image_tensor = tf.cast(tf.image.decode_jpeg(image_binary), tf.float32)

Model running part as usual:

with sv.managed_session() as sess:
        sess.run(init_local)
        sess.run(init_all)

        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord, sess=sess)

        try:
                while not coord.should_stop() and not sv.should_stop():
                        sess.run(accumulator)
        except tf.errors.OutOfRangeError:
                print('Done training -- epoch limit reached')
                #
        except Exception as e:
                # Report exceptions to the coordinator.
                coord.request_stop(e)
        finally:
                coord.request_stop()

        coord.request_stop()
        coord.join(threads)

When running this code I see the following, and I could not figure out how to catch this exception correctly.

Traceback (most recent call last):
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1022, in _do_call
    return fn(*args)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1004, in _run_fn
    status, run_metadata)
  File "/usr/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/framework/errors_impl.py", line 469, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid JPEG data, size 0
         [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=0, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](ReaderReadV2:1)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "calculate_mean.py", line 67, in <module>
    coord.join(threads)
  File "/usr/lib/python3.5/contextlib.py", line 66, in __exit__
    next(self.gen)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 973, in managed_session
    self.stop(close_summary_writer=close_summary_writer)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/training/supervisor.py", line 801, in stop
    stop_grace_period_secs=self._stop_grace_secs)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/training/coordinator.py", line 386, in join
    six.reraise(*self._exc_info_to_raise)
  File "/usr/lib/python3/dist-packages/six.py", line 686, in reraise
    raise value
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/training/queue_runner_impl.py", line 234, in _run
    sess.run(enqueue_op)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 767, in run
    run_metadata_ptr)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 965, in _run
    feed_dict_string, options, run_metadata)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1015, in _do_run
    target_list, options, run_metadata)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1035, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid JPEG data, size 0
         [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=0, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](ReaderReadV2:1)]]

Caused by op 'DecodeJpeg', defined at:
  File "calculate_mean.py", line 19, in <module>
    image_tensor = tf.cast(tf.image.decode_jpeg(image_binary), tf.float32)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/ops/gen_image_ops.py", line 345, in decode_jpeg
    dct_method=dct_method, name=name)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 763, in apply_op
    op_def=op_def)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 2395, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/home/matwey/venv/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1264, in __init__
    self._traceback = _extract_stack()

InvalidArgumentError (see above for traceback): Invalid JPEG data, size 0
         [[Node: DecodeJpeg = DecodeJpeg[acceptable_fraction=1, channels=0, dct_method="", fancy_upscaling=true, ratio=1, try_recover_truncated=false, _device="/job:localhost/replica:0/task:0/cpu:0"](ReaderReadV2:1)]]

Unfortunately, an answer given in
Skipping nonexistent or corrupt files in Tensorflow
doesn't work for me. It seems that in my case an exception is raised by coord.join(threads) which is too late.


问:
i want to count occurrence of each word in a given sentence in java
beginner at java was asked in an interview
here i have to count the occurrence of each word in a given sentence.
for eg( "chair is equal to chair but not equal to table."
           Output : chair :2,
                    is :1,
                    equal :2,
                    to :2,
                    but :1,
                    not :1,
                    table :1 )
I have written some part of the code and tried using for loop but i failed....

```<code>public static void main(String[] args)
{
            int counter = 0;
   String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";

   String[] b =a.split(" "); //stored in array and splitted

 for(int i=0;i<b.length;i++)
 {
     counter=0;
     for(int j<b.length;j>0;j--)
     {
         if(b[i] = b[j])
          //

     }
 }
}
</code>```

}

答:
Use a hashmap to count frequency of objects

```<code>import java.util.HashMap;
import java.util.Map.Entry;

public class Funly {
    public static void main(String[] args) {
        int counter = 0;
        String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";

        String[] b = a.split(" "); // stored in array and splitted
        HashMap<String, Integer> freqMap = new HashMap<String, Integer>();
        for (int i = 0; i < b.length; i++) {
            String key = b[i];
            int freq = freqMap.getOrDefault(key, 0);
            freqMap.put(key, ++freq);
        }
        for (Entry<String, Integer> result : freqMap.entrySet()) {
            System.out.println(result.getKey() + " " + result.getValue());
        }
    }
}
</code>```

Body:
beginner at java was asked in an interview
here i have to count the occurrence of each word in a given sentence.
for eg( "chair is equal to chair but not equal to table."
           Output : chair :2,
                    is :1,
                    equal :2,
                    to :2,
                    but :1,
                    not :1,
                    table :1 )
I have written some part of the code and tried using for loop but i failed....

public static void main(String[] args)
{
            int counter = 0;
   String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";

   String[] b =a.split(" "); //stored in array and splitted

 for(int i=0;i<b.length;i++)
 {
     counter=0;
     for(int j0;j--)
     {
         if(b[i] = b[j])
          //

     }
 }
}

}

Body:
Use a hashmap to count frequency of objects

import java.util.HashMap;
import java.util.Map.Entry;

public class Funly {
    public static void main(String[] args) {
        int counter = 0;
        String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";

        String[] b = a.split(" "); // stored in array and splitted
        HashMap<String, Integer> freqMap = new HashMap<String, Integer>();
        for (int i = 0; i < b.length; i++) {
            String key = b[i];
            int freq = freqMap.getOrDefault(key, 0);
            freqMap.put(key, ++freq);
        }
        for (Entry<String, Integer> result : freqMap.entrySet()) {
            System.out.println(result.getKey() + " " + result.getValue());
        }
    }
}


问:
Ajax saving array into global variables not working keep getting undefined
Trying to save an array retrieved from ajax into a global variable such that I may use it later on but keep getting undefined error</p>

```<code>   <script>
    var items = [];

    function add(value){
        items.push(value);
    }

    $(document).ready( function() {
    $.ajax({
        type: 'POST',
        url: 'xxxx.php',
        dataType: 'json',
        cache: false,
        success: function(result) {
            for(i=0; i < result.length; i++){
                add(result[i]);
            }
        },
    });
    });

    document.write(items[1])

    </script>
</code>```

答:
You can use ajaxstop to call the method after the ajax request has completed. Place the following function in document ready:

```<code> $(document).ajaxStop(function () {
     document.write(items[1]);
 });
</code>```

The above solution works but this is another option I used when waiting for multiple ajax functions to complete. This will call every time you complete an ajax request but there is a way to limit to one call if need be.

Body:
You can use ajaxstop to call the method after the ajax request has completed. Place the following function in document ready:

 $(document).ajaxStop(function () {
     document.write(items[1]);
 });

The above solution works but this is another option I used when waiting for multiple ajax functions to complete. This will call every time you complete an ajax request but there is a way to limit to one call if need be.


答:
There are several solutions to this and I'm not going to provide you with any of them. However, I'm going to give you a rough outline of one possible solution:

You could use a Map, for example a HashMap, where you use the words as keys and the number of their occurrence as values. Then, all you need to do is to split the input string on spaces and iterate over the resulting array. For each word, you check if it already exists in the map. If so you increase the value by one, otherwise you add the word to the map and set the value to 1. After that, you can iterate over the map to create the desired output.

Title: i want to count occurrence of each word in a given sentence in java


问:
DTExec returns The package path referenced an object that cannot be found
I have a SSIS package and am trying to execute it using DTExec.exe

My command is this:

```<code>DTExec /F \\SERVERNAME\CUBEDAILYBACKUP.DTSX /MAXCONCURRENT "-1" /CHECKPOINTING OFF /REPORTING EWCPI /CONSOLELOG SMT /SET \PACKAGE.VARIABLES[BackupPath].VALUE;\\SERVERNAME\CUBESBACKUP
</code>```

and I get error:

.... The package path referenced an object that cannot be found:
  "\PACKAGE.VARIABLES[BackupPath].VALUE". This occurs when an attempt is
  made to resolve a package path to an object that cannot be found. ....

答:
The issue is that you are using upper case:

you need to write Package.Variables instead of PACKAGE.VARIABLES

Also use  .Value instead of .VALUE

Body:
I have a SSIS package and am trying to execute it using DTExec.exe

My command is this:

DTExec /F \\SERVERNAME\CUBEDAILYBACKUP.DTSX /MAXCONCURRENT "-1" /CHECKPOINTING OFF /REPORTING EWCPI /CONSOLELOG SMT /SET \PACKAGE.VARIABLES[BackupPath].VALUE;\\SERVERNAME\CUBESBACKUP

and I get error:

.... The package path referenced an object that cannot be found:
  "\PACKAGE.VARIABLES[BackupPath].VALUE". This occurs when an attempt is
  made to resolve a package path to an object that cannot be found. ....


问:
Gensim: error while loading pretrained doc2vec model?
I'm loading pretrained Doc2Vec model using:

```<code>from gensim.models import Doc2Vec
model = Doc2Vec.load('/path/to/pretrained/model')
</code>```

I'm getting the following error:

AttributeError: 'module' object has no attribute 'call_on_class_only'

Does anyone know how to fix it. The model was trained with gensim 0.13.3 and I'm using  gensim 0.12.4.

答:
Gensim will generally try to support loading of models saved from older versions into newer versions – but the reverse is a much harder problem, and will only work sometimes.

So upgrade the environment where you want to load the model to 0.13.3, to match where it was trained. (Or try the most-recent version, 1.0.1.) But don't try to move models backwards.

Body:
I'm loading pretrained Doc2Vec model using:

from gensim.models import Doc2Vec
model = Doc2Vec.load('/path/to/pretrained/model')

I'm getting the following error:

AttributeError: 'module' object has no attribute 'call_on_class_only'

Does anyone know how to fix it. The model was trained with gensim 0.13.3 and I'm using  gensim 0.12.4.


问:
Compilation errors in simple Java program with Scanner
```<code>import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}
</code>```

<p>I dont know why im getting 2 errors on strings cannot converted to int. </p>

答:
Change your first and second variables from

```<code>int first = keyboard.next();
int second = keyboard.next();
</code>```

to

```<code>int first = keyboard.nextInt();
int second = keyboard.nextInt();
</code>```

Body:
import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.

Body:
Change your first and second variables from

int first = keyboard.next();
int second = keyboard.next();

to

int first = keyboard.nextInt();
int second = keyboard.nextInt();


问:
How to Perform Unit testing for Serialization and Deserialization of a class in C#?
I want to perform NUnit or MS tests on a class for serialized and deserialized behavior.

I looked at another stackoverflow article here, but I still don't understand how to do this. Please help me to understand how to perform these tests,

Below is my part of code:

```<code>namespace PMT.Service.Common.DataContract
{
    public partial class MyBankInfo
    {
        public string MyId { get; set; }
        public string MyAccountNumber { get; set; }
        public string MyAccountType { get; set; }
        public string MyBankName { get; set; }
        public string MyBankBranchName { get; set; }
        public string MyBankCity { get; set; }
        public string MyBankCityPincode { get; set; }
        public string MyBankIFSCCode { get; set; }

        public void Serialize(BinaryStreamWriter binaryStreamWriter)
        {
            binaryStreamWriter.Write(MyId);
            binaryStreamWriter.Write(MyAccountNumber);
            binaryStreamWriter.Write(MyAccountType);
            binaryStreamWriter.Write(MyBankName);
            binaryStreamWriter.Write(MyBankBranchName);
            binaryStreamWriter.Write(MyBankCity);
            binaryStreamWriter.Write(MyBankCityPincode);
            binaryStreamWriter.Write(MyBankIFSCCode);
        }

        public bool Deserialize(BinaryStreamReader binaryStreamReader,out   string errorString)
        {
            errorString = string.Empty;
            try
            {
                MyId = binaryStreamReader.ReadString();
                MyAccountNumber = binaryStreamReader.ReadString();
                MyAccountType = binaryStreamReader.ReadString();
                MyBankName = binaryStreamReader.ReadString();
                MyBankBranchName = binaryStreamReader.ReadString();
                MyBankCity = binaryStreamReader.ReadString();
                MyBankCityPincode = binaryStreamReader.ReadString();
                MyBankIFSCCode = binaryStreamReader.ReadString();

            }
            catch (Exception ex)
            {
                errorString = ex.Message;
            }
            return string.IsNullOrEmpty(errorString);
        }
    }
}
</code>```

答:
There are two ways to test serialization and deserialization: separately or both together.

Separate tests are best if the serialized data is created by or used by some other software that you don't have control over. In that case, exact formats have to be verified. This is also the hard way.

If your data is only serialized and deserialized by your own class, then you can test both at once:

Create a test object

Create a Writer in memory or backed on disk.

Serialize to that writer.

Create a second object and deserialize it from the saved data.

Write a bunch of assertions that compare the original object's properties to the new object's.

Body:
I want to perform NUnit or MS tests on a class for serialized and deserialized behavior.

I looked at another stackoverflow article here, but I still don't understand how to do this. Please help me to understand how to perform these tests,

Below is my part of code:

namespace PMT.Service.Common.DataContract
{
    public partial class MyBankInfo
    {
        public string MyId { get; set; }
        public string MyAccountNumber { get; set; }
        public string MyAccountType { get; set; }
        public string MyBankName { get; set; }
        public string MyBankBranchName { get; set; }
        public string MyBankCity { get; set; }
        public string MyBankCityPincode { get; set; }
        public string MyBankIFSCCode { get; set; }

        public void Serialize(BinaryStreamWriter binaryStreamWriter)
        {
            binaryStreamWriter.Write(MyId);
            binaryStreamWriter.Write(MyAccountNumber);
            binaryStreamWriter.Write(MyAccountType);
            binaryStreamWriter.Write(MyBankName);
            binaryStreamWriter.Write(MyBankBranchName);
            binaryStreamWriter.Write(MyBankCity);
            binaryStreamWriter.Write(MyBankCityPincode);
            binaryStreamWriter.Write(MyBankIFSCCode);
        }

        public bool Deserialize(BinaryStreamReader binaryStreamReader,out   string errorString)
        {
            errorString = string.Empty;
            try
            {
                MyId = binaryStreamReader.ReadString();
                MyAccountNumber = binaryStreamReader.ReadString();
                MyAccountType = binaryStreamReader.ReadString();
                MyBankName = binaryStreamReader.ReadString();
                MyBankBranchName = binaryStreamReader.ReadString();
                MyBankCity = binaryStreamReader.ReadString();
                MyBankCityPincode = binaryStreamReader.ReadString();
                MyBankIFSCCode = binaryStreamReader.ReadString();

            }
            catch (Exception ex)
            {
                errorString = ex.Message;
            }
            return string.IsNullOrEmpty(errorString);
        }
    }
}


问:
What is the best ORM framework and why?
What is the best ORM Object Relational Mapping framework or architecture in your opinion, And why??</p>

答: Hibernate is good documented, has support in other frameworks like Spring. Also implements JPA so it's definitly good choice. </p>

Title: What is the best ORM framework and why?


答:
You need to use Map data structure which stores data in key-value pairs.

You can use the HashMap (implementation of Map) to store each word as key and their occurance as the value inside the Map as shown in the below code with inline comments:

```<code>String[] b =a.split(" "); //split the array
Map<String, Integer> map = new HashMap<>();//create a Map object
Integer counter=null;//initalize counter
for(int i=0;i<b.length;i++) { //loop the whole array
     counter=map.get(b[i]);//get element from map
     if(map.get(b[i]) == null) { //check if it already exists
          map.put(b[i], 1);//not exist, add with counter as 1
     } else {
          counter++;//if already eists, increment the counter & put to Map
           map.put(b[i], counter);
     }
}
</code>```

Body:
You need to use Map data structure which stores data in key-value pairs.

You can use the HashMap (implementation of Map) to store each word as key and their occurance as the value inside the Map as shown in the below code with inline comments:

String[] b =a.split(" "); //split the array
Map<String, Integer> map = new HashMap<>();//create a Map object
Integer counter=null;//initalize counter
for(int i=0;i<b.length;i++) { //loop the whole array
     counter=map.get(b[i]);//get element from map
     if(map.get(b[i]) == null) { //check if it already exists
          map.put(b[i], 1);//not exist, add with counter as 1
     } else {
          counter++;//if already eists, increment the counter & put to Map
           map.put(b[i], counter);
     }
}


问:
Visual Studio breakpoints break in the wrong source file (or multiple files simultaneously) if multiple files have the same name
In a team project I'm working on, setting a breakpoint in a file (say IdeasController.cs) will lead to erratic debugger behaviour if there's another file with the same name in the solution. I've reproduced the problem on several developers' workstations.

Example

I set a breakpoint in IdeasController.cs in our Web API:

Another file called IdeasController.cs exists in our separate MVC 4 web project. In the screenshot below, the debugger shows the Api->IdeasController source code, but the line highlight matches the code structure of Web->IdeasController. The breakpoint is duplicated, with one of them in the middle of a comment block.

The Breakpoint window shows the breakpoint in both files simultaneously:

On some workstations the debugger steps through the correct lines (regardless of the line highlight); on others it cheerfully steps through irrelevant lines (including comments and whitespace). I'm guessing this depends on which source file it chooses to display.

What I've tried

I've trawled the Internet. This kind of problem seems to occur when there's a mismatch between the debug file (*.pdb), the source file, and the compiled code. There are a lot of possible causes: duplicate file names (which can confuse the debugger[5]), outdated project build files, invalid solution cache, or incorrect build configuration.

These are the solutions I've found and tried:

Checked my build configuration.

Made sure the project isn't built in release mode.

Made sure we don't have code optimization enabled.

Made sure the project's debug module was loaded correctly. (Started debugging the project and checked Debug > Windows > Modules. Both assemblies are listed, not optimized, and have a symbol status of "Symbols loaded".)

Reset the debugging metadata & Visual Studio cache.

Closed Visual Studio and deleted the solution cache file (*.suo).[1]

Deleted each project's build output (the bin and obj folders). (For future reference: open the solution folder in Windows Explorer and type this in the search box: "type:folder AND (name:=bin OR name:=obj)".

Deleted the assembly cache folder (C:\Documents and Settings\<user>\Local Settings\Application Data\dl3).[2][3]

None of these had any effect. I can rename one of the files (without renaming the class) to temporarily work around the problem, but that's far from ideal.

Where I am now

Page 14 of my latest Google search. Suggestions would be much appreciated. :)

答:
Although renaming one of the files will work, I found that the simplest solution is to temporarily disable automatic loading of symbols for the "other" assembly.

Start the debugger and continue until you hit the erroneous breakpoint.

Find where the debugger actually set the breakpoint using the Call Stack window:

Right-click on the row with the yellow arrow and enable Show Module Names. (The row should also have the red breakpoint symbol on it.)

The assembly name is now visible on that row.

Find that assembly in the Modules window (Debug > Windows > Modules).

Right-click on the assembly and disable Always Load Automatically.

Stop the debugger.

Start debugging again.

By doing this, you're preventing the Visual Studio debugger from mapping the breakpoint to the wrong assembly. It will then load the symbols from the other [presumably] correct assembly first, therefore mapping the breakpoint to the correct assembly.

Why does this happen?

This seems to occur when two different symbol files (PDB files) — for two different assemblies — both reference a source file with the same name. Although the source files are completely different, the Visual Studio debuggger seems to get confused.

For example, imagine there are two different files both with the name IdeasController.cs. The first one compiles into assembly Api.dll, and the second one compiles into assembly Web.dll.

When the debugger loads symbols, it will either load Api.pdb or Web.pdb first. Let's say it loads Api.pdb first. Then even if you set a breakpoint in Web\IdeasController.cs, it will find a match for IdeasController.cs in Api.pdb. It then maps code from Web\IdeasController.cs to Api.dll. This won't map correctly, of course, and so you see all sorts of odd issues while debugging.


问:
Perl6: Match elements in a list with another list
I have a list of numbers L. There is another list of numbers M. I need to return a list L' of numbers found in both L and M.

Edit: Mathematically, I am looking for Multiset intersection.

Example:

L  = 3, 1, 4, 1, 5, 9, 2, 6

  M  = 9, 7, 1, 2, 1, 1

  L' = 9, 1, 2, 1

I wrote the following code for that:

```<code>my @some-numbers = 3, 1, 4, 1, 5, 9, 2, 6;
my @to-match     = 9, 7, 1, 2, 1, 1;
my @matched;

my %histogram;
for @some-numbers -> $n { %histogram{$n}++ };

for @to-match -> $n {
    next if not defined %histogram{$n};
    if %histogram{$n} > 0 {
        push @matched, $n;
        %histogram{$n}--;
    }
};

say @matched;
</code>```

While it achieves the purpose, I was wondering whether there was an idiomatic Perl6 way of doing this?

Some background: I have been trying to learn Perl6 and Python together, and solve the same puzzles in both the languages. Python offered a particularly pleasing solution for the above problem. To my beginner eyes at least :)

答:
Depending on the precise semantics you're looking for, Bag operations might be just the ticket:

```<code>my \L = 3, 1, 4, 1, 5, 9, 2, 6;
my \M = 9, 7, 1, 2, 1, 1;

.put with L.Bag ∩ M.Bag;
</code>```

displays:

```<code>9 1(2) 2
</code>```

This is the stringification of a Bag containing the three keys '9', '1', and '2' whose respective values (repeat counts) are the integers 1, 2, and 1.

To get Perl 6 to produce a list from a bag with each key repeated the number of times indicated by its associated value, use the .kxxv method:

```<code>.kxxv.put with L.Bag ∩ M.Bag;
</code>```

displays:

```<code>9 1 1 2
</code>```

(The mnemonic for the kxxv method is that it's k for "key" then xx in analogy with the xx repetition operator and finally v for "value". It sorta makes sense if you think about it.)

But perhaps a bag won't do. For example, perhaps the order of elements in the result matters -- you need 9 1 2 1 and not 9 1 1 2? I'll extend this answer if a bag isn't the right way to go.

Body:
I have a list of numbers L. There is another list of numbers M. I need to return a list L' of numbers found in both L and M.

Edit: Mathematically, I am looking for Multiset intersection.

Example:

L  = 3, 1, 4, 1, 5, 9, 2, 6

  M  = 9, 7, 1, 2, 1, 1

  L' = 9, 1, 2, 1

I wrote the following code for that:

my @some-numbers = 3, 1, 4, 1, 5, 9, 2, 6;
my @to-match     = 9, 7, 1, 2, 1, 1;
my @matched;

my %histogram;
for @some-numbers -> $n { %histogram{$n}++ };

for @to-match -> $n {
    next if not defined %histogram{$n};
    if %histogram{$n} > 0 {
        push @matched, $n;
        %histogram{$n}--;
    }
};

say @matched;

While it achieves the purpose, I was wondering whether there was an idiomatic Perl6 way of doing this?

Some background: I have been trying to learn Perl6 and Python together, and solve the same puzzles in both the languages. Python offered a particularly pleasing solution for the above problem. To my beginner eyes at least :)

Body:
Depending on the precise semantics you're looking for, Bag operations might be just the ticket:

my \L = 3, 1, 4, 1, 5, 9, 2, 6;
my \M = 9, 7, 1, 2, 1, 1;

.put with L.Bag ∩ M.Bag;

displays:

9 1(2) 2

This is the stringification of a Bag containing the three keys '9', '1', and '2' whose respective values (repeat counts) are the integers 1, 2, and 1.

To get Perl 6 to produce a list from a bag with each key repeated the number of times indicated by its associated value, use the .kxxv method:

.kxxv.put with L.Bag ∩ M.Bag;

displays:

9 1 1 2

(The mnemonic for the kxxv method is that it's k for "key" then xx in analogy with the xx repetition operator and finally v for "value". It sorta makes sense if you think about it.)

But perhaps a bag won't do. For example, perhaps the order of elements in the result matters -- you need 9 1 2 1 and not 9 1 1 2? I'll extend this answer if a bag isn't the right way to go.


问:
How to do a ASP.NET MVC Ajax form post with multipart/form-data?
I am working on a ASP.NET MVC web site which has a form that allows for the upload of files using the multipart/form data enctype option on the form tag like so

```<code><form enctype="multipart/form-data" method="post" action='<%= Url.Action("Post","Entries",new {id=ViewData.Model.MemberDetermination.DeterminationMemberID})  %>'>
</code>```

How would I write this to do an ASP.NET MVC Ajax form post instead?

答:
I mixed Brad Larson answer with Amirhossein Mehrvarzi, because Brad answer wasn't providing any way to handle the response and Amirhossein was causing 2 postbacks.
I just added ($('#formBacklink').valid()) to call model validation before send.</p>

```<code>window.addEventListener("submit", function (e) {
        if ($('#formBacklink').valid()) {
            var form = e.target;
            if (form.getAttribute("enctype") === "multipart/form-data") {
                if (form.dataset.ajax) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    var dataString;
                    event.preventDefault();
                    var action = $("#formBacklink").attr("action");
                    if ($("#formBacklink").attr("enctype") == "multipart/form-data") {
                        //this only works in some browsers.
                        //purpose? to submit files over ajax. because screw iframes.
                        //also, we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.
                        dataString = new FormData($("#formBacklink").get(0));
                        contentType = false;
                        processData = false;
                    } else {
                        // regular form, do your own thing if you need it
                    }
                    $.ajax({
                        type: "POST",
                        url: action,
                        data: dataString,
                        dataType: "json", //change to your own, else read my note above on enabling the JsonValueProviderFactory in MVC
                        contentType: contentType,
                        processData: processData,
                        success: function (data) {
                            //BTW, data is one of the worst names you can make for a variable
                            //handleSuccessFunctionHERE(data);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            //do your own thing
                        }
                    });
                }
            }
        }
    }, true);
</code>```

OwnerDisplayName: dswatik

Body:
I am working on a ASP.NET MVC web site which has a form that allows for the upload of files using the multipart/form data enctype option on the form tag like so

<form enctype="multipart/form-data" method="post" action='<%= Url.Action("Post","Entries",new {id=ViewData.Model.MemberDetermination.DeterminationMemberID})  %>'>

How would I write this to do an ASP.NET MVC Ajax form post instead?

Body:
I mixed Brad Larson answer with Amirhossein Mehrvarzi, because Brad answer wasn't providing any way to handle the response and Amirhossein was causing 2 postbacks.
I just added ($('#formBacklink').valid()) to call model validation before send.

window.addEventListener("submit", function (e) {
        if ($('#formBacklink').valid()) {
            var form = e.target;
            if (form.getAttribute("enctype") === "multipart/form-data") {
                if (form.dataset.ajax) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    var dataString;
                    event.preventDefault();
                    var action = $("#formBacklink").attr("action");
                    if ($("#formBacklink").attr("enctype") == "multipart/form-data") {
                        //this only works in some browsers.
                        //purpose? to submit files over ajax. because screw iframes.
                        //also, we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.
                        dataString = new FormData($("#formBacklink").get(0));
                        contentType = false;
                        processData = false;
                    } else {
                        // regular form, do your own thing if you need it
                    }
                    $.ajax({
                        type: "POST",
                        url: action,
                        data: dataString,
                        dataType: "json", //change to your own, else read my note above on enabling the JsonValueProviderFactory in MVC
                        contentType: contentType,
                        processData: processData,
                        success: function (data) {
                            //BTW, data is one of the worst names you can make for a variable
                            //handleSuccessFunctionHERE(data);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            //do your own thing
                        }
                    });
                }
            }
        }
    }, true);