text:
Q: Application runs, but eventually ends up with SIGSEGV or NullReferenceException I have the following program (full source):
using Mono.Unix;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

namespace StoneOS.ResourceMonitor
{
    class Program
    {
        static void Main(string[] args)
        {
            var runner = new Timer(state =>
            {
                var cpu = CPUUsage();
                var ram = RAMUsage();
                var hdd = DriveUsage("/dev/sda3");

                Console.WriteLine("[{0:O}] C: {1:N2} | R: {2:N2} | S: {3:N2} | H: {4:N2}", DateTime.Now, cpu, ram.Total, ram.Swap, hdd);
            }, null, TimeSpan.Zero, TimeSpan.FromMilliseconds(50));

            Console.ReadKey(true);
        }

        private static string LastReadCPULine = null;

        struct Jiffy
        {
            public double Total;

            public double Work;
        }

        public static double? CPUUsage()
        {
            // File path and descriptor, that holds the actual CPU data.
            var statsFile = "/proc/stat";
            // var unixInfo = new FileInfo(statsFile);
            var unixInfo = new UnixFileInfo(statsFile);

            // Read last queried data into cache.
            string last = LastReadCPULine;

            // Prepare for new read.
            List<string> output = new List<string>();

            // Read data.
            using (var reader = new StreamReader(unixInfo.OpenRead()))
            {
                string currentLine;

                while ((currentLine = reader.ReadLine()) != null)
                {
                    output.Add(currentLine);
                }
            }

            unixInfo = null; // clear...

            // Select the first entry, that should be total of CPU.
            string current = LastReadCPULine = output.First();

            // If there was no last entry, that means we cannot calculate - return zero.
            if (last == null)
            {
                return null;
            }

            return CalculateCPUUsage(last, current);
        }

        private static double CalculateCPUUsage(string last, string current)
        {
            Jiffy lastJiffy = GetJiffies(last);
            Jiffy currentJiffy = GetJiffies(current);

            double work = currentJiffy.Work - lastJiffy.Work;
            double total = currentJiffy.Total - lastJiffy.Total;

            return (work / total) * 100;
        }

        private static Jiffy GetJiffies(string statLine)
        {
            // Split on spaces.
            string[] parts = subsequentSpacePattern.Split(statLine);

            // Remove first entry (label - cpu).
            IEnumerable<double> convertedData = parts.Skip(1).Select(entry => Convert.ToDouble(entry));

            // Calculate the values for the Jiffy.
            return new Jiffy
            {
                Total = convertedData.Sum(),
                Work = convertedData.Take(3).Sum()
            };
        }

        struct Memory
        {
            public double Total;
            public double Swap;
        }

        private static Memory RAMUsage()
        {
            var processInfo = new ProcessStartInfo("/bin/free", "-b")
            {
                RedirectStandardError = true,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

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

            using (var process = Process.Start(processInfo))
            {
                process.WaitForExit();

                string currentLine;

                using (var reader = process.StandardOutput)
                {
                    while ((currentLine = reader.ReadLine()) != null)
                    {
                        output.Add(currentLine);
                    }
                }
            }

            return new Memory
            {
                Total = CalculateTotalMemoryUsage(output.Skip(1).Take(1).Single()),
                Swap = CalculateSwapUsage(output.Skip(2).Take(1).Single())
            };
        }

        private static Regex subsequentSpacePattern = new Regex(@"\s+");

        private static double CalculateTotalMemoryUsage(string memoryLine)
        {
            string[] parts = subsequentSpacePattern.Split(memoryLine);

            // Console.WriteLine("[{0:O}] Memory: {1}", DateTime.Now, memoryLine);
            // Console.WriteLine("[{0:O}] Memory: {1}", DateTime.Now, String.Join(", ", parts));

            string totalByteString = parts.Skip(1).Take(1).Single();
            string availableByteString = parts.Last();

            // Console.WriteLine("[{0:O}] Total: '{1}'; Available: '{2}'", DateTime.Now, totalByteString, availableByteString);

            double total = Convert.ToDouble(totalByteString);
            double available = Convert.ToDouble(availableByteString);

            var percentage = (available / total) * 100d;

            // Console.WriteLine("[{0:O}] Memory %: {1} (Total: {2}, Free: {3})", DateTime.Now, percentage, total, available);

            return 100d - percentage;
        }

        private static double CalculateSwapUsage(string swapLine)
        {
            string[] parts = subsequentSpacePattern.Split(swapLine);

            // Console.WriteLine("[{0:O}] Swap: {1}", DateTime.Now, swapLine);
            // Console.WriteLine("[{0:O}] Swap: {1}", DateTime.Now, String.Join(", ", parts));

            string totalByteString = parts.Skip(1).Take(1).Single();
            string freeByteString = parts.Last();

            // Console.WriteLine("[{0:O}] Total: '{1}'; Free: '{2}'", DateTime.Now, totalByteString, freeByteString);

            double total = Convert.ToDouble(totalByteString);
            double free = Convert.ToDouble(freeByteString);

            var percentage = (free / total) * 100d;

            // Console.WriteLine("[{0:O}] Swap %: {1} (Total: {2}, Free: {3})", DateTime.Now, percentage, total, free);

            // We are interested in remainder.
            return 100d - percentage;
        }

        private static Regex multiSpacePattern = new Regex(@"\s+");

        private static double DriveUsage(string drive)
        {
            var processInfo = new ProcessStartInfo("/bin/df", String.Format("-B1 {0}", drive))
            {
                RedirectStandardError = true,
                RedirectStandardInput = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

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

            using (var process = Process.Start(processInfo))
            {
                process.WaitForExit();

                string currentLine;

                using (var reader = process.StandardOutput)
                {
                    while ((currentLine = reader.ReadLine()) != null)
                    {
                        output.Add(currentLine);
                    }
                }
            }

            // Second output line is the one we're looking for.
            var second = output.Last();

            string[] parts = multiSpacePattern.Split(second);

            if (parts.Length != 6)
            {
                throw new ApplicationException(String.Format("Invalid column count in df's output: {0}", second));
            }

            var percentage = parts[4].TrimEnd('%');

            // Console.WriteLine("Output: {0}", second);
            // Console.WriteLine("[4] = {0}, percentage = {1}", parts[4], percentage);

            return Convert.ToDouble(percentage);
        }
    }
}

Just a basic resource monitor, that reads/requests some information from the system and reports every N seconds. This is used to reflect the errors happening in the actual application. This happens to error out in the same manner as actual app. The periodic interval is set as high to get to the errors faster for debugging purposes.
As can be seen around lines 41 & 42, respectively:
// var unixInfo = new FileInfo(statsFile);
var unixInfo = new UnixFileInfo(statsFile);

I have set up two solutions. One utilizing the native .NET/Mono itself, the other - Mono.Posix.
When run by utilizing the native solution (FileInfo) - there are no problems, everything works as expected.
Now, when running with the Mono.Posix equivalent (UnixFileInfo), the software eventually ends up in a System.NullReferenceException or even worse - SIGSEGV.
System.NullReferenceException case:
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object
  at System.String.IndexOfAnyUnchecked (System.Char[] anyOf, Int32 startIndex, Int32 count) [0x00000] in :0
  at System.String.IndexOfAny (System.Char[] anyOf) [0x00019] in /build/mono/src/mono-3.10.0/mcs/class/corlib/System/String.cs:896
  at Mono.Unix.UnixPath.CheckPath (System.String path) [0x00000] in :0
  at Mono.Unix.UnixFileSystemInfo..ctor (System.String path) [0x00000] in :0
  at Mono.Unix.UnixFileInfo..ctor (System.String path) [0x00000] in :0
  at StoneOS.ResourceMonitor.Program.CPUUsage () [0x00008] in /home/stone/sandbox/StoneOS.ResourceMonitor/StoneOS.ResourceMonitor/Program.cs:44
  at StoneOS.ResourceMonitor.Program.m__0 (System.Object state) [0x00001] in /home/stone/sandbox/StoneOS.ResourceMonitor/StoneOS.ResourceMonitor/Program.cs:20
  at System.Threading.Timer+Scheduler.TimerCB (System.Object o) [0x00007] in /build/mono/src/mono-3.10.0/mcs/class/corlib/System.Threading/Timer.cs:317
SIGSEGV case:
Stacktrace:

Native stacktrace:

        /usr/lib/libmonosgen-2.0.so.1(+0xd546a) [0x7f2d9851f46a]
        /usr/lib/libmonosgen-2.0.so.1(+0x133aeb) [0x7f2d9857daeb]
        /usr/lib/libmonosgen-2.0.so.1(+0x3fde6) [0x7f2d98489de6]
        /usr/lib/libpthread.so.0(+0x10200) [0x7f2d9823e200]
        /usr/lib/libmonosgen-2.0.so.1(+0x204d70) [0x7f2d9864ed70]
        /usr/lib/libmonosgen-2.0.so.1(+0x20bd4f) [0x7f2d98655d4f]
        /usr/lib/libmonosgen-2.0.so.1(+0x20c159) [0x7f2d98656159]
        /usr/lib/libmonosgen-2.0.so.1(+0x229cb3) [0x7f2d98673cb3]
        /usr/lib/libmonosgen-2.0.so.1(+0x229d7f) [0x7f2d98673d7f]
        [0x4150ff33]

Debug info from gdb:

warning: File "/usr/bin/mono-sgen-gdb.py" auto-loading has been declined by your `auto-load safe-path' set to "$debugdir:$datadir/auto-load".
To enable execution of this file add
        add-auto-load-safe-path /usr/bin/mono-sgen-gdb.py
line to your configuration file "/root/.gdbinit".
To completely disable this security protection add
        set auto-load safe-path /
line to your configuration file "/root/.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual.  E.g., run from the shell:
        info "(gdb)Auto-loading safe path"
warning: Could not load shared library symbols for linux-vdso.so.1.
Do you need "set solib-search-path" or "set sysroot"?
[New LWP 441]
[New LWP 440]
[New LWP 439]
[New LWP 438]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/libthread_db.so.1".
0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6
  Id   Target Id         Frame
  5    Thread 0x7f2d95c9b700 (LWP 438) "Finalizer" 0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6
  4    Thread 0x7f2d956ff700 (LWP 439) "Timer-Scheduler" 0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6
  3    Thread 0x7f2d954fe700 (LWP 440) "Threadpool moni" 0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6
  2    Thread 0x7f2d954bd700 (LWP 441) "Threadpool work" 0x00007f2d9823ddeb in waitpid () from /usr/lib/libpthread.so.0
* 1    Thread 0x7f2d98c48780 (LWP 437) "mono" 0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6

Thread 5 (Thread 0x7f2d95c9b700 (LWP 438)):
#0  0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6
#1  0x00007f2d9864cd46 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#2
#3  0x00007f2d9823c90e in sem_wait () from /usr/lib/libpthread.so.0
#4  0x00007f2d986ab5c6 in mono_sem_wait () from /usr/lib/libmonosgen-2.0.so.1
#5  0x00007f2d98624529 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#6  0x00007f2d986069e7 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#7  0x00007f2d986b0dd5 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#8  0x00007f2d98235314 in start_thread () from /usr/lib/libpthread.so.0
#9  0x00007f2d97f733ed in clone () from /usr/lib/libc.so.6

Thread 4 (Thread 0x7f2d956ff700 (LWP 439)):
#0  0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6
#1  0x00007f2d9864cd46 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#2
#3  0x00007f2d9823ac68 in pthread_cond_timedwait@@GLIBC_2.3.2 () from /usr/lib/libpthread.so.0
#4  0x00007f2d986885ba in ?? () from /usr/lib/libmonosgen-2.0.so.1
#5  0x00007f2d9869c9c2 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#6  0x00007f2d9860642f in ?? () from /usr/lib/libmonosgen-2.0.so.1
#7  0x00007f2d986078dc in ?? () from /usr/lib/libmonosgen-2.0.so.1
#8  0x000000004152a6ad in ?? ()
#9  0x0000000000000001 in ?? ()
#10 0x0000000000000001 in ?? ()
#11 0x0000000000000032 in ?? ()
#12 0x00007f2d97002cd0 in ?? ()
#13 0x0000000000000031 in ?? ()
#14 0x00007f2d880025e0 in ?? ()
#15 0x00007f2d956febb0 in ?? ()
#16 0x00007f2d956fe9f0 in ?? ()
#17 0x00007f2d956fe950 in ?? ()
#18 0x000000004152a418 in ?? ()
#19 0x0000000000000000 in ?? ()

Thread 3 (Thread 0x7f2d954fe700 (LWP 440)):
#0  0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6
#1  0x00007f2d9864cd46 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#2
#3  0x00007f2d97f802ca in clock_nanosleep () from /usr/lib/libc.so.6
#4  0x00007f2d9869df48 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#5  0x00007f2d98609abe in ?? () from /usr/lib/libmonosgen-2.0.so.1
#6  0x00007f2d986069e7 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#7  0x00007f2d986b0dd5 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#8  0x00007f2d98235314 in start_thread () from /usr/lib/libpthread.so.0
#9  0x00007f2d97f733ed in clone () from /usr/lib/libc.so.6

Thread 2 (Thread 0x7f2d954bd700 (LWP 441)):
#0  0x00007f2d9823ddeb in waitpid () from /usr/lib/libpthread.so.0
#1  0x00007f2d9851f500 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#2  0x00007f2d9857daeb in ?? () from /usr/lib/libmonosgen-2.0.so.1
#3  0x00007f2d98489de6 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#4
#5  0x00007f2d9864ed70 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#6  0x00007f2d98655d4f in ?? () from /usr/lib/libmonosgen-2.0.so.1
#7  0x00007f2d98656159 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#8  0x00007f2d98673cb3 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#9  0x00007f2d98673d7f in ?? () from /usr/lib/libmonosgen-2.0.so.1
#10 0x000000004150ff33 in ?? ()
#11 0x00007f2d973fffa0 in ?? ()
#12 0x00007f2d973ff108 in ?? ()
#13 0x000000000000001d in ?? ()
#14 0x00007f2d973ff108 in ?? ()
#15 0x0000000000000001 in ?? ()
#16 0x00007f2d800025e0 in ?? ()
#17 0x000000000000001f in ?? ()
#18 0x00007f2d954bc6d0 in ?? ()
#19 0x00007f2d954bc5e0 in ?? ()
#20 0x0000000041557efc in ?? ()
#21 0x00007f2d97000d30 in ?? ()
#22 0x00007f2d973fffa0 in ?? ()
#23 0x00007f2d973f1ae8 in ?? ()
#24 0x000000000000001f in ?? ()
#25 0x0000000000000001 in ?? ()
#26 0x000000000000001d in ?? ()
#27 0x00007f2d954bd680 in ?? ()
#28 0x00007f2d98673d3f in ?? () from /usr/lib/libmonosgen-2.0.so.1
#29 0x000000004150ff33 in ?? ()
#30 0x00007f2d97000d30 in ?? ()
#31 0x00007f2d973f1ae8 in ?? ()
#32 0x0000000000000001 in ?? ()
#33 0x0000000000000025 in ?? ()
#34 0x00007f2d973f1ae8 in ?? ()
#35 0x00007f2d97000d30 in ?? ()
#36 0x00007f2d973f1ae8 in ?? ()
#37 0x00007f2d97000d30 in ?? ()
#38 0x00007f2d954bc770 in ?? ()
#39 0x00000000415577e4 in ?? ()
#40 0x000000000000001f in ?? ()
#41 0x0000000000000001 in ?? ()
#42 0x0000000000000001 in ?? ()
#43 0x000000000000001c in ?? ()
#44 0x0000000000000001 in ?? ()
#45 0x0000000000000025 in ?? ()
#46 0x000000000000001f in ?? ()
#47 0x0000000000000001 in ?? ()
#48 0x0000000000000001 in ?? ()
#49 0x00007f2d973f1ae8 in ?? ()
#50 0x00007f2d973fffa0 in ?? ()
#51 0x0000000000000000 in ?? ()

Thread 1 (Thread 0x7f2d98c48780 (LWP 437)):
#0  0x00007f2d97ebed57 in sigsuspend () from /usr/lib/libc.so.6
#1  0x00007f2d9864cd46 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#2
#3  0x00007f2d9823d3bb in read () from /usr/lib/libpthread.so.0
#4  0x00007f2d986897e1 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#5  0x00007f2d985ac234 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#6  0x0000000041530c61 in ?? ()
#7  0x00007f2d970168c0 in ?? ()
#8  0x0000000000000000 in ?? ()

=================================================================
Got a SIGSEGV while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================

Aborted (core dumped)
Most of the times, though, it's the SIGSEGV error.
What I have tried... well, besides switching back and forth from FileInfo and UnixFileInfo nothing, problem is, I don't know what to even try.
This is my first major Mono application targeted for Linux, hence have no idea what to do here.
I have walked through the Mono GDB debugging guide - set up the provided .gdbinit, ran with gdb - result:
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff47fe700 (LWP 4558)]
0x00007ffff7a1cc47 in ?? () from /usr/lib/libmonosgen-2.0.so.1
(gdb) mono_backtrace 15
#0  0x00007ffff7a1cc47 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#1  0x00007ffff7a1caf8 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#2  0x00007ffff79f236d in ?? () from /usr/lib/libmonosgen-2.0.so.1
#3  0x00007ffff79f7725 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#4  0x00007ffff79f8159 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#5  0x00007ffff7a15cb3 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#6  0x00007ffff7a15ed4 in ?? () from /usr/lib/libmonosgen-2.0.so.1
#7  0x00007ffff79cdb16 in mono_array_new_specific ()
   from /usr/lib/libmonosgen-2.0.so.1
#8 0x400135cb in Cannot access memory at address 0xffffffffe00f2410
This gives something what the default mono --debug <path/to/exe> doesn't - the mono_array_new_specific() call, though, I don't know of what relevance it is here.
I am unsure whether this is a bug in the Mono.Posix library or something else, but this is really bugging me. Yes, for this particular example case I can get away with FileInfo, but in the real app I am actually utilizing UnixSymbolicLinkInfo which is causing the same problem.
mono -V:
Mono JIT compiler version 3.10.0 (tarball Mon Oct  6 20:46:04 UTC 2014)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
        TLS:           __thread
        SIGSEGV:       altstack
        Notifications: epoll
        Architecture:  amd64
        Disabled:      none
        Misc:          softdebug
        LLVM:          supported, not enabled.
        GC:            sgen

What makes my application eventually end up erroring out with a SIGSEGV or System.NullReferenceException?

A: A NullReferenceException should never happen inside the class libraries (System.String class), so this must be a bug. Please report it in http://bugzilla.xamarin.com/. Ideally you should include in the report what is exactly the string used, and the parameter used, when calling the method IndexOfAny(). For that you may need to check the sources of Mono.Posix to see what's done inside Mono.Unix.UnixPath.CheckPath().


text:
Q: RMarkdown html_output error I am trying to create a RMarkdown document with RStudio using shiny server. It works fine if the ouptut is pdf but if I want it as html I get this following error at the end of the process (in the RMarkdown console I can see it reached 100%).
Error: unrecognized fields specified in html_dependency: attachment
I have no idea why this error is happening.
Can anyone help me with this?
Thank you

A: I had a similar problem and found that it was caused by RStudio attempting to use Knitr to build a Shiny page. You can fix this by running using rmarkdown::run() instead of rmarkdown::render().  In some older versions of RStudio, the "Knit html" button runs this:
rmarkdown::render('filename.Rmd', 'html_document')

whereas, you can get the the results you want by running this command instead:
rmarkdown::run('filename.Rmd')

You could use this command or just update to the latest version of RStudio.
There is more info about authoring Shiny document here: http://rmarkdown.rstudio.com/authoring_shiny.html.

A: This is caused by a recent update of the relevant rmarkdown package or related ones.
Update RStudio to the latest version and then the error should disappear. It worked in my case.

A: Updating RStudio didn't work for me. What did work was updating all R packages (Tools > Check for Package Updates...).

redpajama_set_name: RedPajamaStackExchange


text:
Q: If anything other than an integer is entered, ask user to enter only an integer I'm currently programming in Java creating the "Nim" game.  However, I am at an utter lost as to how I can modify my program to make the user enter only integers and if they enter anything else, ask them to enter an integer.
import java.util.Scanner;

public class Nim
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);

        int noEntered;

        int firstPile = 3;
        int secondPile = 4;
        int thirdPile = 5;

        int next = 1;

        int choose;

        do
        {
            if (next % 2 == 1)
            {
                System.out.print("Player 1 - choose bag: ");
                choose = scanner.nextInt();

                if (choose == 1)
                {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = scanner.nextInt();
                    firstPile = firstPile - noEntered;
                    System.out.println("Bag Status: " + + firstPile + ", " + secondPile + ", "
                    + thirdPile);
                }
                else if (choose == 2)
                {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = scanner.nextInt();
                    secondPile = secondPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                }
                else if (choose == 3)
                {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = scanner.nextInt();
                    thirdPile = thirdPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                }
            }
            else
            {
                System.out.print("Player 2 - choose bag: ");
                choose = scanner.nextInt();
                if (choose == 1)
                {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = scanner.nextInt();
                    firstPile = firstPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                }
                else if (choose == 2)
                {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = scanner.nextInt();
                    secondPile = secondPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                }
                else if (choose == 1)
                {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = scanner.nextInt();
                    thirdPile = thirdPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                }
            }
            next++;
        }
        while (firstPile != 0 && secondPile != 0 && thirdPile != 0);

        if (next % 2 == 1)
        {
            System.out.println("Game Over - Player 1 wins");
        }
        else if (next % 2 == 0)
        {
            System.out.println("Game Over - Player 2 wins");
        }
    }
}

Any help?  Thanks.

A: Use try and catch() like this,
try{
        System.out.print("Player 1 - choose bag: ");
        choose = scanner.nextInt();
}catch(InputMismatchException exception)
{
  System.out.println("This is not an integer");
}

UPDATE:
import java.util.Scanner;

public class Nim
{
  public static void main(String[] args)
  {
   try{
    Scanner scanner = new Scanner(System.in);
    int noEntered;
    int firstPile = 3;
    int secondPile = 4;
    int thirdPile = 5;

    int next = 1;

    int choose;

    do
    {
        if (next % 2 == 1)
        {
            System.out.print("Player 1 - choose bag: ");
            choose = scanner.nextInt();

            if (choose == 1)
            {
                System.out.print("Now choose no. of tokens: ");
                noEntered = scanner.nextInt();
                firstPile = firstPile - noEntered;
                System.out.println("Bag Status: " + + firstPile + ", " + secondPile + ", "
                + thirdPile);
            }
            else if (choose == 2)
            {
                System.out.print("Now choose no. of tokens: ");
                noEntered = scanner.nextInt();
                secondPile = secondPile - noEntered;
                System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                        + thirdPile);
            }
            else if (choose == 3)
            {
                System.out.print("Now choose no. of tokens: ");
                noEntered = scanner.nextInt();
                thirdPile = thirdPile - noEntered;
                System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                        + thirdPile);
            }
        }
        else
        {
            System.out.print("Player 2 - choose bag: ");
            choose = scanner.nextInt();
            if (choose == 1)
            {
                System.out.print("Now choose no. of tokens: ");
                noEntered = scanner.nextInt();
                firstPile = firstPile - noEntered;
                System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                        + thirdPile);
            }
            else if (choose == 2)
            {
                System.out.print("Now choose no. of tokens: ");
                noEntered = scanner.nextInt();
                secondPile = secondPile - noEntered;
                System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                        + thirdPile);
            }
            else if (choose == 1)
            {
                System.out.print("Now choose no. of tokens: ");
                noEntered = scanner.nextInt();
                thirdPile = thirdPile - noEntered;
                System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                        + thirdPile);
            }
        }
        next++;
    }
    while (firstPile != 0 && secondPile != 0 && thirdPile != 0);

    if (next % 2 == 1)
    {
        System.out.println("Game Over - Player 1 wins");
    }
    else if (next % 2 == 0)
    {
        System.out.println("Game Over - Player 2 wins");
    }
   }catch(InputMismatchException exception){
        System.out.println("Given input is not a number");
      }
   }
  }

A: In your Problem Pattern-Matcher can be really helpful  to avoid Exception capturing and handling using try catch block,You can Define a pattern to identify  integers.
static Pattern PATTERN = Pattern.compile( "^(-?0|-?[1-9]\\d*)" );

validate Integer.
 public static boolean isInteger( String value ) {
    return value != null && PATTERN.matcher( value ).matches();
  }

Use a method to take input  and validate if input is only Integer else display message like "Please enter valid Integer" and wait for next valid input.
public static Integer getIntInput(Scanner scanner){
        String sentanse=scanner.next();
        if(isInteger(sentanse)){
            System.out.println("number "+sentanse);
          return Integer.parseInt(sentanse);
        }else{
            System.out.println("Please enter valid Integer");
           return getIntInput(scanner);
        }
}

To see Result please modify you code like below
public class Nim {

    static Pattern PATTERN = Pattern.compile("^(-?0|-?[1-9]\\d*)");

    public static boolean isInteger(String value) {
        return value != null && PATTERN.matcher(value).matches();
    }

    public static Integer getIntInput(Scanner scanner) {
        String sentanse = scanner.next();
        if (isInteger(sentanse)) {
            System.out.println("number " + sentanse);
            return Integer.parseInt(sentanse);
        } else {
            System.out.println("Please enter valid Integer");
            return getIntInput(scanner);
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int noEntered;

        int firstPile = 3;
        int secondPile = 4;
        int thirdPile = 5;

        int next = 1;

        int choose;

        do {
            if (next % 2 == 1) {
                System.out.print("Player 1 - choose bag: ");
                choose = getIntInput(scanner);

                if (choose == 1) {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = getIntInput(scanner);
                    firstPile = firstPile - noEntered;
                    System.out.println("Bag Status: " + +firstPile + ", " + secondPile + ", "
                            + thirdPile);
                } else if (choose == 2) {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = getIntInput(scanner);
                    secondPile = secondPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                } else if (choose == 3) {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = getIntInput(scanner);
                    thirdPile = thirdPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                }
            } else {
                System.out.print("Player 2 - choose bag: ");
                choose = getIntInput(scanner);
                if (choose == 1) {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = getIntInput(scanner);
                    firstPile = firstPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                } else if (choose == 2) {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = getIntInput(scanner);
                    secondPile = secondPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                } else if (choose == 1) {
                    System.out.print("Now choose no. of tokens: ");
                    noEntered = getIntInput(scanner);
                    thirdPile = thirdPile - noEntered;
                    System.out.println("Bag Status: " + firstPile + ", " + secondPile + ", "
                            + thirdPile);
                }
            }
            next++;
        } while (firstPile != 0 && secondPile != 0 && thirdPile != 0);

        if (next % 2 == 1) {
            System.out.println("Game Over - Player 1 wins");
        } else if (next % 2 == 0) {
            System.out.println("Game Over - Player 2 wins");
        }

}

Hope this will help you to resolve your problem.

A: You can use
 scanner.hasNextInt ()
To find out if there is an int

A: public static int validateNumber () {
    try {
        return scanner.nextInt();
    } catch (InputMismatchException e ) {
         scanner.next();
        System.out.println("not a number");
        return 0 ;
    }
}

A: using
if(scanner.hasNextInt())
reference here:
[http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextInt()][1]


text:
Q: How to spoof complete browser identity? I found question on how to spoof user agent. I dont' want to spoof only user agent. I want to spoof everything from user agent, to Accept headers to http headers and also the information javascript can tell about browser - screen resolution and depth, class cpu, platform, device name, etc.
Do you know of a way to achieve this in any browser out there ? I don't want 10 plugins to achieve this. I'd like unified way.


text:
Q: Using sendRedirect inside a servlet forwarded with request dispatcher I have a filter that implements a custom convention for loading servlets and JSPs. In that convention I am using the following code to include the servlet:
servletContext
    .getRequestDispatcher( uriDispatcherLocator.getServletLocation( uri ) )
    .include( request, response );

and the following code to include the JSP (in the same filter):
servletContext
    .getRequestDispatcher( "/index.jsp" )
    .include( request, response );

Everything works fine, the servlet executes, then it includes the JSP and some irrelevant custom rules take place.
As you can see, at the very moment I include a servlet with request dispatcher I cannot send an http header response to the client.
The problem is that I want the servlet to have full control of the response as if it was called from inside the filter (because the filter will do nothing else than dinamically mapping the servlets according to their respective Class/JSP location in the project file system).
I can use .forward() instead of .include(), but if I do I will not be able to include a JSP after the servlet has been executed.
So, how would I allow the servlet to execute the code below when being included through a filter via RequestDispatcher interface?
response.sendRedirect( "/somePath" );

No Javascript hacks, I am willing to send the proper HTTP response from the server to make the browser behave correctly.
--
EDIT:
In other words:
I want to change the headers sent to the client from INSIDE an included servlet by using RequestDispatcher, but the docs states:
The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

A: Your Filter includes your servlet
servletContext
    .getRequestDispatcher( uriDispatcherLocator.getServletLocation( uri ) )
    .include( request, response );

Your Servlet indicates it wants to redirect
request.setAttribute ("sendRedirect", "/some/path");

or, wishes to add one or more response headers
Map<String, String> respHeaders = new HashMap<String, String>();
respHeaders.put("Expires", "0");
respHeaders.put("Cache-Control", "no-cache");
request.setAttribute("respHeaders", respHeaders);

Your Filter checks for these special requests
Map<String, String> respHeaders =
                   (Map<String, String>) request.getAttribute("respHeaders");
for (String key : respHeaders.keySet()) {
    response.setHeader(key, respHeaders.get(key)); // set response headers
}

String sendRedirect;
if ((sendRedirect = (String) request.getAttribute("sendRedirect")) != null) {
    response.sendRedirect(sendRedirect); // redirect the client
}

EDIT: Perhaps some of your servlets are already driving the flow and setting response headers when called from outside an include. But, there's no way to reuse them as is. You can't simply include them and expect the same behaviour because the goal of a RequestDispatcher#include() is to provide for server-side includes (SSI) only.
Hence, we do not find any overloaded methods (or any setters that could modify this behaviour) in the API. If you want to include such servlets and retain their behaviour (like redirects) you would have to pass them a hint that they're running under an include context and so should submit their response requests.
request.setAttribute ("includeContext", true);


text:
Q: How to fix app keeps downloading the wrong image? I'm building a simple image listing app with some extra features, including a download image feature.
I've managed to successfully download the image, but somehow the app keeps downloading the wrong one from my JSON.
Rendering items from a JSON:
renderItem = ({ item }) => {

  imageToDownload = item.image;

  return (
    <View style={{ padding: 15, paddingBottom: 0 }}>
      <Card elevation={1}>
        <View
          style={{
            flex: 1,
            flexDirection: "row",
            flexWrap: "wrap",
            alignItems: "flex-start"
          }}
        >

          <View style={{ flex: 1 }}>
            <TouchableOpacity
              onPress={() => {
                imageToDownload = item.image;
                this.toggleModal();
                this.setState({
                  webViewurl: item.image
                });
              }}
              onLongPress={() => Linking.openURL(item.image)}
              activeColor="blue"
            >
              <ImageBackground
                source={{ uri: item.image }}
                style={{ height: 216 }}
              >
                <IconButton
                  icon="favorite-border"
                  size={20}
                  color="#6200EE"
                  style={{ alignSelf: "flex-end" }}
                  onPress={this._savedAlert}
                />
              </ImageBackground>
            </TouchableOpacity>
          </View>
        </View>
      </Card>
    </View>
  );
}

The download image function:
downloadImage() {
  const fileUri = `${FileSystem.documentDirectory}memebook_meme.png`;
  FileSystem
    .downloadAsync(imageToDownload, fileUri)
    .then(({ uri }) => {
      console.log('Finished downloading to ', uri);
    })

  CameraRoll.saveToCameraRoll(fileUri, 'photo');
}

The download button:
<Button
  icon="file-download"
  mode="contained"
  onPress={this.downloadImage}
  style={{ borderRadius: 0, width: "33.4%" }}
/>

UPDATE
My data:
{
    "listings": [
     {
         "title": "pikachu",
         "image": "https://3.pik.vn/20182c2771b3-e6fd-4018-ba30-ad1d6a1e93ab.jpg"
     },
     {
         ...
     }
]
}

A: You are setting imageToDownload inside the renderItem so it will be overwritten with every call of renderItem and downloadImage is using this global variable. Please consider not using global variables as they lead to problems like this.
Make sure to provide the correct value to the download button so that the correct image will be downloaded!

A: Insert the download button into the renderItem function and use it.
renderItem = ({ item }) => {
...
<Button
  icon="file-download"
  mode="contained"
  onPress={ (item) => this.downloadImage(item)}
  style={{ borderRadius: 0, width: "33.4%" }}
/>

...
downloadImage(item) {
  const fileUri = `${FileSystem.documentDirectory}memebook_meme.png`;
  FileSystem
    .downloadAsync(item.image, fileUri)
    .then(({ uri }) => {
      console.log('Finished downloading to ', uri);
    })

  CameraRoll.saveToCameraRoll(fileUri, 'photo');
}


text:
Q: Bind focus to datacontext in WPF I would like to bind the current focus to the datacontext. My menu system has a viewmodel that contains a list of ButtonViewModels as datacontext. How would I go about having the focused button be determined by the datacontext?
There is a FocusManager.FocusedElement, but this references to a control and the idea of a ViewModel is to not depend on the implementation of the View...

A: I tried to place a DataTrigger in the Button Style which binds to a property called IsFocused in the ButtonViewModel and in the Setter Bind FocusManager.FocusedElement to the Button where IsFocused is set to true. This should allow you to Control the Focus directly from the ButtonViewModel
<ItemsControl ItemsSource="{Binding ButtonViewModels}">
    <ItemsControl.Resources>
        <Style x:Key="FocusBindingStyle" TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsFocused}" Value="True">
                    <Setter Property="FocusManager.FocusedElement"
                            Value="{Binding RelativeSource={RelativeSource Self}}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ItemsControl.Resources>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="Test" Style="{StaticResource FocusBindingStyle}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>


text:
Q: How to remove "http://" from domain name inside view How can I remove "http://" from beginning of a URL inside view in an AngularJS app?
I have URLs in database like:
http://example.com/
http://example.com
example.com

but I only need to show
example.com

inside the view.

A: This deals with HTTP and HTTPS or any other URL. It uses the built-in URL class, which will handle all of the things you haven't thought of correctly.
  app.filter('domain', function () {
    return function (input) {
      try {
        var url = new URL(input);
        return url.hostname;
      } catch (DOMException) {
        // Malformed URL. Return original (or something else).
        return input; }
      };
    });

URLs that are correct and you  might not have thought of:

*

*http://example.com

*http://example.com:8000

*http://me@example.com

*file://example.com

*https://example.com

*http://example.com/some-path

*http://example.com?some-query-url
You may not need them now, but using the correct library function means your app won't break unexpectedly in future when someone tries to use it for something else.

A: use this filter in view
app.filter('domain', function () {
  return function (input) {
    var output = "",
    matches;

    var urls = /\w+:\/\/([\w|\.]+)/;
    matches = urls.exec( input );

    if (matches !== null) output = matches[1];
      return output;
  };
});


text:
Q: How to design templates for clustered nifi Do we need to think about underlying cluster while designing nifi templates?
Here is my simple flow
+-----------------+                         +---------------+                       +-----------------+
|                 |                         |               |                       |                 |
|  READ FROM      |                         |  MERGE        |                       |   PUT HDFS      |
|  KAFKA          |                         |  FILES        |                       |                 |
|                 +-----------------------> |               +---------------------> |                 |
|                 |                         |               |                       |                 |
|                 |                         |               |                       |                 |
|                 |                         |               |                       |                 |
+-----------------+                         +---------------+                       +-----------------+

I have 3 nodes cluster.. When system is running I check "cluster" menu and see only master node is utilizing sources, other cluster nodes seems idle... The question is in such a cluster should I design template according to cluster or nifi should do the load balancing.
I saw one of my colleagues created remote processors for each node on cluster and put a load balancer in front of these within template, is it required? (like below)
                                                                   +------------------+
                                                                   |                  |                 +-------------+
                                                                   | REMOTE PROCESS   |                 |  input port |
                                                            +----> | GROUP FOR        |                 |    (rpg)    |
                                                            |      | NODE 1           |                 +-------------+
                                                            |      |                  |                        |
                                                            |      |                  |                        |
                                                            |      +------------------+                        v
+-----------------+               +-----------------+       RPG
|                 |               |                 |       |                                           +--------------+
|  READ FROM      |               |                 |       |                                           |              |
|  KAFKA          |               | LOAD BALANCER   |       |       +------------------+                | MERGE FILES  |
|                 +-------------> |                 +-------------> |                  |                |              |
|                 |               |                 |       |       |  REMOTE PROCESS  |                |              |
|                 |               |                 |       |       |  GROUP FOR       |                |              |
|                 |               |                 |       |       |  NODE 2          |                |              |
+-----------------+               +-----------------+       RPG     |                  |                +--------------+
                                                            |       +------------------+                       |
                                                            |                                                  |
                                                            |                                                  v
                                                            |
                                                            |       +-------------------+               +---------------+
                                                            |       |                   |               |               |
                                                            |       |   REMOTE PROCESS  |               | PUT HDFS      |
                                                            +-----> |   GROUP FOR       |               |               |
                                                                    |   NODE 3          |               |               |
                                                                    |                   |               |               |
                                                                    |                   |               |               |
                                                                    +-------------------+               +---------------+

And what is the use-case for load-balancer except remote clusters, can I use load-balancer to split traffic into several processors to speedup the operation?

A: Apache NiFi does not do any automatic load balancing or moving of data, so it is up to you to design the data flow in a way that utilizes your cluster. How to do this will depend on the data flow and how the data is being brought into the cluster.
I wrote this article once to try and summarize the approaches:
https://community.hortonworks.com/articles/16120/how-do-i-distribute-data-across-a-nifi-cluster.html
In you case with Kafka, you should be able to have the flow run as shown in your first picture (without remote process groups). This is because Kafka is a data source that will allow each node to consume different data.
If ConsumeKafka appears to be running on only one node, there could be a couple of reasons for this...
First, make sure ConsumeKafka is not scheduled for primary node only.
Second, figure out how many partitions you have for your Kafka topic. The Kafka client (used by NiFi) will assign 1 consumer to 1 partition, so if you have only 1 partition then you can only ever have 1 NiFi node consuming from it. Here is an article to further describe this behavior:
http://bryanbende.com/development/2016/09/15/apache-nifi-and-apache-kafka


text:
Q: I can't get the Knight's Honor trophy Knight's Honor trophy will not come up. I've looked all over the net and I have all the weapons. Can someone give me the full list of what they are, please? I need to know if the trophy is glitched or not.  I got a list of all the weapons I need but it still did not come up.  Does anyone know how to resolve this?

A: A quick duckduckgo search provided :Link To Guide With Items
Chaos Blade
Crystal Ring Shield
Darkmoon Bow
Dragonbone Fist
Dragonslayer Spear
Golem Axe
Great lord Greatsword
Greatshield of Artorias
Greatsword of Artorias
(True) Greatsword of Artorias
Lifehunt Scythe
Moonlight Butterfly Horn
Quelaag's Furysword
Smough's Hammer
Tin Darkmoon Catalyst
--Weapons or Shields dropped by enemies--
Black Knight Greataxe
Black knight Greatsword
Black Knight Halberd
Black Knight Shield
Black knight Sword
Channeler's Trident
Crest Shield
Crescent Axe
Demon's Spear
Giant's Halberd
Grant
Sanctus
Silver Knight Shield
Silver Knight Spear
Silver Knight Straight Sword
Stone Greatshield
Stone Greatsword
--Weapons found as treasure--
Astoria's Straight Sword
Blood Shield
Dragon Crest Shield
Dragon Tooth
Dragonslayer Greatbow
Effigy Shield
Havel's Greatshield
Velka's Rapier
--Weapons or Shields acquired from covenants--
Dark Hand
Gravelord Sword
Dragon Greatsword
-- Weapons acquired from cutting off boss tails--
Drake Sword
Dragonking Greataxe
Moonlight Greatsword
Priscilla's Dagger

A: There seems to be an issue obtaining this trophy when you've used the Bottomless Box glitch to obtain all of the weapons. Downgrading one of your weapons and re-ascending it may help.
See here for more details: http://forums.demonssouls.info/viewtopic.php?f=76&t=15092


text:
Q: Django model with crud operations Working with Django and stuck on how to make my model c.r.u.d operations using Models.Manager.
The fields I'm working with are zipcode, city, latitude, longitude, coordinates and current time.
I would like to insert a new entry with zipcode, city, latitude, longitude and current time.
Also, would like to update an existing record by zipcode.  Lastly, get a record by zipcode returning city and get a record by zipcode returning city, state, and coordinates( latitude and longitude ).
from django.db import models
from datetime import datetime

class Name(models.Model):
    zipcode     = models.CharField(max_length=5, primary=True, blank=False)
    city        = models.CharField(max_length=50, blank=False)
    state       = models.CharField(max_length=2, blank=False)
    latitue     = models.CharField(max_length=15, blank=False)
    longitue    = models.CharField(max_length=15, blank=False)
    curr_time   = models.datetime(default=datetime.now, blank=False)

A: You should read the django documentation some more https://docs.djangoproject.com/en/1.3/. The tutorial has a portion talking about saving and updating models. However, in answer to your question...
from models import Name
from datetime import datetime

# create a new model
name = Name(city='New York', state='NY')
# fields can also be set this way
name.zipcode = '10027'
# save the model to the database
name.save()
# find a model by zipcode
name = Name.objects.filter(zipcode='10027')
# modify it
name.curr_time = datetime.now()
# save it
name.save()

Easy, right?

A: For your curr_time field, you may use:
curr_time = models.DateField(auto_now=True)
# or auto_now_add=True, if you want set this field only at the creation.

More here: https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield


text:
Q: Difference between Jstack and gcore when generating Core Dumps? We all know that Core Dumps are an essential diagnostic tools for analysing various processes in Unix . I know both jstack  and gcore  are both used for generating Javacore files or Core Dumps but I have a doubt that Gcore is mainly used for Processes and Jstack is used for threads .
As from an Operating System perspective Process and Threads though interrelated (Process comprises of Threads only) they are relatively different from each other w.r.t memory/speed/execution . So is that gcore  will diagnose the process and jstack will analyse the threads in that process ???

A: GCore act at OS level and you got a dump of native code that is currently running. From a java point of view, it is not really understandable.
JStack get you the stack trace at VM level (the java stack) of all thread your application have. You can find from that what is the real java code executed at a point.
Clearly, GCore is almost never used (too low level, native code...). Only really strange issue with native library or stuff like that will perhaps need this kind of tool.
There is also jmap that can generate a hprof file which is the heap data from you VM. A tool like 'Memory Analyser Tool' can open the hprof, and you can drill down on what was going on (on memory side).
If your VM crash because of a OutOfMemory, you can also set parameter to get the hprof when the event occurs. It helps to understand why (too many users, A DB query that fetch too much data...)
Last thing is the fact that you can add a debug option when your start your VM, so that you can connect to it, and put debug on running process. It can help if you have some strange issue that you are not able to reproduce in your local environment.


text:
Q: How to add icons to AngularUI calendar I used this AngularUI calendar
I want to add icons (Bootstrap glyphicons) like this

any help please,
thank you

A: Finally I found the solution.With className Event Object you can do this.
$scope.events = [
    {className: 'fa fa-bar-chart', title: 'dashboard', start: new Date(y, m, 1), url: 'http://localhost/view_finance'},
    {className: 'fa fa-user', title: 'dashboard 2', start: new Date(y, m, 1), url: 'http://localhost/view_finance/d/dash2'},
    {className: 'fa fa-bar-chart', title: 'invoice', start: new Date(y, m, 5), url: 'http://localhost/view_finance/invoice/invoice#!/invoice_view'},
    {id: 999, title: 'documents', start: new Date(y, m, d - 3, 16, 0), url: 'http://localhost/view_finance/files/browse/home'},
    {id: 999, title: 'control side', start: new Date(y, m, d + 4, 16, 0), url: 'http://localhost/view_finance/manage/dashboard'},
    {title: 'balance', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), url: 'http://localhost/view_finance/d/balance'},
    {title: 'invoice settings', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://localhost/view_finance/invoice/invoice#!/invoice_setting'}
];


text:
Q: How to split this types of dictionary in python I have created web service using flask, so add request JSON parameter but now then problem is how to split my dict into simple data
My dictionary is
order={
   "userid":17,
   "details":[
      {
         "productid":1,
         "eachprice":45,
         "quantity":1,
         "price":45
      },
      {
         "productid":3,
         "eachprice":749,
         "quantity":1,
         "price":749
      }
   ]
}

so I split like
for x, y in order.items():
            print(x, y)

but the question is how I print nested data

A: A quick and not so nice (=not general) solution is this:
for x, y in order.items():
    print(x,y, type(y))
    if type(y) == list:                     # check if the value is a list
        for element in y:                   # loop lists
            for k, v in element.items():    # loop dictionaries within the list
                print(k,v)

A: Based on a recipe that recursively calculates the size of an object, this recursive solution basically flattens the whole data structure to a 1-dimensional list:
import itertools
def unpack(object, lst=[]):
    typ = type(object)
    dict_handler = lambda d: itertools.chain.from_iterable(d.items())

    if typ is dict:
        object = dict_handler(object)       # Iterate over both keys and values when dict
    if typ in [list, set, tuple, dict, frozenset]:
        for e in object:
            unpack(e, lst)                  # Recursive call for elements in container
    else:
        lst.append(object)
    return lst

print(unpack(data))


text:
Q: Stay hidden after fadeout I have a logo in a preloader div that I want to fade out Up after a call.
The logo does fadeoutup but becomes visible after it's faded out completely.
What I want is to keep it faded out or make it display none with CSS only if possible I can use jquery but rather not.
&.preloader-remove{
            -webkit-animation: fadeOutUp 1s;
            animation: fadeOutUp 1s;
        }

Css Animation
@-webkit-keyframes fadeOutUp {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
    -webkit-transform: translate3d(0, -100%, 0);
    transform: translate3d(0, -100%, 0);
  }
}

@keyframes fadeOutUp {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
    -webkit-transform: translate3d(0, -100%, 0);
    -ms-transform: translate3d(0, -100%, 0);
    transform: translate3d(0, -100%, 0);
  }
}

.fadeOutUp {
  -webkit-animation-name: fadeOutUp;
  animation-name: fadeOutUp;
}

A: Try using a css transition rather than animation:
&.preloader-remove {
    position: relative;
    top: 50px;
    opacity: 0;
    -webkit-transition: top 1s, opacity 1s;
    transition: top 1s, opacity 1s;
}

A: From the jquery api:http://api.jquery.com/fadeout/
.fadeOut()
Description: Hide the matched elements by fading them to transparent.
$( "#clickme" ).click(function() {
  $( "#book" ).fadeOut( "slow", function() {
    // Animation complete.
  });
});


text:
Q: Does anyone know why a default rails app on the bitnami stack would refuse to allow the app root to be set? I have just begun using rails so I apologize if this is a dumb question, but I have been googling for a few hours and I'm starting to get really frustrated.
I've set up an AWS Bitnami Rails stack using the free one on the AWS Marketplace, and I've been following the tutorial at http://guides.rubyonrails.org/getting_started.html to start getting my head around running an app functionally. (I've already done rails for zombies and ruby 101)
Basically, I get to section 4.3 which is supposed to set me up with the basic routing for the app and I can't seem to get it to work. No matter what I put in the routing file of the welcome_controller, the app just serves the template index file located at /opt/bitnami/ruby/lib/ruby/gems/2.3.0/gems/railties-4.2.5.1/lib/rails/templates/rails/welcome/index.html.erb
My routes.rb file is
Rails.application.routes.draw do

  get 'welcome/index'

  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  # You can have the root of your site routed with "root"
  root 'welcome#index'

and my welcome_controller is
    class WelcomeController < ApplicationController
  def index
  end
end

I really hope someone can help.
I'm guessing this is some sort of really stupid config error but I have a feeling others might have it as well so maybe this could be of use in the future.

A: Two possibilities:

*

*You didn't restart the rails server after you generated controller. Though, /welcome/index etc should still work without restart.

*Your server is running from directory which doesn't have this code checked in. As your error log doesn't reports absence of routes altogether.


text:
Q: RoR appended ?format= on form submit I'm creating a little newsletter application, with 'double opt-in restrictions', when I simply fill in my form (subscription page) and submit the form I get redirected to my subscribed page (which is all normal) however my form appends a querystring to my action attribute of my form (http://localhost:3000/newsletter/subscribe?format=)
routes:
  match 'newsletter/subscription' => 'newsletter_subscriptions#subscription'
  post 'newsletter/subscribe' => 'newsletter_subscriptions#subscribe'

controller:
class NewsletterSubscriptionsController < ApplicationController
  respond_to :html

  # GET /newsletter/subscription
  def subscription
    respond_with (@subscription = NewsletterSubscription.new)
  end

  # POST /newsletter/subscribe
  def subscribe

    # If there's already an unconfirmed record with the submitted email, use that object otherwise create a new one based on the submitted email
    sub_new       = NewsletterSubscription.new
    sub_new.email = params[:newsletter_subscription]['email']
    sub_old       = NewsletterSubscription.find_by_email_and_confirmed sub_new.email, 0
    @subscription = sub_old || sub_new

    if @subscription.save
      Newsletter.delay.subscribed(@subscription) # with delayed_job
    else
      render :action => "subscription"
    end
  end

  ...

end

view (newsletter_subscription/subscription.html.erb):

New newsletter_subscription

<%= form_for(@subscription, :url => newsletter_subscribe_path(@subscription)) do |f| %>
    <% if @subscription.errors.any? %>

<%= pluralize(@subscription.errors.count, "error") %> prohibited this newsletter_subscription from being
            saved:

            <% @subscription.errors.full_messages.each do |msg| %>

<%= msg %>

            <% end %>

    <% end %>

      <%= f.label :email %>

      <%= f.text_field :email %>

      <%= f.submit %>

<% end %>

PS: I would be pleased if someone could evaluate my ruby code please (posted above), I'm still learning a lot and would like to see some 'guidelines' or feedback, I think I still can learn a lot.

A: Try removing the @subscription argument you're passing into newsletter_subscribe_path. Since there isn't an :id in the route and it's a new object, passing it doesn't really make sense. I'm assuming that's what is being interpreted as the format.
<%= form_for(@subscription, :url => newsletter_subscribe_path) do |f| %>

As for improvements you can make to the code, the biggest thing I see is moving the old/new subscription logic into the model.
# in NewsletterSubscription
def self.with_email(email)
  find_by_email_and_confirmed(email, 0) || new(:email => email)
end

# in controller
@subscription = NewsletterSubscription.with_email(params[:newsletter_subscription]['email'])
if @subscription.save
#...

Also respond_to and respond_with aren't really necessary here since you're just dealing with HTML views. You can remove that.


text:
Q: Cauchy-Schwarz for exected value of sum In a proof I am reading, Cauchy Schwarz is given to justify the following inequality:
$$\mathbb E[\sum_i a_ib_i]\le \big(\sum\mathbb E[a_i^2]\big)^{1/2}\big(\sum\mathbb E[b_i^2]\big)^{1/2}=:RHS$$
where $\{a_i,b_i\}$ is a finite collection of random variables.
I am having trouble seeing how exactly C-S is applied here. I am assuming C-S to be $$\sum a_ib_i\le (\sum a_i^2)^{1/2}(\sum b_i^2)^{1/2}$$
So taking the expectation gives (by monotonicity)
$$\mathbb E[\sum a_ib_i]\le \mathbb E[(\sum a_i^2)^{1/2}(\sum b_i^2)^{1/2}]$$
But in order to get RHS I am imagining having to use Jensen's inequality with the concave function $x\mapsto x^{1/2}$, then arguing that $a_i$'s and $b_i$'s are uncorrelated to separate the two expectations, which is not obvious.
Especially since they are probably not uncorrelated because $a_i=(W_i-W_{i-1})^2$ is the square of a Brownian increment, and $b_i=h(W_{i-1},W_i)$ is a function of the two random variables that make up the increment.

A: Consider this a little bit larger. Take $[1..n]\times\Omega$ as base space, $a$, $b$ are square-integrable functions on this space and the scalar product as
$$
\langle a,b\rangle=\mathbb E[\sum_i a_ib_i].
$$
Then the cited inequality is just the bare Cauchy-Schwarz inequality for this scalar product.


text:
Q: Subdomain showing directory content I am devoloping a website with htaccess rules. This is the url structure:
example.com
example.com/index.php/login
example.com/index.php/foo
demos.example.com

For the last url above (demos.example) I would like to do show the content of example.com/index.php/demos, for this reason, I have create a .htaccess file as follow:
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?demos.example.com
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/demos [L]

When I browse demos.example.com the index page is displayed (example.com), as nothing had happended. I hope that my explanation has been clear.

*

*I have readed this topic, but this solution do a "browser redirection" and that is not the idea.

*Using this example produces nothing: the index is displayed instead of index.php/demos

Update
If I use the .htaccess as follow:
RewriteCond %{HTTP_HOST} ^(www\.)?demos\.example\.com
RewriteRule ^(.*)$ index.php/demos/$1 [L]

...this make that the browser display a 500 internal server error. Viewing the log, it prints the following messages:
[Thu Dec 06 15:06:24 2012] [error] [client 201.192.30.254] Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace., referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3112): [client 201.192.30.254] r->uri = /index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/index.php/demos/index.php/demos/index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/index.php/demos/index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /index.php/demos/, referer: http://example.com/
[Thu Dec 06 15:06:24 2012] [debug] core.c(3118): [client 201.192.30.254] redirected from r->uri = /, referer: http://example.com/

A: Try this:
RewriteCond %{HTTP_HOST} ^(www\.)?demos\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/index.php/demos/$1 [L]


text:
Q: How to type the arguments of a function that returns a function I am trying to create type definitions for various axios services for the resources in my app. I'd like to enforce a specific configuration type for specific services (e.g. a function that fetches one resource should have the method property to set GET). Here is what I have:
import { AxiosPromise } from 'axios';
import fetch from 'auth/FetchInterceptor';

type TFetchOneConfig = {
    url: string;
    method: 'GET' | 'get';
};

type TFetchOne = (
    id: number
) => ReturnType<(config: TFetchOneConfig) => AxiosPromise<any>>;

interface Service {
    fetchOne: TFetchOne;
}

const AccountService: Service = {
    fetchOne: (id) => fetch({ url: `/accounts/${id}`, method: 'GET' }),
};

where fetch is an AxiosInstance.
The problem I'm having is that I can provide any AxiosRequestConfig (e.g. method: 'POST') to the fetch AxiosInstance in the fetchOne function. How do I enforce the TFetchOneConfig type as the configuration?

A: As you said, fetch is of type AxiosInstance, and that's it. If you want to enforce a different behavior to fetch - it should be of a different type. Means, you could write your own "copy" of the AxiosIntance interface, like this:
interface MyAxiosInstance extends AxiosInstance {
  (config: AxiosRequestConfig & TFetchOneConfig): AxiosPromise;
}

And then use this interface to type your fetch.


text:
Q: Running a function on non empty cells I have this small data set. Can you please advice on how can i move the content on v1 to state column only if v1 cells are not empty? the idea is not to replace the content that is already in state and zip
v1    v2    state    zip
            ia     51732
nc    29576

A: Find out the rows where v1 is not empty and move first 2 columns to column 3 and 4 for those rows. Turn first 2 columns back to empty.
inds <- df$v1 != ''
df[inds, 3:4] <- df[inds, 1:2]
df[inds, 1:2] <- ''

df
#  v1 v2 state   zip
#1          ia 51732
#2          nc 29576

data
df <- structure(list(v1 = c("", "nc"), v2 = c("", "29576"), state = c("ia",
""), zip = c("51732", "")), row.names = c(NA, -2L), class = "data.frame")


text:
Q: why am not getting data from firestore? hello I have the list of categories in my firestore i want to fetch them in to a listview it only shows CircularProgressIndicator then after it disapear nothing comes on screen where  did get  wrong?
Expanded(
                        child: _appwidget.customeTextFormField(
                            hint: "Select category",
                            icon: InkWell(
                                onTap: () {
                                  showFancyCustomDialog(context,
                                      height: 500,
                                      width: 500,
                                      title: "Add / Select / Delete Category",
                                      widget: FutureBuilder<DocumentSnapshot>(
                                          future: _services.category
                                              .doc("ProductCategories")
                                              .get(),
                                          builder: (BuildContext context,
                                              AsyncSnapshot<DocumentSnapshot>
                                                  snapshot) {
                                            if (snapshot.hasError) {
                                              return Text('error');
                                            }
                                            if (snapshot.connectionState ==
                                                ConnectionState.waiting) {
                                              return Container(
                                                child:
                                                    Center(child: CircularProgressIndicator()),
                                              );
                                            }

                                            return ListView.builder(
                                              itemBuilder:
                                                  (BuildContext context,
                                                      int index) {
                                                return ListTile(
                                                  title: Text(snapshot.data!["Categories"]
                                                      [index]["name"]),
                                                );
                                              },
                                              itemCount: snapshot.data!['Categories'] ==
                                                      null
                                                  ? 0
                                                  : snapshot.data!['Categories'].length,
                                            );
                                          }),
                                      addButton: Container());
                                },
                                child: Icon(Icons.list)))),

A: You forgot to tackle the condition in which you have data.
Just add if(snapshot.hasData) & return your ListView.builder(), because in other conditions you are not sure whether you have received the data or not.
return Expanded(
        child: _appwidget.customeTextFormField(
            hint: "Select category",
            icon: InkWell(
                onTap: () {
                  showFancyCustomDialog(context,
                      height: 500,
                      width: 500,
                      title: "Add / Select / Delete Category",
                      widget: FutureBuilder<DocumentSnapshot>(
                          future: _services.category
                              .doc("ProductCategories")
                              .get(),
                          builder: (BuildContext context,
                              AsyncSnapshot<DocumentSnapshot>
                              snapshot) {
                            if (snapshot.hasError) {
                              return Text('error');
                            }
                            if (snapshot.connectionState ==
                                ConnectionState.waiting) {
                              return Container(
                                child:
                                Center(child: CircularProgressIndicator()),
                              );
                            }
                            if(snapshot.hasData){
                              return ListView.builder(
                                itemBuilder:
                                    (BuildContext context,
                                    int index) {
                                  return ListTile(
                                    title: Text(snapshot.data!["Categories"]
                                    [index]["name"]),
                                  );
                                },
                                itemCount: snapshot.data!['Categories'] ==
                                    null
                                    ? 0
                                    : snapshot.data!['Categories'].length,
                              );
                            }

                          }),
                      addButton: Container());
                },
                child: Icon(Icons.list))));


text:
Q: resolve typeerror: list indices must be integers or slices, not str I am quite new to python, so maybe there is a simple answer to my question.
I have imported data from a json file as follows:
input:
with open('file_destination.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
print(data)

output:
[{'Node': {'Construction': {'id': 'd9794e40-c894-5027-8576-b30a3eb3c95c'}]

I would like to be able to extract the data for e.g. id = d9794e40-c894-5027-8576-b30a3eb3c95c, however I get:
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print(data['id'])
TypeError: list indices must be integers or slices, not str

Can anyone help me resolve this issue?

A: I've run :
t=[{'Node': {'Construction': {'id': 'd9794e40-c894-5027-8576-b30a3eb3c95c'}}}]
print(t[0]['Node']['Construction']['id'])

And i get this output:
d9794e40-c894-5027-8576-b30a3eb3c95c

I assume this solves your problem.


text:
Q: Column header repeat don´t work in ssrs 2008 I have a report with a tablix that has row headers. I want to repeat the headers on each page, so I activated the flag "Repeat header columns on each page". But nothing happens... this worked with earlier versions of ssrs...

A: Answer can be found here.

A: You may also need to set KeepWithGroup to "After" in that Report Group properties. Need to switch to Advanced mode to see this option. How to switch to Advanced mode: click littel downward triangle on the right from "Column Groups" heading


text:
Q: YouTube Analytics API Reports query: 400 bad request As a content owner I would like to retrieve reports by using the reports.query method in the YouTube Analytics API. When I execute the request the error is: badRequest with the message The query is not supported. Code 400.
I fill in the following fields:

*

*ids: contentOwner==MyContentOwnerId

*start-date:2017-08-01

*end-date:2017-08-10

*metrics:views

Why do I receive the 400 error? Thanks for your time!
Robert

A: I tried your query and I got the same bad request error, however when I filter it down to the video level it provides me with the information I needed.
ids: contentOwner==ContentOwnerId
start-date: 2017-08-01
end-date:2017-08-10
metrics:views
dimension:day
filter:video==videoId
Hope this helps!


text:
Q: Shadows in mathematica Graphics3D If I understood the Mathematica documentation correct ( haven't found examples either ) Graphics3D does not produce shadows of 3D objects, although Graphics3D has a Lighting-> option.
Question: Have you ever tried to produce Mathematica 3D objects with shadows? If so have you solved this in Mathematica? Or have you exported the graphics to other 3D ( scene-graph ) viewers like for example J-Reality?

A: The shading model used by MMA, the so-called Phong shading, determines the pixel intensities based on a simple relationship between local surface orientation, light source direction(s), camera direction and diffuse and specular properties of the surface. No other aspect of the geometry is taken into account, which means that objects do not influence the pixel values of other objects even if they are between the object and the light source.
This means that the model doesn't generates shadows. It is not able to.
You could simulate shadows yourself by projecting your object's polygons on the ground plane or wall planes as applicable. That shouldn't be too difficult, but shadows on non-planar surfaces will be pretty hard.
Example:
polys = (PolyhedronData["GreatRhombicTriacontahedron", "Faces"] //
      Normal // N) /. {x_, y_, z_}?VectorQ -> {x, y, z + 6};
     (* raise it slightly above ground plane*)

shadow = polys /. {x_, y_, z_}?VectorQ -> {x - z, y, 0};
         (* projection from a directional light source at 45 deg elevation *)

Graphics3D[{polys, EdgeForm[], FaceForm[Darker@Gray], shadow},
 Lighting -> {{"Directional", White, {{1, 0, 1}, {0, 0, 0}}}},
 Boxed -> False]

Of course, you need to make sure that the lighting sources (point, spot, directional...) and your shadow projection are consistent.


text:
Q: Magento 2 opensearch indexing error I'm using opensearch, when I'm trying to reindex 'catalogsearch_fulltext', I'm getting error:
{"error":"no handler found for uri [/khmagento2_product_1_v2/document/_mapping] and method [PUT]"}'
Here is the result of:
curl -u admin:admin -i http://localhost:9200/_cluster/health
{"cluster_name":"khmagento2","status":"yellow","timed_out":false,"number_of_nodes":1,"number_of_data_nodes":1,"discovered_master":true,"discovered_cluster_manager":true,"active_primary_shards":14,"active_shards":14,"relocating_shards":0,"initializing_shards":0,"unassigned_shards":12,"delayed_unassigned_shards":0,"number_of_pending_tasks":0,"number_of_in_flight_fetch":0,"task_max_waiting_in_queue_millis":0,"active_shards_percent_as_number":53.84615384615385}
in magento configuration:

A: Downgrade to Opensearch 1.3.6 and it will work. You will have to delete the old data from /var/lib/opensearch otherwise opensearch won't start, it will throw exceptions/segfaults.


text:
Q: three.js - update (copy?) object position I just instantiated an object for every vertex of another mesh, and applied some morph targets to this last one. Unfortunately, when I tweak the shape of the big mesh, the instantiated little meshes do not move at all! They stand still like the english queen's guards.
My question is: is there any way to let the little ones follow the other one's vertices? Keep in mind I'm using a for loop with an array where I push object2.clone()s for every vertex.
Thanks in advance!
UPDATE: Here's a portion of the code i'm using:
// some stuff before
var mesh = new THREE.Mesh( geometry, material );
// SFERETTE
var sfera = new THREE.SphereGeometry(1.5, 24, 20, 0, Math.PI * 2, 0, Math.PI * 2);
var material2 = new THREE.MeshLambertMaterial( {
    color: 0x005c6c
} );

var mesh2 = new THREE.Mesh( sfera, material2 );

// ARRAY POSIZIONAMENTO VERTICI
var sferetta = mesh2.clone();
sferetta.matrixWorldNeedsUpdate = true;
sferetta.position.needsUpdate = true;
//  sferetta.matrixAutoUpdate = false;

var vertexArray = [];
for (var i = 0; i < geometry.vertices.length; i++) {
    vertexArray.push(geometry.vertices[i])
}
for (var i = 0; i < vertexArray.length; i++) {
    sferetta.position.set(vertexArray[i].x, vertexArray[i].y, vertexArray[i].z)

    mesh.add(sferetta.clone())
}
// TUTTA LA GIOSTRA SM

scene.add( mesh );

// MORPHING
var params = {
    influence1: 0,
    influence2: 0,
    influence3: 0,
    influence4: 0,
    influence5: 0,
    influence6: 0,
    influence7: 0,
    influence8: 0,
    influence9: 0,
    influence10: 0,
    influence11: 0,
    influence12: 0,
    influence13: 0,
    influence14: 0,
    influence15: 0,
    influence16: 0
};
var gui = new dat.GUI();
var folder = gui.addFolder( 'Morph Targets' );
folder.add( params, 'influence1', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 0 ] = value; } );
folder.add( params, 'influence2', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 1 ] = value; } );
folder.add( params, 'influence3', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 2 ] = value; } );
folder.add( params, 'influence4', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 3 ] = value; } );
folder.add( params, 'influence5', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 4 ] = value; } );
folder.add( params, 'influence6', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 5 ] = value; } );
folder.add( params, 'influence7', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 6 ] = value; } );
folder.add( params, 'influence8', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 7 ] = value; } );
folder.add( params, 'influence9', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 8 ] = value; } );
folder.add( params, 'influence10', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 9 ] = value; } );
folder.add( params, 'influence11', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 10 ] = value; } );
folder.add( params, 'influence12', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 11 ] = value; } );
folder.add( params, 'influence13', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 12 ] = value; } );
folder.add( params, 'influence14', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 13 ] = value; } );
folder.add( params, 'influence15', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 14 ] = value; } );
folder.add( params, 'influence16', 0, 1 ).step( 0.01 ).onChange( function( value ) { mesh.morphTargetInfluences[ 15 ] = value; } );
folder.open();


text:
Q: how to update the contact list on UI without using set state() via button pressed or refreshing the page in flutter? I am creating an app in flutter in which i can select the contacts from phone book , saving them in shared preferences and displaying contact list on main page UI. Every thing is working fine but i have to press the load button each time to show the updated list on UI . I want it to update automatically when i go back to main.dart page after selecting the contacts. how can i manage this state?
main.dart file :
import 'package:flutter/material.dart';
import 'package:mapstest/test_stuff/contact_model.dart';
import 'package:mapstest/test_stuff/google_maps.dart';
import 'package:mapstest/test_stuff/select_contacts.dart';
import 'package:mapstest/test_stuff/shared_pref.dart';
import 'package:mapstest/test_stuff/sms.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  SharedPref sharedPref = SharedPref();
  ContactModel modelLoad = ContactModel(
      displayName: 'saniya', phoneNumber: '324235 ');
  List _list = [];

  @override
  initState() {
    super.initState();
    // Add listeners to this clas
    // loadSharedPrefs();
  }

  loadSharedPrefs() async {
    try {
      _list.clear();
      print('in load shared pref-- getting keys ');
      final prefs = await SharedPreferences.getInstance();

      final keys = prefs.getKeys();

      print('now load shared pref ');
      for (String key in keys) {
        ContactModel user = ContactModel.fromJson(await sharedPref.read(key));
        _list.add(user);
      }
      setState(() {

      });
      print('done load shared pref ');
    }
    catch (Excepetion) {

    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Testing Stuff for FYP'),
          centerTitle: true,
        ),
        body: Column(
          children: [
            RaisedButton(
              onPressed: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => GoogleMaps()));
              },
              child: const Text('View Google Maps'),
            ),
            RaisedButton(
              onPressed: () {
              //  Navigator.push(context,
                //    MaterialPageRoute(builder: (context) => ShareData()));
              },
              child: const Text('Share Over Apps'),
            ),
            RaisedButton(
              onPressed: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => MySMS(list: _list,)));
              },
              child: const Text('SMS ALERT'),
            ),
            RaisedButton(
              onPressed: () {
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => Plugin1()));
              },
              child: const Text(''
                  'select contacts'),
            ),
            RaisedButton(
              onPressed: () async {
                await loadSharedPrefs();

              },
              child: Text('Load', style: TextStyle(fontSize: 20)),
            ),
            Expanded(
              child: _list.isNotEmpty ?
              ListView.builder(
                shrinkWrap: true,
                itemCount: _list.length,
                itemBuilder: (context, position) {
                  return ListTile(
                    leading: Icon(Icons.contacts),
                    title: Text(
                      _list[position].displayName.toString(),
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    subtitle: Text(_list[position].phoneNumber.toString()) ,
                    trailing: IconButton(
                      icon: Icon(Icons.delete),
                      onPressed: () async {
                        print( _list[position].displayName.toString());
                        String key = _list[position].displayName.toString();
                        await deleteFromSharedPrefs(key);
                        deleteFromList(position);

                      },

                    ),

                  );

                },
              ) : Center(child: Text('No list items to show')),
            ),

          ],
        ));
  }

  void deleteFromList(int index) {
    print('deleting from list');
    _list.removeAt(index);
    print('deleted from list');

    setState(() {

    });

  }

  Future<void> deleteFromSharedPrefs(String key) async {
    print('deleting from SharedPref');
    final prefs = await SharedPreferences.getInstance();
    SharedPref sharedPref = SharedPref();
    sharedPref.remove(key);
    print('deleted from SharedPref');
  }

}

select_contacts.dart file:
//import 'package:contacts_test/main.dart';
//import 'package:contacts_test/shared_pref.dart';
import 'package:flutter/material.dart';
import 'package:fluttercontactpicker/fluttercontactpicker.dart';
import 'package:mapstest/test_stuff/shared_pref.dart';
import 'package:permission_handler/permission_handler.dart';

import 'contact_model.dart';

class Plugin1 extends StatefulWidget {
  const Plugin1({Key? key}) : super(key: key);

  @override
  State<Plugin1> createState() => _Plugin1State();
}

class _Plugin1State extends State<Plugin1> {
  SharedPref sharedPref = SharedPref();
  ContactModel model = ContactModel(displayName: ' ' , phoneNumber: ' ');
  List<ContactModel> _list = [];

  PhoneContact? _contact;

  String? _phoneContact;
  String? _name;
  int? _id;

  final Permission _permission = Permission.contacts;
  PermissionStatus _permissionStatus = PermissionStatus.denied;

  Future<PermissionStatus> _getContactPermission() async {
    _permissionStatus = await _permission.status;

    if (_permissionStatus != PermissionStatus.granted) {
      _permissionStatus = await _permission.request();
      return _permissionStatus;
    } else {
      return _permissionStatus;
    }
  }

  pickContact() async {

    PermissionStatus permissionStatus = await _getContactPermission();
    if (permissionStatus == PermissionStatus.granted) {
      final PhoneContact contact =
      await FlutterContactPicker.pickPhoneContact();

      _phoneContact = contact.phoneNumber?.number;
      _name = contact.fullName;

      //set into model
      model = ContactModel( displayName: _name.toString(), phoneNumber: _phoneContact.toString());

      await sharedPref.save(model.displayName, model);

      _list.add(model);
      setState(()  {

      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [

            RaisedButton(
              onPressed: () {
                pickContact();
              },
              child: Text('select contacts'),
            ),
            Expanded(
              child: _list.isNotEmpty ?
              ListView.builder(
                shrinkWrap: true,
                itemCount: _list.length,
                itemBuilder: (context, position) {
                  return ListTile(
                    leading: Icon(Icons.contacts),
                    title: Text(

                        _list[position].displayName.toString()
                    ),

                  );

                },
              ) : Center(child: Text('No list items to show')),
            ),

            //     Text(_phoneContact ?? "contact not selected" ),
            //    Text(_name ?? "name not selected" ),]
          ],
        ));
  }
}

shared_pref.dart file (separate class for shared preferences)
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class SharedPref {
  read(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return json.decode(prefs.getString(key).toString());
  }

  save(String key, value) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(key, json.encode(value));
  }

  remove(String key) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.remove(key);
  }

  clearData() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.clear();
  }

}

contact_model.dart file (model class for contacts):
class ContactModel {
  int? id;
  String displayName;
  String phoneNumber;

  ContactModel({ this.id, required this.displayName, required this.phoneNumber});

  //setters
  set contactName(String dispName) {
    displayName = dispName;
  }

  set contactNumber(String num) {
    phoneNumber = num;
  }

  //getters
  String get contactName {
    return displayName;
  }

  String get contactNumber {
    return phoneNumber;
  }

  ContactModel.fromJson(Map<String, dynamic> json)
      : displayName = json['displayName'],
        phoneNumber = json['phoneNumber'];

  Map<String, dynamic> toJson() => {
    'displayName': displayName,
    'phoneNumber': phoneNumber,
  };

  @override
  String toString() {
    return 'Contact { name: $displayName, age: $phoneNumber}';
  }

}//class ends

A: Wait until a route is popped and then reload. Something like this:
RaisedButton(
  onPressed: () async {
    await Navigator.push(context, MaterialPageRoute(builder: (context) => Plugin1()));
    await loadSharedPrefs();
  },
...
),

See Return data from a screen for details.