How would I run an async Task method synchronously?

Question: I am learning about async/await, and ran into a situation where I need to call an async method synchronously. How can I do that?
Async method:
public async Task<Customers> GetCustomers()
{
    return await Service.GetCustomersAsync();
}

Normal usage:
public async void GetCustomers()
{
    customerList = await GetCustomers();
}

I've tried using the following:
Task<Customer> task = GetCustomers();
task.Wait()

Task<Customer> task = GetCustomers();
task.RunSynchronously();

Task<Customer> task = GetCustomers();
while(task.Status != TaskStatus.RanToCompletion)

I also tried a suggestion from here, however it doesn't work when the dispatcher is in a suspended state.
public static void WaitWithPumping(this Task task)
{
        if (task == null) throw new ArgumentNullException("task");
        var nestedFrame = new DispatcherFrame();
        task.ContinueWith(_ => nestedFrame.Continue = false);
        Dispatcher.PushFrame(nestedFrame);
        task.Wait();
}

Here is the exception and stack trace from calling RunSynchronously:

System.InvalidOperationException
Message: RunSynchronously may not be called on a task unbound to a delegate.
InnerException: null
Source: mscorlib
StackTrace:

          at System.Threading.Tasks.Task.InternalRunSynchronously(TaskScheduler scheduler)
   at System.Threading.Tasks.Task.RunSynchronously()
   at MyApplication.CustomControls.Controls.MyCustomControl.CreateAvailablePanelList() in C:\Documents and Settings\...\MyApplication.CustomControls\Controls\MyCustomControl.xaml.cs:line 638
   at MyApplication.CustomControls.Controls.MyCustomControl.get_AvailablePanels() in C:\Documents and Settings\...\MyApplication.CustomControls\Controls\MyCustomControl.xaml.cs:line 233
   at MyApplication.CustomControls.Controls.MyCustomControl.<CreateOpenPanelList>b__36(DesktopPanel panel) in C:\Documents and Settings\...\MyApplication.CustomControls\Controls\MyCustomControl.xaml.cs:line 597
   at System.Collections.Generic.List`1.ForEach(Action`1 action)
   at MyApplication.CustomControls.Controls.MyCustomControl.<CreateOpenPanelList>d__3b.MoveNext() in C:\Documents and Settings\...\MyApplication.CustomControls\Controls\MyCustomControl.xaml.cs:line 625
   at System.Runtime.CompilerServices.TaskAwaiter.<>c__DisplayClass7.<TrySetContinuationForAwait>b__1(Object state)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at MyApplication.App.Main() in C:\Documents and Settings\...\MyApplication\obj\Debug\App.g.cs:line 50
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Comment: @Stephen Cleary Absolutely agree, but sometimes its simply unavoidable, such as when your code is dependent on some 3rd party API that does not use async/await. In addition, if binding to WPF properties when using MVVM, its literally impossible to use async/await as this is not supported on properties.
Comment: The best answer to the question "How can I call an async method synchronously" is "don't". There are [hacks](http://stackoverflow.com/a/5097066/263693) to try to force it to work, but they all have very subtle pitfalls. Instead, back up and fix the code that makes you "need" to do this.
Comment: @StephenCleary That's all nice theory, but "don't do it" has that inherent issue with it that it "doesn't work". C# actively forbids me to use `await` within synchronised blocks. Should I have Microsoft change their language? Or should I drop my synchronisation and accept messed up data structures? `async` is that cancer, not so much GPL. Once you have it you can't get rid of it.
Comment: @StephenCleary 1) GeneXus is a 3rd pt tool and I don't have access to its source code; 2) GeneXus don't even has implementations of "functions", so I can't realize how I could implement a "callback" with this type of thing. Surely it would be a harder workaround than using `Task` synchronously; 3) I'm integrating GeneXus with [MongoDB C# driver](https://docs.mongodb.org/getting-started/csharp/), which expose some methods only asynchronously
Comment: @StephenCleary Not always. I'm building a DLL which will be imported in [GeneXus](http://www.genexus.com/). It don't support async/await keywords, so I must use only synchronous methods.
Comment: The absence of StackOverflow the biggest names even in late 2016 strongly suggests that there still isn't a simple method to do that. BTW. I wonder why there is no `runsync` operator.
Comment: @ygoe: Use an async-compatible lock, such as `SemaphoreSlim`.
Comment: Possible duplicate of [How to call asynchronous method from synchronous method in C#?](http://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c)
Comment: I've been told not to use `var x = SomeAsyncMethod().Result` to run async task inside an non-async method since it will block the main thread and cause deadlock.  Is it still valid in 2022 for .NET 6 apps?  what if I have that line in a .NET Framework 4.7 project?  I've seen people suggest `var x = Task.Run( async ()=> await SomeAsyncMethod()).Result` instead to avoid deadlock.  Will that work?
Comment: @DineiA.Rockenbach: Three better alternatives spring immediately to mind: 1) Have GeneXus add support for async methods; 2) Implement a callback/event instead of using `Task` (often required for cross-language interop); 3) Use synchronous code all the way, so sync-over-async doesn't even come up. Each of these is a better alternative to using dubious hacks.
Comment: Linking a [related q/a](https://stackoverflow.com/q/53508160/1768303) on how to do this on a UI thread.
Comment: @StephenCleary why .net does not provide something like ".RunAsSynchronous()" method that we can call on Task type ? this kind of method would just ignore/remove all that async stuff and run it. So instead of us writing async method and synchronous versions of it, we could just have one metod but caller would decide if they want to use async stuff on it or just completely ignore it as it never existed.
Comment: @IronHide: What about code that returns task objects *not* created by `async`?
Comment: @StephenCleary I have no idea, I did not think of every possible scenario, I assumed that some async  gurus like your self will figure it out in like no time :) (Not being sarcastic)
Answer: Here's a workaround I found that works for all cases (including suspended dispatchers). It's not my code and I'm still working to fully understand it, but it does work.
It can be called using:
customerList = AsyncHelpers.RunSync<List<Customer>>(() => GetCustomers());
Code is from here
public static class AsyncHelpers
{
    ///
    /// Synchronously execute's an async Task method which has a void return value.
    ///
    /// <param name="task">The Task method to execute.</param>
    public static void RunSync(Func<Task> task)
    {
        var oldContext = SynchronizationContext.Current;
        var syncContext = new ExclusiveSynchronizationContext();
        SynchronizationContext.SetSynchronizationContext(syncContext);

        syncContext.Post(async _ =>
        {
            try
            {
                await task();
            }
            catch (Exception e)
            {
                syncContext.InnerException = e;
                throw;
            }
            finally
            {
                syncContext.EndMessageLoop();
            }
        }, null);

        syncContext.BeginMessageLoop();

        SynchronizationContext.SetSynchronizationContext(oldContext);
    }

    ///
    /// Synchronously execute's an async Task<T> method which has a T return type.
    ///
    /// <typeparam name="T">Return Type</typeparam>
    /// <param name="task">The Task<T> method to execute.</param>
    /// <returns>The result of awaiting the given Task<T>.</returns>
    public static T RunSync<T>(Func<Task<T>> task)
    {
        var oldContext = SynchronizationContext.Current;
        var syncContext = new ExclusiveSynchronizationContext();
        SynchronizationContext.SetSynchronizationContext(syncContext);
        T result;

        syncContext.Post(async _ =>
        {
            try
            {
                result = await task();
            }
            catch (Exception e)
            {
                syncContext.InnerException = e;
                throw;
            }
            finally
            {
                syncContext.EndMessageLoop();
            }
        }, null);

        syncContext.BeginMessageLoop();

        SynchronizationContext.SetSynchronizationContext(oldContext);

        return result;
    }

    private class ExclusiveSynchronizationContext : SynchronizationContext
    {
        private readonly AutoResetEvent workItemsWaiting = new AutoResetEvent(false);
        private readonly Queue<Tuple<SendOrPostCallback, object>> items =
            new Queue<Tuple<SendOrPostCallback, object>>();
        private bool done;

        public Exception InnerException { get; set; }

        public override void Send(SendOrPostCallback d, object state)
        {
            throw new NotSupportedException("We cannot send to our same thread");
        }

        public override void Post(SendOrPostCallback d, object state)
        {
            lock (items)
            {
                items.Enqueue(Tuple.Create(d, state));
            }

            workItemsWaiting.Set();
        }

        public void EndMessageLoop()
        {
            Post(_ => done = true, null);
        }

        public void BeginMessageLoop()
        {
            while (!done)
            {
                Tuple<SendOrPostCallback, object> task = null;
                lock (items)
                {
                    if (items.Count > 0)
                    {
                        task = items.Dequeue();
                    }
                }

                if (task != null)
                {
                    task.Item1(task.Item2);
                    if (InnerException != null) // the method threw an exeption
                    {
                        throw new AggregateException("AsyncHelpers.Run method threw an exception.", InnerException);
                    }
                }
                else
                {
                    workItemsWaiting.WaitOne();
                }
            }
        }

        public override SynchronizationContext CreateCopy()
        {
            return this;
        }
    }
}

Comment: For some background on how this works, Stephen Toub (Mr Parallel) wrote a series of posts about this. [Part 1](http://blogs.msdn.com/b/pfxteam/archive/2012/01/20/10259049.aspx) [Part 2](http://blogs.msdn.com/b/pfxteam/archive/2012/01/21/10259307.aspx) [Part 3](http://blogs.msdn.com/b/pfxteam/archive/2012/02/02/10263555.aspx)
Comment: @StephenCleary Although I generally agree with you that the code should be async all the way down, sometimes you find yourself in an infeasible situation where one *has* to force it as a synchronous call. Basically, my situation is that all my data access code is in async fashion. I needed to build a sitemap based on the sitemap and the third party library I was using was MvcSitemap. Now when one is extending it via the `DynamicNodeProviderBase` base class, one cannot declare it as a `async` method. Either I had to replace with a new library, or just call a synchronous op.
Comment: I updated John's code to work without wrapping tasks in lambdas: https://github.com/tejacques/AsyncBridge. Essentially you work with async blocks with the using statement. Anything inside a using block happens asynchronously, with a wait at the end. The downside is that you need to unwrap the task yourself in a callback, but it's still fairly elegant, especially if you need to call several async functions at once.
Comment: @justin.lovell: Yes, *library limitations* can force us to put in hacks, at least until the library is updated. It sounds like MvcSitemap is one such situation where a hack is required (MVC filters and child actions, too); I just dissuade people from this in general because hacks like this are used way too often when they are *not* necessary. With MVC in particular, some ASP.NET/MVC APIs do assume that they have an `AspNetSynchronizationContext`, so this particular hack won't work if you're calling those APIs.
Comment: This code will not work. If it is called from a pool thread it can trigger thread-starvation deadlock. Your caller will block waiting for the operation to complete, which may never happen if he has exhausted the thread pool. See [this article](http://blogs.msdn.com/b/pfxteam/archive/2012/04/13/10293638.aspx).
Comment: Sometimes you inherit someone else's code that was written all sync, and you have to deliver something by a certain deadline, and rewriting everything to be async upwards isn't an option.
Comment: @ghord - if you don't want to block the UI then you can't run it synchronously...by definition it will block the thread it runs on. Just await it if you don't want it to block. I don't understand the point of what you are asking.
Comment: This code has a bug. It doesn't restore the old context (`SynchronizationContext.SetSynchronizationContext(oldContext)`) when an exception is thrown. Using `try { ... } finally { ... }` fixes it.
Comment: @cameron macfarland cited a blog post by Stephen Toub. It does not work any more. Has someone an updated link?
Comment: This method blocks the UI thread it is executed on. Would it be possible to somehow use `Dispatcher.PushFrame(DispatcherFrame)` method to prevent blocking the UI?
Comment: What you are asking for is impossible though, just think about it - if you don't pass control back to the UI thread then the UI won't update. By definition, something running synchronously on the UI thread will freeze the UI until it finishes. I'm certain there's a better way to achieve whatever it is you are trying to do. Instead of bloating this thread more, how about you post a separate question and I will try my best to answer it.
Comment: @MikeMarynowski It was possible in 4.0 with `Dispatcher.PushFrame` and it worked quite well. It just so happens it causes async/await code to deadlock. I don't need new question - I just reorganized my app so it didn't need this.
Comment: @ghord sure, it still works perfectly: https://gist.github.com/ivan-danilov/3ee430522d596ccf6496
Comment: Unfortunately it does not work for *all* cases. WaitOne() internally pumps messages (so that COM things work as expected I believe). This means that external code (such as event handlers) can execute every time a task is awaited in the custom context, and WaitOne() is called. I experienced such a situation causing a deadlock between the main thread and itself :/

I solved it by executing my task on a new thread, and actually blocking with a `while (!task.IsCompleted) { /*wait*/}`. This is ugly, but unless something in your task tries to execute on the waiting thread, everything should work.
Comment: @MikeMarynowski I had a problem with async void (cannot change to Task) method with awaits, which I wanted to execute fully before passing control. This solution helps, but it hangs the UI thread, which I was trying to avoid.
Comment: @Paval This answer is pretty old, however in the past I never had any problems like that with the code. The use of the `await` keyword says *"queue this command on a separate thread, and everything below this to run upon thread completion, then end this code block and go back to whatever else you were doing"*, which in this case is the message loop calling `.WaitOne` repeatedly. Because the task runs on a separate thread, I don't think you should experiencing any dead locks with this code.
Comment: To avoid FxCopy warning Implement IDisposable in ExclusiveSynchronizationContext, disposing _workItemsWaiting
Comment: @TomJacques tried your library since I was suspicious of that working without having to wrap in lambdas. Tried with a small winforms app. Didnt work for me. Of course I tested against a hot task.
Comment: I am having issues with my console application just hanging, not sure why but after using this code it started happening.
Comment: Though this answer has been posted a very long time ago. Thank you so much, after series of searches, this worked once.
Comment: In some rare scenarios the ExclusiveSynchronizationContext.Post() can be called after leaving BeginMessageLoop() and the callback will never be executed. Example:

    AsyncHelpers.RunSync(() => MyTask());

    private static async Task MyTask()
    {
        await Task.Delay(1);
        var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
       Task.Run(async () => await Task.Delay(1000)).ContinueWith(g =>
        {
           Console.WriteLine("Will never be executed");
       }, scheduler);
        await Task.Delay(100);
      }
Comment: See Stephen Toub's blog with [AsyncPump](https://devblogs.microsoft.com/pfxteam/await-synchronizationcontext-and-console-apps/).
Answer: Be advised this answer is three years old. I wrote it based mostly on a experience with .Net 4.0, and very little with 4.5 especially with async-await.
Generally speaking it's a nice simple solution, but it sometimes breaks things. Please read the discussion in the comments.
.Net 4.5
Just use this:
// For Task<T>: will block until the task is completed...
var result = task.Result;

// For Task (not Task<T>): will block until the task is completed...
task2.RunSynchronously();

See:
TaskAwaiter,
Task.Result,
Task.RunSynchronously

.Net 4.0
Use this:
var x = (IAsyncResult)task;
task.Start();

x.AsyncWaitHandle.WaitOne();

...or this:
task.Start();
task.Wait();

Comment: `Result` can [easily cause deadlock in `async` code](http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html), as I describe on my blog.
Comment: `.Result` can produce a deadlock in certain scenario's
Comment: The question concerns a Task that is returned by async method. Such kind of Task may have already been started, executed, or canceled, so usage of *Task.RunSynchronously* method may result in *InvalidOperationException*. See MSDN page: [Task.RunSynchronously Method](http://msdn.microsoft.com/en-us/library/dd321435(v=vs.110).aspx). Besides, that Task is probably created by *Task.Factory.StartNew* or *Task.Run* methods (inside async method), so it's dangerous to try start it again. Some race conditions may occur at runtime. In the othe hand, *Task.Wait* and *Task.Result* may result i deadlock.
Comment: @StephenCleary I read your post, and tried it myself. I honestly think someone at microsoft was really drunk... It's the same issue as like winforms and background threads....
Comment: Run Synchronously worked for me... I don't know if I'm missing something but this seems preferable to the horrors of the marked answer - I was just looking for a way of switching off async for testing code that just there to stop the ui from hanging
Comment: a. RunSynchronously may not be called on a task not bound to a delegate
so I wrapped it in a Task(async () => await methodAsync().ConfigureAwait(continueOnCapturedContext: false))
b. Added the .Wait() per the MSDN article
Surprise the task started synchronous execution then claimed completion when I/O started, leading to baffling race condition.
Fell back to .GetAwaiter().GetResult(); which really waited for completion.
By why is RunSynchronously() and Wait() returning before async task is really done???
Comment: task.Wait() sometimes does not work "synchronously". This introduces some very nasty bugs
Comment: `Result` causes weird connection exceptions in Entity Framework
Comment: When you run this the following error occurs : RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.
Comment: It worth to mention that  based on [this](http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html#comment-8d8069d0-4401-11e9-ab1b-b1484e5f4180) and [this](https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html), the deadlock is not a problem for ASP.NET Core!
Comment: If you want to use async in .NET 4.0 you can install the NuGet package async:

http://www.nuget.org/packages/Microsoft.Bcl.Async/
Comment: @JordyLangen of course, you are waiting for that task to complete... But that's usual with parallel programming, and always true when waiting on something...
Comment: The documentation for RunSynchronously() suggests calling Wait() afterword "to handle any exceptions that the task might throw".
Answer: Surprised no one mentioned this:
public Task<int> BlahAsync()
{
    // ...
}

int result = BlahAsync().GetAwaiter().GetResult();

Not as pretty as some of the other methods here, but it has the following benefits:

it doesn't swallow exceptions (like Wait)
it won't wrap any exceptions thrown in an AggregateException (like Result)
works for both Task and Task<T> (try it out yourself!)

Also, since GetAwaiter is duck-typed, this should work for any object that is returned from an async method (like ConfiguredAwaitable or YieldAwaitable), not just Tasks.

edit: Please note that it's possible for this approach (or using .Result) to deadlock, unless you make sure to add .ConfigureAwait(false) every time you await, for all async methods that can possibly be reached from BlahAsync() (not just ones it calls directly). Explanation.
// In BlahAsync() body
await FooAsync(); // BAD!
await FooAsync().ConfigureAwait(false); // Good... but make sure FooAsync() and
                                        // all its descendants use ConfigureAwait(false)
                                        // too. Then you can be sure that
                                        // BlahAsync().GetAwaiter().GetResult()
                                        // won't deadlock.

If you're too lazy to add .ConfigureAwait(false) everywhere, and you don't care about performance you can alternatively do
Task.Run(() => BlahAsync()).GetAwaiter().GetResult()

Comment: Please do NOT edit other people's answers to insert a link to your own. If you believe your answer is better, leave it as a comment instead.
Comment: This caused a deadlock inside an asmx web method. Nevertheless, wrapping the method call in a Task.Run() made it work: Task.Run(() => BlahAsync()).GetAwaiter().GetResult()
Comment: Works for me for simple stuff.  Also, if the method returns an IAsyncOperation, I had to convert it to a Task first:
BlahAsync().AsTask().GetAwaiter().GetResult();
Comment: I like this approach best syntactically because it does not involve lambdas.
Comment: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1.getawaiter?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(System.Threading.Tasks.Task%601.GetAwaiter)%3Bk(TargetFrameworkMoniker-.NETFramework%2CVersion%3Dv4.6.1)%3Bk(DevLang-csharp)%26rd%3Dtrue&view=netframework-4.6.2#remarks says about `GetAwaiter()`, "This method is intended for compiler user rather than use directly in code."
Comment: Should be a solution for the question as it addresses the problem, minimal custom code, and answer perfectly explains key points.
Comment: This way (BlahAsync()).GetAwaiter().GetResult()) can cause the program to stall and never finish. This is why I had to switch to Rachel's for much better performance.
Comment: much cleaner than accepted, thanks, should remembered :D
Comment: Put the 'too lazy' answer nearer to the top! X
Answer: It's much simpler to run the task on the thread pool, rather than trying to trick the scheduler to run it synchronously. That way you can be sure that it won't deadlock. Performance is affected because of the context switch.
Task<MyResult> DoSomethingAsync() { ... }

// Starts the asynchronous task on a thread-pool thread.
// Returns a proxy to the original task.
Task<MyResult> task = Task.Run(() => DoSomethingAsync());

// Will block until the task is completed...
MyResult result = task.Result;

Comment: @sgnsajgon You are wrong. Task.Run is different than Task.Factory.StartNew in that it automatically unwraps the result already. See [this article](http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx).
Comment: Then you call task.Wait(). The data type is simply Task.
Comment: Let's assume that *DoSomethingAsync()* is long-running async method as whole (internally it awaits a long-running task), but it yields back a flow control to its caller quickly, thus the lambda argument work ends also quickly. The result of Tusk.Run() may *Task* or *Task>*, so you are awaiting a result of outer task which is completed quickly, but inner task ( due to awaiting long-running job in async method) is still running. Conclusions are that we probably need to use *Unwrap()* approach (as was done in @J.Lennon post) to achieve synchronous behaviour of async method.
Comment: Can I just write `Task.Run(DoSomethingAsync)` instead? This removes one level of delegates.
Comment: Yep. Going the opposite direction, though, as in `Task task = Task.Run(async () => await DoSomethingAsync());` is more explicit and addresses the concern by @sgnsajgon that it might be returning a Task>. The correct overload of Task.Run is selected either way, but the async delegate makes your intent obvious.
Comment: And if the task is void (without result)?
Answer:
I'm learning about async/await, and ran into a situation where I need to call an async method synchronously. How can I do that?

The best answer is you don't, with the details dependent on what the "situation" is.
Is it a property getter/setter? In most cases, it's better to have asynchronous methods than "asynchronous properties". (For more info, see my blog post on asynchronous properties).
Is this an MVVM app and you want to do asynchronous data binding? Then use something like my NotifyTask, as described in my MSDN article on asynchronous data binding.
Is it a constructor? Then you probably want to consider an asynchronous factory method. (For more info, see my blog post on asynchronous constructors).
There's almost always a better answer than to do sync-over-async.
If it's not possible for your situation (and you know this by asking a question here describing the situation), then I'd recommend just using synchronous code. Async all the way is best; sync all the way is second-best. Sync-over-async is not recommended.
However, there are a handful of situations where sync-over-async is necessary. Specifically, you are constrained by the calling code so that you have to be sync (and have absolutely no way to re-think or re-structure your code to allow asynchrony), and you have to call async code. This is a very rare situation, but it does come up from time to time.
In that case, you would need to use one of the hacks described in my article on brownfield async development, specifically:

Blocking (e.g., GetAwaiter().GetResult()). Note that this can cause deadlocks (as I describe on my blog).
Running the code on a thread pool thread (e.g., Task.Run(..).GetAwaiter().GetResult()). Note that this will only work if the asynchronous code can be run on a thread pool thread (i.e., is not dependent on a UI or ASP.NET context).
Nested message loops. Note that this will only work if the asynchronous code only assumes a single-threaded context, not a specific context type (a lot of UI and ASP.NET code expect a specific context).

Nested message loops are the most dangerous of all the hacks, because it causes re-entrancy. Re-entrancy is extremely tricky to reason about, and (IMO) is the cause of most application bugs on Windows. In particular, if you're on the UI thread and you block on a work queue (waiting for the async work to complete), then the CLR actually does some message pumping for you - it'll actually handle some Win32 messages from within your code. Oh, and you have no idea which messages - when Chris Brumme says "Wouldn't it be great to know exactly what will get pumped? Unfortunately, pumping is a black art which is beyond mortal comprehension.", then we really have no hope of knowing.
So, when you block like this on a UI thread, you're asking for trouble. Another cbrumme quote from the same article: "From time to time, customers inside or outside the company discover that we are pumping messages during managed blocking on an STA [UI thread]. This is a legitimate concern, because they know that it's very hard to write code that's robust in the face of reentrancy."
Yes, it is. Very hard to write code that's robust in the face of reentrancy. And nested message loops force you to write code that's robust in the face of reentrancy. This is why the accepted (and most-upvoted) answer for this question is extremely dangerous in practice.
If you are completely out of all other options - you can't redesign your code, you can't restructure it to be async - you are forced by unchangeable calling code to be sync - you can't change the downstream code to be sync - you can't block - you can't run the async code on a separate thread - then and only then should you consider embracing reentrancy.
If you do find yourself in this corner, I would recommend using something like Dispatcher.PushFrame for WPF apps, looping with Application.DoEvents for WinForm apps, and for the general case, my own AsyncContext.Run.
Comment: This answer goes a long way over my head. *"Use async all the way down"* is confusing advice, due to clearly not being possible to follow. A program with an async `Main()` method doesn't compile; at some point you've *got* to bridge the gap between the sync and async worlds. It's not a *"**very** rare situation"*, it's necessary in literally every program that calls an async method. There is no option to not *"do sync-over-async"*, just an option to shunt that burden up to the calling method instead of shouldering it in the one you're currently writing.
Comment: @MarkAmery: Sync-over-async is necessary in the `Main` method of console apps. ASP.NET, unit test frameworks, and every UI system all support async natively. Even if all your apps are console apps, you'd only need to do sync-over-async once per app. (of course, library callbacks that don't support async yet may require additional hacks).
Comment: @AlexeiLevenkov: I don't feel right doing that, for a few reasons: 1) The answer on the linked question is fairly out-of-date. 2) I've written an [entire article on the subject](https://msdn.microsoft.com/en-us/magazine/mt238404.aspx) that I feel is more complete than any existing SO Q/A. 3) The accepted answer on this question is *extremely* popular. 4) I am *vehemently* opposed to that accepted answer. So, closing this as a dup of that would be an abuse of power; closing that as a dup of this (or merging) would empower a dangerous answer even more. I let it be, and leave it to the community.
Comment: Great. I'm about to put `async` on all of the methods in my application now. And that's a lot. Can't this just be the default?
Comment: It worth to mention that as you [replied me](http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html#comment-8d8069d0-4401-11e9-ab1b-b1484e5f4180) and based on your blog [here](https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html), the deadlock is not a problem for ASP.NET Core!
Comment: Stephen, there is another very similar [qestion](http://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c) which you provided awesome answer too. Do you think one of them can be closed as duplicate or maybe merge request or bring up on meta first (as each q has ~200K views 200+ votes)? Suggestions?
Comment: Ok. I'll consider bringing it up on meta than in some way.
Answer: If I am reading your question right - the code that wants the synchronous call to an async method is executing on a suspended dispatcher thread. And you want to actually synchronously block that thread until the async method is completed.
Async methods in C# 5 are powered by effectively chopping the method into pieces under the hood, and returning a Task that can track the overall completion of the whole shabang. However, how the chopped up methods execute can depend on the type of the expression passed to the await operator.
Most of the time, you'll be using await on an expression of type Task. Task's implementation of the await pattern is "smart" in that it defers to the SynchronizationContext, which basically causes the following to happen:

If the thread entering the await is on a Dispatcher or WinForms message loop thread, it ensures that the chunks of the async method occurs as part of the processing of the message queue.
If the thread entering the await is on a thread pool thread, then the remaining chunks of the async method occur anywhere on the thread pool.

That's why you're probably running into problems - the async method implementation is trying to run the rest on the Dispatcher - even though it's suspended.
.... backing up! ....
I have to ask the question, why are you trying to synchronously block on an async method? Doing so would defeat the purpose on why the method wanted to be called asynchronously. In general, when you start using await on a Dispatcher or UI method, you will want to turn your entire UI flow async. For example, if your callstack was something like the following:

[Top] WebRequest.GetResponse()
YourCode.HelperMethod()
YourCode.AnotherMethod()
YourCode.EventHandlerMethod()
[UI Code].Plumbing() - WPF or WinForms Code
[Message Loop] - WPF or WinForms Message Loop

Then once the code has been transformed to use async, you'll typically end up with

[Top] WebRequest.GetResponseAsync()
YourCode.HelperMethodAsync()
YourCode.AnotherMethodAsync()
YourCode.EventHandlerMethodAsync()
[UI Code].Plumbing() - WPF or WinForms Code
[Message Loop] - WPF or WinForms Message Loop

Actually Answering
The AsyncHelpers class above actually works because it behaves like a nested message loop, but it installs its own parallel mechanic to the Dispatcher rather than trying to execute on the Dispatcher itself. That's one workaround for your problem.
Another workaround is to execute your async method on a threadpool thread, and then wait for it to complete. Doing so is easy - you can do it with the following snippet:
var customerList = TaskEx.RunEx(GetCustomers).Result;

The final API will be Task.Run(...), but with the CTP you'll need the Ex suffixes (explanation here).
Comment: +1 for the detailed explanation, however `TaskEx.RunEx(GetCustomers).Result` hangs the application when it gets run on a suspended dispatcher thread. Also, the GetCustomers() method is normally run async, however in one situation it needs to run synchronously, so I was looking for a way to do that without building a sync version of the method.
Comment: +1 for "why are you trying to synchronously block on an async method?" There is always a way to properly use `async` methods; nested loops should certainly be avoided.
Answer: This is working well for me
public static class TaskHelper
{
    public static void RunTaskSynchronously(this Task t)
    {
        var task = Task.Run(async () => await t);
        task.Wait();
    }

    public static T RunTaskSynchronously<T>(this Task<T> t)
    {
        T res = default(T);
        var task = Task.Run(async () => res = await t);
        task.Wait();
        return res;
    }
}

Comment: That is not correct. The Task.Run will return Task. See this overload http://msdn.microsoft.com/en-us/library/hh194918(v=vs.110).aspx
Comment: How is this supposed to be used? This deadlocks in WPF: `MyAsyncMethod().RunTaskSynchronously();`
Comment: This only works for platforms without synchronization contexts (console apps, ASP.NET Core apps etc). For platforms with sync context, this work for only cold tasks, aka not the 99% normal cases. For tasks that has already started, there is no point in wrapping it in `Task.Run`. In other words, in normal usages like `GetFromNetworkAsync().RunTaskSynchronously()` hangs for UI apps.
Comment: You need to also use *Task.Unwrap* method, because your *Task.Wait* statement causes waiting for outer Task (created by *Task.Run*), not for inner *await t* Task passed as parameter of extension method. Your *Task.Run* method returns not Task, but Task>. In some simple scenarios your solution may works because of TaskScheduler optimizations, for example using *TryExecuteTaskInline* method to execute Tasks within current thread during *Wait* operation .Please look at my comment to [this](http://stackoverflow.com/a/17094801/823040) answer.
Answer: Tested in .Net 4.6. It can also avoid deadlock.
For async method returning Task.
Task DoSomeWork();
Task.Run(async () => await DoSomeWork()).Wait();

For async method returning Task<T>
Task<T> GetSomeValue();
var result = Task.Run(() => GetSomeValue()).Result;

Edit:
If the caller is running in the thread pool thread (or the caller is also in a task), it may still cause a deadlock in some situation.
Comment: My answar after almost 8 years :) The second example - will produce a deadlock in all scheduled context that are mainly used (console app / .NET core / desktop app / ...).
here you have more overview what i'm talking about now:
https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d
Comment: `Result` is perfect for the job if you want a synchronous call, and downright dangerous otherwise.  There is nothing in the name `Result` or in the intellisense of `Result` that indicates it is a blocking call.  It really should be renamed.
Answer: I've faced it a few times, mostly in unit testing or in a windows service development. Currently I always use this feature:
        var runSync = Task.Factory.StartNew(new Func<Task>(async () =>
        {
            Trace.WriteLine("Task runSync Start");
            await TaskEx.Delay(2000); // Simulates a method that returns a task and
                                      // inside it is possible that there
                                      // async keywords or anothers tasks
            Trace.WriteLine("Task runSync Completed");
        })).Unwrap();
        Trace.WriteLine("Before runSync Wait");
        runSync.Wait();
        Trace.WriteLine("After runSync Waited");

It's simple, easy and I had no problems.
Comment: @AndreFeijo I dont know what it is, but this is essentially `Task.Run(() => ..).Wait()` (with slight tweaks). Both should work.
Comment: This is the only one that didn't deadlock for me.
Answer: I found this code at Microsoft.AspNet.Identity.Core component, and it works.
private static readonly TaskFactory _myTaskFactory = new
     TaskFactory(CancellationToken.None, TaskCreationOptions.None,
     TaskContinuationOptions.None, TaskScheduler.Default);

// Microsoft.AspNet.Identity.AsyncHelper
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
    CultureInfo cultureUi = CultureInfo.CurrentUICulture;
    CultureInfo culture = CultureInfo.CurrentCulture;
    return AsyncHelper._myTaskFactory.StartNew<Task<TResult>>(delegate
    {
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = cultureUi;
        return func();
    }).Unwrap<TResult>().GetAwaiter().GetResult();
}

Comment: https://github.com/aspnet/AspNetIdentity/blob/master/src/Microsoft.AspNet.Identity.Core/AsyncHelper.cs
Comment: I wonder why there is a call to Unwrap ()?
Answer: The simplest way I have found to run task synchronously and without blocking UI thread is to use RunSynchronously() like:
Task t = new Task(() =>
{
   //.... YOUR CODE ....
});
t.RunSynchronously();

In my case, I have an event that fires when something occurs.  I dont know how many times it will occur.  So, I use code above in my event, so whenever it fires, it creates a task.  Tasks are executed synchronously and it works great for me.  I was just surprised that it took me so long to find out of this considering how simple it is.  Usually, recommendations are much more complex and error prone.  This was it is simple and clean.
Comment: But how could we use this method when the async code returns something we need?
Comment: This works for cold tasks, not tasks that has begun.
Comment: This will not work because "YOUR CODE" in your example must be synchronous code for this Task constructor. But we actually have async code we would want to put there.
Answer: Just a little note - this approach:
Task<Customer> task = GetCustomers();
task.Wait()

works for WinRT.
Let me explain:
private void TestMethod()
{
    Task<Customer> task = GetCustomers(); // call async method as sync and get task as result
    task.Wait(); // wait executing the method
    var customer = task.Result; // get's result.
    Debug.WriteLine(customer.Name); //print customer name
}
public class Customer
{
    public Customer()
    {
        new ManualResetEvent(false).WaitOne(TimeSpan.FromSeconds(5));//wait 5 second (long term operation)
    }
    public string Name { get; set; }
}
private Task<Customer> GetCustomers()
{
    return Task.Run(() => new Customer
    {
        Name = "MyName"
    });
}

Moreover this approach works for Windows Store solutions only!
Note: This way isn't thread safe if you call your method inside of other async method (according to comments of @Servy)
Comment: This can very easily result in deadlocks when called in asynchronous situations.
Comment: Then you need to worry about having the timeout being reached when the operation isn't actually done, which is very bad, and also the time spent waiting until the timeout in the cases where it deadlocks (and in that case you're *still* continuing on when it's not done).  So no, that doesn't fix the problem.
Comment: I explained this solution, check EDIT section.
Comment: @Servy make sense. So as I get correct using Wait(timeOut) can help,  right?
Comment: @Servy Looks like I have to implement `CancellationToken` for my solution.
Comment: @Servy Why, could you explain a bit?
Comment: I could, or you could just ask Google about it, or for that matter just look at the comments on the answers that are, more or less, a duplicate of yours; in particular the one with the most votes, as it has [a link to] an explanation.
Comment: Your example works because your *GetCustomers()* method is not the *async* method in terms of C# 5.0 (no *async-await* keywords pair), but just a *Task-returning* method. The question was about C# 5.0 *async* method. Mark your *GetCustomers()* method as *async*, then *await Task.Run()* invocation, then you will probably get deadlock.
Answer: NOTE: I think as best practice is not recommended to change the nature of the action if it is asynchronous the best thing is handling as it is (async all the way). In that way you can get other benefits like parallel processing / multi-threading, etc.
Seeing the other answers did not use this approach, I want to post it here as well:
var customers = GetCustomersAsync().GetAwaiter().GetResult();

Comment: This is still equivalent to calling `var customer = GetCustomersAsync().Result` but now exceptions are unwrapped instead of being wrapped inside an AggregatedException.
Answer: In your code, your first wait for task to execute but you haven't started it so it waits indefinitely. Try this:
Task<Customer> task = GetCustomers();
task.RunSynchronously();

Edit:
You say that you get an exception. Please post more details, including stack trace.
Mono contains the following test case:
[Test]
public void ExecuteSynchronouslyTest ()
{
        var val = 0;
        Task t = new Task (() => { Thread.Sleep (100); val = 1; });
        t.RunSynchronously ();

        Assert.AreEqual (1, val);
}

Check if this works for you. If it does not, though very unlikely, you might have some odd build of Async CTP. If it does work, you might want to examine what exactly the compiler generates and how Task instantiation is different from this sample.
Edit #2:
I checked with Reflector that the exception you described occurs when m_action is null. This is kinda odd, but I'm no expert on Async CTP. As I said,  you should decompile your code and see how exactly Task is being instantiated any how come its m_action is null.
Comment: @gaearon I think you had got downvotes because your post is not applicable to question. The discussion is about async-await methods, not about simple Task-returning methods. Moreover, in my opinion, async-await mechanism is a syntax sugar, but not so trivial - there is continuation , context capturing, local context resuming, enhanced local exceptions handling, and more. Then, you shouldn't invoke *RunSynchronously* method on result of the async method, because by definition asynchronous method should return Task that is currently at least scheduled, and more than once is in the running state.
Comment: `async` and `async` keywords are nothing more than syntax sugar. Compiler generates code to create `Task` in `GetCustomers()` so that's where I would look first. As for exception, you only posted exception message, which is useless without exception type and stack trace. Call exception's `ToString()` method and post output in the question.
Comment: I adjusted my question to make the code I had attempted a bit clearer. RunSynchronously returns an error of `RunSynchronously may not be called on a task unbound to a delegate`. Google is no help since all the results for that are in chinese...
Comment: I think the difference is that I don't create the Task and then try to run it. Instead, the task is created by the async method when the `await` keyword is used. The exception posted in my earlier comment is the exception I get, although it is one of the few that I cannot Google and find a cause or resolution for.
Comment: @gaearon: I posted the exception details and stack trace in my original question.
Comment: I'm also wondering if you're using `Task` from .NET 4.0 (not some preview release) and stable version of Async CTP.
Comment: I'm using the most stable release of AsyncCTP as of a month or two ago, and the .Net 4.0 Task object. I actually found an alternative that works, although its not my code so I'm still working to fully understand it.
Answer: Why not create a call like:
Service.GetCustomers();

that isn't async.
Comment: That's going to be what I do if I can't get this working... create a Sync version in addition to an Async version
Comment: What if you cannot write your own functions since you are using a lib?
Answer: This answer is designed for anyone who is using WPF for .NET 4.5.
If you attempt to execute Task.Run() on the GUI thread, then task.Wait() will hang indefinitely, if you do not have the async keyword in your function definition.
This extension method solves the problem by checking to see if we are on the GUI thread, and if so, running the task on the WPF dispatcher thread.
This class can act as the glue between the async/await world and the non-async/await world, in situations where it is unavoidable, such as MVVM properties or dependencies on other APIs that do not use async/await.
///
///     Intent: runs an async/await task synchronously. Designed for use with WPF.
///     Normally, under WPF, if task.Wait() is executed on the GUI thread without async
///     in the function signature, it will hang with a threading deadlock, this class
///     solves that problem.
///
public static class TaskHelper
{
    public static void MyRunTaskSynchronously(this Task task)
    {
        if (MyIfWpfDispatcherThread)
        {
            var result = Dispatcher.CurrentDispatcher.InvokeAsync(async () => { await task; });
            result.Wait();
            if (result.Status != DispatcherOperationStatus.Completed)
            {
                throw new Exception("Error E99213. Task did not run to completion.");
            }
        }
        else
        {
            task.Wait();
            if (task.Status != TaskStatus.RanToCompletion)
            {
                throw new Exception("Error E33213. Task did not run to completion.");
            }
        }
    }

    public static T MyRunTaskSynchronously<T>(this Task<T> task)
    {
        if (MyIfWpfDispatcherThread)
        {
            T res = default(T);
            var result = Dispatcher.CurrentDispatcher.InvokeAsync(async () => { res = await task; });
            result.Wait();
            if (result.Status != DispatcherOperationStatus.Completed)
            {
                throw new Exception("Error E89213. Task did not run to completion.");
            }
            return res;
        }
        else
        {
            T res = default(T);
            var result = Task.Run(async () => res = await task);
            result.Wait();
            if (result.Status != TaskStatus.RanToCompletion)
            {
                throw new Exception("Error E12823. Task did not run to completion.");
            }
            return res;
        }
    }

    ///
    ///     If the task is running on the WPF dispatcher thread.
    ///
    public static bool MyIfWpfDispatcherThread
    {
        get
        {
            return Application.Current.Dispatcher.CheckAccess();
        }
    }
}

Answer: Simply calling .Result; or .Wait() is a risk for deadlocks as many have said in comments. Since most of us like oneliners you can use these for .Net 4.5<
Acquiring a value via an async method:
var result = Task.Run(() => asyncGetValue()).Result;

Syncronously calling an async method
Task.Run(() => asyncMethod()).Wait();

No deadlock issues will occur due to the use of Task.Run.
Source:
https://stackoverflow.com/a/32429753/3850405
Comment: If you vote down please add a comment why. Hard to improve answer otherwise
Answer: use below code snip
Task.WaitAll(Task.Run(async () => await service.myAsyncMethod()));

Comment: Task.WaitAll adds nothing here. Why not just Wait?
Answer: This is works for me
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    public static class AsyncHelper
    {
        private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);

        public static void RunSync(Func<Task> func)
        {
            _myTaskFactory.StartNew(func).Unwrap().GetAwaiter().GetResult();
        }

        public static TResult RunSync<TResult>(Func<Task<TResult>> func)
        {
            return _myTaskFactory.StartNew(func).Unwrap().GetAwaiter().GetResult();
        }
    }

    class SomeClass
    {
        public async Task<object> LoginAsync(object loginInfo)
        {
            return await Task.FromResult(0);
        }
        public object Login(object loginInfo)
        {
            return AsyncHelper.RunSync(() => LoginAsync(loginInfo));
            //return this.LoginAsync(loginInfo).Result.Content;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var someClass = new SomeClass();

            Console.WriteLine(someClass.Login(1));
            Console.ReadLine();
        }
    }
}

Answer: I think the following helper method could also solve the problem.
private TResult InvokeAsyncFuncSynchronously<TResult>(Func< Task<TResult>> func)
    {
        TResult result = default(TResult);
        var autoResetEvent = new AutoResetEvent(false);

        Task.Run(async () =>
        {
            try
            {
                result = await func();
            }
            catch (Exception exc)
            {
                mErrorLogger.LogError(exc.ToString());
            }
            finally
            {
                autoResetEvent.Set();
            }
        });
        autoResetEvent.WaitOne();

        return result;
    }

Can be used the following way:
InvokeAsyncFuncSynchronously(Service.GetCustomersAsync);

Comment: I just wrote almost the identical code (line by line the same) but instead using SemaphoreSlim instead of the auto reset event.   Wish I had seen this sooner.  I find this approach to prevent deadlocks and keeps your async code running the same as it does in true asynchronous scenarios.  Not really sure why this is a bad idea.  Seems much cleaner than the other approaches I have seen above.
Comment: It is not an true "synchronously".Y ou create two threads and wait in first results of other.
Comment: and all things aside, this is a very bad idea.
Comment: @DanPantry I am actually seeing some deadlocks now with this approach that I don't understand.  Could you expand on why it is a bad idea?
Comment: My bad.  I got. this working now.  My problem was that I was creating the task on the main thread and then passed that task to the invoke async method.  Thanks @donttellya your code helped me out.
Answer: I have found that SpinWait works pretty well for this.
var task = Task.Run(()=>DoSomethingAsyncronous());

if(!SpinWait.SpinUntil(()=>task.IsComplete, TimeSpan.FromSeconds(30)))
{//Task didn't complete within 30 seconds, fail...
   return false;
}

return true;

The above approach doesn't need to use .Result or .Wait().  It also lets you specify a timeout so that you're not stuck forever in case the task never completes.
Comment: This is polling (spinning), the delegate will be taking thread from pool up to 1000 times per second. It may not return control immediately after task is finished (up to [10+ms](https://referencesource.microsoft.com/#mscorlib/system/threading/SpinWait.cs,120) error). If finished by timeout the task will continues running, which makes timeout practically useless.
Comment: Actually, I'm using this all over the place in my code and when the condition is met, SpinWaitSpinUntil() immediately exits.  So whichever comes first, 'condition met' or timeout, the task exits.  It does not continue to run.
Answer:     private int GetSync()
    {
        try
        {
            ManualResetEvent mre = new ManualResetEvent(false);
            int result = null;

            Parallel.Invoke(async () =>
            {
                result = await SomeCalcAsync(5+5);
                mre.Set();
            });

            mre.WaitOne();
            return result;
        }
        catch (Exception)
        {
            return null;
        }
    }


Empathy Map as alternative or addition to (ad hoc) personas?

Question: Would you say an Empathy Map is an alternative approach to (ad hoc) personas or is it kind of an addition when you already have created personas (first the personas, second the empathy maps)? Like described here: http://www.cooper.com/journal/2014/5/persona-empathy-mapping
It's a little bit confusing for me. I want to create personas, starting from zero. I'm thinking about using an Empathy Map or ad hoc personas like described here: https://uxmag.com/articles/using-proto-personas-for-executive-alignment
What do you think I should start with? Thanks!
Answer: I think that personas, empathy maps and customer journeys are pieces of UX assets that provide related information but in slightly different context (that you use in designing the overall user experience). But terminology aside, lets think about the types of information that these assets capture, and how they are applied to designing interfaces because that will give you a better idea of where to start if you are a little bit confused about where to start.
Firstly, all applications are designed based on the assumption that they will cater for the needs of a particular type/group of users. So how do you capture the research information about the different users that will interact with your product/service, and what information will give you guidances on how to design for those people? There are definite factors in terms of gender, age, occupation, ethnicity as well as behavioural factors such as their familiarity with technology (which you shouldn't assume from age), knowledge domain (if you have a specialized product/service), interests, habits, etc. Personas tend to cover more of the demographics and less of the behavioural side of things.
I think this is where some of the things that I have seen in the empathy map that helps you get inside the head of the people that you create in the personas. Because just knowing the vital stats of someone doesn't really mean that you'll know how they think or behave (think about online dating profiles). But you need to be careful not to mix up the information in personas with empathy maps, depending on whether the personas were created by 'averaging' specific user groups, and whether empathy maps were developed from raw user input or an extension of a specific persona.
Then you need to think about how a person would behave in a specific situation rather than in general circumstances, because again just because someone normally does something in a certain way doesn't immediately mean that they will follow the same patterns of behaviour in a different context (although it is an assumption that you can make then try to validate). Again if we try to think about online dating experiences, just because you have a preference for say a blonde person doesn't mean that you'll like every blonde person's profile or not like a brunette. So the way to understand how a person might behave and feel given a specific set of circumstances is to observe and enquire so that you can capture this type of information in a customer journey map.
So once you have information about the different types of users, how they think in general, and how they behave given a specific scenario, you have the basic information for starting to produce your high level designs that you can test these user research finding. This then allows you to continually refine your model and understanding about the users and create a knowledgebase that contains your research data.
I hope this gives you a good understanding of what to look out for, and how to integrate all the research information and document them for design purposes.
Answer: Create persona's first. It will give you basic understanding about who you are designing for.
It also lays down the basics for your customer journey or empathy map so it won't be wasted time. So it's indeed an addition to persona's and not an alternative.
The article from Cooper shows how they use empathy mapping as how persona's would be used: As an asset to refer to when some understanding of the user is needed during the design process. They just merged the for them most important information into a so called persona empathy map.


Name of short story about post-apocalyptic society and Daylight Savings

Question: I'm looking for a short story I read a while ago. It's a placed in the indeterminate future, and a traveler from one civilization is bargaining for an artifact from the past (current time) and is considering a clock. All the characters stay up to see the time jump: a remnant of when people created an hour of time (daylight saving) and were then destroyed. Any help would be appreciated!
Edit: I read it online within the last year for sure, and probably within six months.
Edit: as a commenter mentioned it was formatted as a blog post,which probably makes it much harder to find.
Comment: About how long is "a while"? Any memory of what sort of publication you read this in - online, magazine, collection of one author's work, anthology of several authors' work?
Comment: Yeah, there was no time-travel involved; it was set long after civilization had collapsed, and the clock was a mysterious object whose purpose was unknown. IIRC it came into the possession of a tribe who treated it as a quasi-religious object and were awestruck when it skipped an hour. Or possibly when it failed to do so as expected. The details are hazy...
Comment: Did you read it in an anthology? A magazine? Online?
Comment: I've definitely read this story -- in fact, I thought this question had to be a duplicate. The version I read was online, possibly formatted as a blog post, but I don't know for sure that it was the original.
Comment: That's right! It was a blog post!
Comment: I apparently completely misunderstood.
Comment: If the answer is The Witching Hour, please click the check mark to accept the answer.
Answer: I found it: "The Witching Hour" by Scott Alexander.

"They created a single hour," said Fin. "Of the nine thousand hours in a year, all but one were made by the gods, but one was made by Man. What stopped them from creating more, from creating an infinite number of hours, from becoming immortal by arresting the progression of Time? We will never know. But it is my belief that when they saw what men had done, the gods stopped them before they could do worse. Meical, I believe that is how the Lost World ended. A last ditch effort by the gods to save Time itself from the hubris of Man."


If you are a multiclass spellcaster, does your save DC vary based on which class you got a spell from?

Question: For instance, let's posit a character, sorc 1 wiz 1, that can cast Ice Knife through Sorcerer, and Burning Hands through wizard.  But their INT is 16, and their CHA is 18.  What would their save DC base off of, for Burning Hands?
Answer: Yes, it does
Your spell DC is specifically based on your class.
Sorcerers have the class feature:

In addition, you use your Charisma modifier when setting the saving throw DC for a sorcerer spell you cast and when making an attack roll with one. (PHB, p. 101, bold added).

While Wizards have the feature:

you use your Intelligence modifier when setting the saving throw DC for a wizard spell you cast and when making an attack roll with one. (PHB, p. 114, bold added)

These features apply both to single class sorcerers and wizards, and to multi-classed ones. As stated in PHB, p. 164 in the rules on Multiclassing (credit to Rubiksmoose for pointing this out):

Each spell you know and prepare is associated with one of your classes, and you use the spellcasting ability of that class when you cast the spell.

In this case, it would depend on one thing: whether you doubled up on spells. You would know two first level spells as a level 1 Sorcerer, but you only mentioned one. If you also selected "burning hands" as one of your two Sorcerer spells, then you could use your Charisma ability, and the DC would be 8+2+4=14. But if you didn't know "burning hands" as a Sorcerer, but only as a Wizard, then your DC would be 8+2+3=13.
Comment: Thanks, Rubiksmoose. I was looking for something like that (but was too stuck on looking for DCs specifically.) I'll include that and credit you.
Comment: Thanks for noting that! I'd missed it completely. And it actually made me realize that I'd given a misleading answer before (implying that class spell lists are all that matters, rather than where you actually learned the spell from).


iPhone - Safari parent window focus issue

Question: I am having a peculiar problem with a website i am developing. The problem only happens on the iPhone(safari).
My setup is as follows.
1) I have a CLIENT page - shows an initial page, and has a login button.
2) User clicks on the LOGIN button, and is shown a LOGIN popup/new-window  (this is created by posting a form using jquery 'submit' function with target='_blank')
CLIENT.html
var formData = '<form style="display: none; margin: 0; padding: 0; border-width: 0; overflow: hidden;" id="MyFormId" action="https://MYSERVER.COM/v2/widgets" method="POST" target="_blank"><input type="hidden" name="action" value="connect"/><input type="hidden" name="referringURL" value="http://MYCLIENT.com/ClientPage.html"/><input type="hidden" name="cartOwnerId" value="A2R6QUFKT17A1O"/></form>';

jQuery("#"+this.getLocation()).append(formData);

jQuery("#"+formIdName).submit();

3) User enters credentials on LOGIN window, and submits. A call is made to the SERVER to authenticate. On SUCCESSFUL authentication, we want to

CLOSE the LOGIN window
REDIRECT Client page to new URL

4) Everything works as planned, EXCEPT that the Client window (that created the LOGIN popup/new window), does not return to full-screen (after the LOGIN window closed).
If i try to put a window.opener.focus() in the LOGIN page javascript, i get focus on the CLIENT page, but the LOGIN page does not close(even if i put window.close before the window.opener.focus())
LOGIN html
jQuery(document).ready(function() {
  ...
  ...

    window.close();

    window.opener.focus()
});

Is there any tips on how i can close the LOGIN window, and redirect the client page to a new URL, and make the Client window full screen?
Any tips would be appreciated.
Thanks
Answer: Does something like this work:
In opener:
window.closePopup = function () {
  window.popup.close();
  window.focus();
}
// open login popup
window.popup = window.open(...);

After user logs in in popup window:
window.opener.closePopup();

THat is, don't have a window close itself, but have the opener close the popup. I've tried something like this and it seems to work sometimes... I haven't quite been able to isolate why it doesn't work. I know one thing that happens in my case is that the user has to interact with the popup window in order for the window.opener.closePopup() to work...


What to do about Foxacid

Question: <code>   8 days ago in Germany where my Windows 7 PC is located I  upgraded its U.S. Firefox browser by hitting the Help/On Firefox tab (I think it was ver 35.0a1, or something like that), I was focibly redirected to a localized version of the download site,- and then all hell broke loose.
   It took me several days to start the system again; there had never before been an attack fierce like that.
   Could it have been that ominous FOXACID attack [very good: The Guardian 4 oct. 2013] of which they won't spare even individual Tor users?
    And what can we do about it?
</code>
Answer: The behavior you are describing is weird, since Mozilla changed the update system in Firefox since a while to a silent updating system. Furthermore, the Firefox version you're running is not stable one, since it's 35.0a1 which means it's an alpha version belonging to the aurora tree (even less stable than a beta version).
My advice is summarized as follows:
1- Install and run an AntiVirus/AntiSpyware to make sure your system is not infected and your programs are not compromised.
2- Synchronize your bookmarks, history, tabs, passwords, etc using Firefox Sync, if you want to keep them.
3- Uninstall your copy of Firefox.
4- Go to https://www.mozilla.org/en-US/ (that will force the English website to show regardless of your geographic location) and get a fresh and stable copy of Firefox there. You won't need to manually update it afterwards since the updates will be silent and automatic.
5- Install the TorButton addon, HTTPS everywhere addon, and optionally NoScript addon in Firefox from the AddOns submenu.
6- As a better (and very recommended) alternative of steps 4 & 5, install the TorBrowserBundle from https://torproject.org, which includes a customized Firefox browser and with the mentioned addons pre-installed, called TorBrowser.
7- Use Firefox Sync to restore your bookmarks, passwords, history, etc.

What to do about Foxacid


Give users lives and gender

Question: I'm pretty new to javascript/dom scripting and I'm doing small projects to get better. My idea was a Truth or Dare'ish game where you can add as many users as you want, after that the users will get added to this Winwheel:
"https://github.com/zarocknz/javascript-winwheel". Then you spin the wheel and you get "x player has to this".
My first thought was to add all users to an array, but my problem is I want all players to have a health system if you want to skip your turn, and every user has f.eg 3 lives. and I also want to store if the user is a boy or a girl. How can I Store info as lives for each individual, and gender when all the users are stored in an array?
Comment: You do it the same way as without an array.
Comment: Care to elaborate?
Comment: @Tweey Each user could be represented by a standard JavaScript object, then you just add the objects to the list. I believe melpomene meant that the representation of the users is completely separate from how the users are stored. One doesn't effect the other.
Answer: You could store an array of objects! Each object would represent a user.
So you could have a user object with this schema:
<code>{
    name: 'John',
    lives: 3,
    gender: 'male'
}
</code>
And you could keep adding as many properties as you want.
Then you could push those items to an array. It would look like this:
<code>[
    {
        name: 'John',
        lives: 3,
        gender: 'male'
    },
    {
        name: 'Vanessa',
        lives: 2,
        gender: 'female'
    },
    ...
]
</code>
Hope this helps!
Comment: I haven't used OOP much before but I will try. Thank you very much!

Give users lives and gender


How can I place links at the bottom of the site?

Question: is it possible to place my privacy notice and cookies policy in the footer menu?  Is there one and how do I do it?
Comment: I recommend you to hire someone. It doesn't sound like you are familiar with HTML or PHP at all so you are going to have a hard time if you want to finish it until tomorrow
Answer: It's impossible to give step-by-step instructions since every Craft site is unique and built differently.
The front-end templates for your site live in the craft/templates folder on your server.  You can change the look and layout of your site by editing those files, which are a combination of Twig and HTML.  Thanks like JavaScript, CSS files, images and assets will typically live in your site's public HTML folder.
Here's a list of learning resources to help get you up to speed on Craft and some links at the end in case you need help finding a developer.
Craft Official Docs & Support

Craft CMS docs - The official Craft CMS documentation
Craft Slack group - The Craft development team is in Slack every day along with 6,000+ other Craft developers and users from all over the world.
Craft Stack Exchange - You obviously found this one, but it is generally the best place to ask "how do I" type questions.
Official support email at email@example.com

Learn Craft

Mijingo Craft Tutorials - Mijingo is our official education and training partner. They have a number of excellent free and paid resources for Craft CMS & Craft Commerce. Ryan Irelan, Mijingo's founder, also offers customized training online or on-site.
Tuts+ Tutorials - Not official but very good and low cost (most are $9).

Professional Services

Partner Match - If you need implementation help for Craft, we can match you with one of our Craft Service Partners or Craft Experts. We work with enterprise level partners, freelancers, and everyone in between.


is there is any list of bugs available for magento ver 1.9.1, i need just a list with solutions

Question: i have just installed a site in magento 1.9.1 , i have found during the research of the blogs that there are bugs which were there in this system. is there is ready list wth solution is available. can you provide me a link to that.
Comment: Yes, the Magento bug tracker... Sign up at Magento.com
Answer: There is not really such a List.
Sure, there are solutions out there. But you cant be sure if they make things worse instead of helping.
That is mostly the reason why they are not fixed yet, because Magento has a very strict quality assurance, which  is quite time consuming.
Sometimes they find downsides in the submited patches, which make an including not possible.
The general rule of thumb here is to only try fixing bugs, which you actually face in your normal operations. Because most of this bugs affect only a small part of users.
If you still search for a list, the bug tracker from magento itself is probably a good search.
Also there are some community forks which try to provide a version with less bugs.
One is https://github.com/OpenMage/magento-lts another https://github.com/firegento/magento
Comment: Fix the bugs that directly cause issues, get yourself to work and upgrade to the latest version for the rest or face major alcohol consumption and wall repair from banging your head on it due to making the fixes and then upgrading and making the fixes again, ad infinitum.


How can I make the fields in my views "searchable?"

Question: So I have several views on my website with specific fields shown in table format. The search bar only searches through specific content, like pages, and basic pages. How can I modify the views or the search function to make it so that words typed into the search bar will search through the text entered for each field displayed in the views?
Answer: I would recommend checking out the Search API module. It's an extremely powerful extension to regular Drupal search, allowing you to use many advanced search backends and also integrates with Views to allow you to search on any field you wish.


How to add Google Now On Tap in a ROM?

Question: I have ROM which doesn't have Now On Tap on Long Pressing Home Key. How can I add it?
Answer: First of all you have to set up Now On Tap in Google Now settings. After that you go to settings and find the "Buttons" section (usually on main settings screen or in rom tweaks section) and then for "long home button press" select "Open Google Now" or "Google Now On Tap" (whatever it is called there).

How to add Google Now On Tap in a ROM?


Cannot connect to local node using polkadot/api library. Return error unexpected character '#' in the library

Question: I'm trying to connect to local node using polkadot/api library but when I start my project it return this error in the library

Here is my code:
Answer: The error means you need to use a babel loader that supports private class fields.
We also ran into this issue, and fixed it with proper build config. We have a working build here but we're using TypeScript not JavaScript.  Maybe that might help you.
It also looks like you aren't the only one, someone reported something like it earlier this year.
Comment: Thank you so much! Your client saves my days!!!
Comment: Great! If you don't mind, would you please mark your question as answered so people can easily find what worked?  Thanks :)


What happen in SQL 2005 when it run out of number for an autonumber column?

Question: What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap?
What is the behavior of SQL Server 2005 when it happen?
Answer: You will get an overflow error when the maximum value is reached. If you use the bigint datatype with a maximum value of 9,223,372,036,854,775,807 this will most likely never be the case.
The error message you will get, will look like this:
Msg 220, Level 16, State 2, Line 10
Arithmetic overflow error for data type tinyint, value = 256.

(Source)
As far as I know MS SQL provides no functionality to fill the identity gaps, so you will either have to do this by yourself or change the datatype of the identity column.
In addition to this you can set the start value to the smallest negative number, to get an even bigger range of values to use.
Here is a good blog post about this topic.
Answer: It will not fill in the gaps.  Instead inserts will fail until you change the definition of the column to either drop the identity and find some other way of filling in the gaps or increase the size (go from int to bigint) or change the type of the data (from int to decimal) so that more identity values are available.
Answer: You will be unable to insert new rows and will receive the error message listed above until you fix the problem.  You can do this a number of ways. If you still have data and are using all the id's below the max, you will have to change the datatype.  If the data is getting purged on a regular basis and you have a large gap that is not going to be used, you can reseed the identity number to the lowest number in that gap.  For example,at a previous job,we were logging transactions.  We had maybe 40-50 million per month, but we were purging everything older than 6 months, so every few years, the identity would get close to 2 Billion, but we would have nothing with an id below 1.5 billion, so we would reseed back to 0. Again it's possible that neither of these will work for you and you will have to find a different solution.
Answer: If the identity column is an Integer, then your max is 2,147,483,647. You will get an overflow error if you exceed it.
If you think this is a risk, just use the BIGINT datatype, which gives you up to 9,223,372,036,854,775,807. Can't imagine a database table with that many rows.
Further discussion here. (Same link as xsl mentioned).
Answer: In the event that you do hit the maximum number for you identity column, you can move the data from that table into a secondary table with a bigger identity column type and specify the starting value for that new identity value to be the maximum of the previous type. The new identity values will continue from that point.
Answer: If you delete "old values" from time to time you just need to reset the seed using
DBCC CHECKIDENT ('MyTable', RESEED, 0);
Comment: DBCC CHECKIDENT ('MyTable', RESEED, -2147483647) could potentially help out if you've already filled up rows 0-2147483647 ;)


Headless Pi Zero SSH access over USB

Question: How can I SSH to a headless Raspberry PI Zero (no GPIO pins, no WiFi) over a USB cable, connecting to a Mac using a shell window from Mac's Terminal program?
Comment: You can read about on [Raspberry Pi Zero Headless Setup](https://davidmaitland.me/2015/12/raspberry-pi-zero-headless-setup/) article
Answer: I found this very helpful for setting up mine: https://learn.adafruit.com/turning-your-raspberry-pi-zero-into-a-usb-gadget/ethernet-gadget
The essential steps are:
1: open up the boot partition on the micro sd with finder and in the file config.txt add dtoverlay=dwc2 to a line on the bottom and save it.
2: Create a new file called ssh using textedit and save it onto the boot partition. Use 'get info' to remove the extension on the file, and it should appear as an EXEC file. You can now eject the card and boot it on your RPi
3: Finally, open up the cmdline.txt. replace all text with this:
dwc_otg.lpm_enable=0 console=serial0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait modules-load=dwc2,g_ether quiet init=/usr/lib/raspi-config/init_resize.sh

Be careful with this step as the formatting is very picky in this file
4: Eject your MicroSD card and boot it up in your pi! make sure you plug the usb cable from your mac into the USB input of your pi - this can also power it.
5: Once its booted you should now be able to open up terminal, and using ping raspberrypi.local you can see the RPi's IP address.
6: Using this address in terminal tpye ssh pi@<Pi's IP Address>
7: It should ask you for a password, this will default be

raspberry

I'd also recommend having a look at 'VNC Viewer' - a piece of free software that lets you run your pi as a virtual machine inside your mac, all you need is the IP address which you will get when doing the ssh connection
https://www.realvnc.com/download/viewer/macosx/
Hope this helps!
Comment: The deadline IO scheduler was replaced with mq-deadline and does not exist in recent Linux kernels in Bullseye.
Answer: After you've done what @Barnaby Hewitt says then this issue may occur:
In my case the Ubuntu host machine could not connect to the Pi Zero via SSH because the Ubuntu machine failed to retrieve an IP address. In order to fix that I set static IP addresses on both ends.
I mounted the SD card to the Ubuntu host machine and I created a file on the mounted SD card, ^path_to_mounted_sd^/rootfs/etc/network/interfaces.d/usb0 containing:
allow-hotplug usb0
iface usb0 inet static
address 192.168.137.2
netmask 255.255.255.0
network 192.168.137.0
broadcast 192.168.137.255
gateway 192.168.137.1

After saving the file and successfully un-mounting the SD card I put it in the Pi and plugged connected my Pi to my computer via a USB cable.
Ubuntu's network manager started to show this icon:  indicating that it tries to retrieve an IP using DHCP. In the end it will fail so we will need to provide a static IP address.
Next you will need to locate the static IP address of the Ubuntu host machine. List all interfaces in order to locate the one that does not yet have an IP address via the ifconfig command. Afterwards run:
sudo ifconfig enp0s20f0u6 192.168.137.3 netmask 255.255.255.0

In my case enp0s20f0u6 is the interface that was located using the ifconfig command on the Ubuntu host. Then I could manage to connect using the command:
ssh email@example.com

Because I did not change the default password yet I used raspberry to connect to the Pi.
In case you plug the Pi to the very same USB then you may want to have these network settings remain the same. For the configuration use the Ubuntu's /etc/network/interfaces or use the network manager in order to set these settings.
Answer: In my case Ubuntu 19.04 I didn't get IP address from Raspberrypi Zero
You can fix it easy just change "USB Ethernet" settings
**IPv4 Method**
 Automatic (DHCP) --> Link-Local Only

After that you will get a 169.254.xxx.xxx IP address.
ping raspberrypi.local
ssh email@example.com
Comment: An address in that range is a public IP.  That's somewhat suspicious, especially if you're claiming that to be a general answer.
Comment: @Brick 169.254.0.0/16 is almost always an IP address assigned automatically by an interface that's set to get its IP via DHCP but can't get one - not a public ip.
Comment: Thanks, that worked flawlessly for me on linux mint.
Answer: For me it did not work; This works (with IP 192.168.137.2) only if I also edit the file /etc/network/interfaces with
allow-hotplug usb0
iface usb0 inet static
address 192.168.137.2
netmask 255.255.255.0
network 192.168.137.0
broadcast 192.168.137.255
gateway 192.168.137.1

That I got from another place ( https://gist.github.com/gbaman/975e2db164b3ca2b51ae11e45e8fd40a ); 192.168.7.2 may be ok instead of 192.168.137.2
Hope this can be useful for others reading this question.
Answer: I'll add my 3 cents - maybe it will save someone a few hours.
My setup was still failing with ssh: Could not resolve hostname raspberrypi.local even though I've done all needed steps: (config.txt, cdmline.txt, ssh file) and "Link-Local Only" network setting.
I could have connected to RPi by IP address, but I could only discover it by running mmap or arp-scan that both took forever. It turns out that for some reason this Bonjur-like auto-config didn't work when connected through my usb-hub. After connecting directly to my PC it worked like charm.
Answer: In case anyone else stumbles up on this in future I ran into issues with the Pi4 I had the Pi Zero plugged into.  Namely that USB0 came up with a 169.x.x.x link only address.  Took me a minute to figure out what was wrong and here are some snippets.
$ ifconfig usb0
usb0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 169.254.122.46  netmask 255.255.0.0  broadcast 169.254.255.255
...

No worries so I changed the USB0 address to the 192.168.4.3.  Note my Zero config was set to 192.168.4.4.
$ sudo ifconfig usb0 192.168.4.3 netmask 255.255.255.0

Still no connectivity but TCP dump shows packets from 192.168.4.4 (Pi Zero).
$ sudo tcpdump -i usb0
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on usb0, link-type EN10MB (Ethernet), capture size 262144 bytes
16:56:56.584779 ARP, Request who-has dns.google tell raspberrypi.local, length 28
16:56:57.428907 IP6 fe80::768e:30aa:7659:e902.mdns > ff02::fb.mdns: 0 PTR (QM)? 188.8.131.52.in-addr.arpa. (45)
16:56:57.429024 IP 192.168.4.3.mdns > 22.214.171.124.mdns: 0 PTR (QM)? 220.127.116.11.in-addr.arpa. (45)
16:56:57.430578 IP 192.168.4.4.mdns > 126.96.36.199.mdns: 0*- [0q] 1/0/0 (Cache flush) PTR raspberrypi.local. (70)

The route table did not setup the 192 network but did have the 169 network.
$ route -n
...
169.254.0.0     0.0.0.0         255.255.0.0     U     207    0        0 usb0
...

Lets fix that
$ sudo route del -net 169.254.0.0 gw 0.0.0.0 netmask 255.255.0.0 dev usb0
$ sudo ip route add 192.168.4.0/24 dev usb0
$ ping 192.168.4.4
PING 192.168.4.4 (192.168.4.4) 56(84) bytes of data.
64 bytes from 192.168.4.4: icmp_seq=1 ttl=64 time=1.10 ms
64 bytes from 192.168.4.4: icmp_seq=2 ttl=64 time=0.444 ms

Headless Pi Zero SSH access over USB


Can I install the vanilla MATE desktop environment alongside the Ubuntu MATE Remix desktop environment (15.04 Vivid Vervet)?

Question: I have installed the Ubuntu MATE Remix desktop environment on Ubuntu 15.04 (Please note I have a regular Ubuntu installation with the desktop environment on it, not the Ubuntu MATE flavor of Ubuntu). I use this as my main desktop environment. Will installing the vannila MATE desktop environment (to try it out) break my Ubuntu MATE Remix installation?
Answer: You can have multiple DE's at the same time, and you will be able to choose one of them when you boot Ubuntu. To do this, run the following commands in a terminal emulator (Ctrl+Alt+T):
<code>sudo apt-add-repository ppa:ubuntu-mate-dev/ppa
sudo apt-add-repository ppa:ubuntu-mate-dev/trusty-mate
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install --no-install-recommends ubuntu-mate-core ubuntu-mate-desktop
</code>
The "--no-install-recommends" attribute is very important in this process. It tells APT not to overwrite anything. After all this process ends, you can log out your current session and choose other DE at the login screen (above your user icon, near the hour applet).
Comment: Since Ubuntu MATE is simply called "MATE" on the lock screen, I was wondering if that might mess things up. Also, your instructions are for Ubuntu 14.04, not 15.04, and for installing the Ubuntu MATE desktop, not the vanilla MATE one.  This may confuse other Ask Ubuntu users.


How do I pre-generate a Minecraft bedrock world

Question: I am looking for a easy script that can teleport me across my Minecraft Bedrock Edition world so I can generate the chunks without causing lag as people explore my server. Please make sure it works for the Bedrock Edition.
Comment: Are you looking for a script for like a servers, or your question is tagged commands so are you looking for a command?
Answer: There's no way that I know of to generate chunks before someone has arrived in that location; the easiest way would be to teleport everyone to all the locations you need generated, which would be quickest done through functions if you're looking for commands. Render distance is 196 blocks (12 chunks) in each direction. To maximize each teleport to load, it would start at, for example 0, 0, then teleport to 0, 392 to load the chunks.


Improvement of Interpretation of residuals vs fitted plot

Question: I wish to examine assumptions for single regression using the built in diagnostics within R. The residuals vs fitted plot below seemly violated the assumption. There are 2 dummy coded variables within my model and 1 categorical variable (testing probability). The model only explains 8% of the variance in selection (DV).
What improvements/Advice can be tell from the plot? Thanks.
Comment: For diagnosing a logistic regression, consider using DHARMa, see hints on logistic regression in https://cran.r-project.org/web/packages/DHARMa/vignettes/DHARMa.html#binomial-data
Comment: The definition residual $=$ observed $-$ fitted implies that distinct observed values define parallel lines on this plot, in this case residual $= 0\ -$ fitted and residual $= 1\ -$ fitted. Nothing is really violated here; it is just that your data aren't well suited to the model you fit.
Answer: Without wanting this to sound snotty, my advice would be not to use linear regression with a binary outcome variable.  Use logistic regression instead.  (In R, that's: glm(<formula>, <data>, family=binomial).  When you do use logistic regression, ignore these plots (see my answer to: Interpretation of plot (glm.model)).


Usefulness of symbolic devices

Question: Each mathematician knows that  good notation or symbolism – which seems to be irrelevant from a purely logical point of view – makes theorems more plausible  and motivates results which would otherwise be overlooked.   Examples abound. Let me only mention such diverse things as decimal notation, $B^A$ for the set of mappings from $A$ to $B$, $\frac{{df}}{{dx}}$ for differentiation, commutative diagrams, umbral calculus, etc.
I would be interested in a list of examples of the most useful notations or symbolic devices  together with hints for the reason of their usefulness.
Comment: A related MO question http://mathoverflow.net/questions/42929/suggestions-for-good-notation
Comment: Is the other MO question essentially a duplicate or is there a different focus here?
Answer: Group conjugation: $a^b$ means $b^{-1}ab$, so $(a^b)^c$ is $a^{bc}$ and $(a^b)^{-1}$ is $(a^{-1})^b$.
Answer: I really like the multi-index notation for derivatives which is quite often found in the theory of PDEs.
$D^\alpha f = \frac{\partial^{\vert\alpha\vert} f}{\partial x_1^{\alpha_1}\cdots\partial x_n^{\alpha_n}}$
Where $\alpha$ is defined as:
$\alpha = (\alpha_1,\cdots,\alpha_n),$
$\vert \alpha\vert = \alpha_1 + \cdots +\alpha_n$
It makes definining Sobolev Spaces (and their corresponding Norms) so much cleaner and straight forward:
$W^{k,p} = \lbrace f\in L^p : D^\alpha f\in L^p \text{ for all } \vert\alpha\vert \le k \rbrace$
Comment: I was going to mention the differential operator D used in ODEs.  So, for example, $Dy=\frac{d}{dx}y$.  I originally thought it was a useless notation, until I realized that it greatly simplified things.  For example, $(D^4+4D^3+6D^2+4D+5)y=0$ is difficult to solve until you express it as $(D^2+1)(D^2+4D+5)y=0$.
Answer: For certain problems, suppression of a common entity or entry and making it understood by other means.  For a lecture involving manipulation of some algebra (ternary groups, maybe?) a form similar to matrix multiplication was used.  Instead of spelling out the matrices with all the entries, those entries that were zero were omitted, giving a more eye-friendly appearence.  I (and many others, I'm sure) use it for small incidence matrices which are not very dense; the symmetry and other relationships seem much more obvious without the clutter of zeroes.  And this is just one example of many.
Gerhard "Ask Me About System Design" Paseman, 2011.09.13

Usefulness of symbolic devices


Is it necessary to use the comma in the following sentence?

Question: Do I have to use the comma before the WHEN CLAUSE in the following sentence?
"We were swimming in the lake, when suddenly a crocodile attacked us."
Answer: It's not a matter of necessity; it's a matter of whether you wish to conform to the style recommended in your manual of style.  I use the Chicago Manual of Style, which recommends that dependent clauses that follow an independent clause be set off by a comma if and only if the dependent clause is non-restrictive, i.e, if it's informational only instead of definitional.
Your example seems non-restrictive:  you've merely added an interesting story to your swimming holiday.  Here's a restrictive example:

Do you remember that swimming holiday when a crocodile suddenly
  attacked us?

Now the clause distinguishes that time when you went swimming from all the other, less eventful times.  So no comma.
Punctuation is a matter of style, not a matter of life and death, like swimming in a crocodile-infested lake.
Comment: Similar to your "distinguishing that swimming trip from others (and hence no comma)" point - if the OP's question is in response to the question "what were you doing when the crocodile attacked you?", then I think the comma should be omitted.
Comment: @deadrat Your explantion is very clear. So the point is to separate the non-defining (dependent) clause from the independent clause with a comma when it (the dependent clause) gives only additional information. Right?
Comment: @midomido Right.


Tor app. through Google Play

Question: I downloaded the Tor browser app. through Google play, is the app. safe and anonymous even though it's downloaded through Google?
Answer: If you ever have questions about what is legitimately Tor, check out https://torproject.org. This is the team that actually makes the Tor browser ad the Tor network itself. Here is the page for android. You can make sure that you are getting the real Tor Browser and not malware.
The Tor developers stand by their work on Android the same as any other operating system. Of course, it is up to you to know how to keep yourself anonymous online. Software can only do so much.

Tor app. through Google Play


OneNote 2016 on O365 SharePoint in Windows 10

Question: I don't want to use the "app" for OneNote that comes with Win10 - and in fact have removed it (see powershell removal instructions here). But when I want to choose OneNote 2016, not OneNote Online, to open a notebook on our (hosted on O365) SharePoint - it goes to the AppStore and gives me no other option. Yes, once I get it the first time by going dumpster diving through the file explorer and it is cached in OneNote client application I can still get to it, but that is very frustrating for training multitudes of new users. Any solutions? The library holding the notebooks is already set to force the client application as default.
Answer: Uninstalling the app is an optional step here. It is important to change the default version in Windows 10 from the App to the Desktop-Application.
There's an excellent article how to change.
It is not the best solution, as "normal" users won't get this change done. This article describes how to apply the change via GPO or SCCM.
Comment: The first link is bad?
Comment: Found it though. Thought I had done that - sneaky bastards, though. They don't even give you the option unless you already have the default changed. Thank you! I was at my wits' end!
Comment: Ok, WEIRD. It worked great on a machine at home. The other PC, where I had removed the Win10 app - doesn't show OneNote2016 as an option on the list for default apps. At all. Even after I reinstalled office just in case. Could it be a 64-bit issue?
Comment: 64Bit Office? Sorry, i do not have much experience with that. It is still a good practice to work with 32Bit editions in most scenarios. https://support.office.com/en-us/article/Choose-between-the-64-bit-or-32-bit-version-of-Office-2dee7807-8f95-4d0c-b5fe-6c6f49b8d261?ui=en-US&rs=en-US&ad=US
Comment: Yeah, I work with large datasets so I use 64-bit. I may have to go back though, as this is driving me nuts. Thanks!